Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add chat cancel method #14

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,30 @@ try {
}
```

Alternatively the `Chat` instance has a method `cancelStream` which which allows equivalent functionality to the above without having to use the `cancel` property of the `onUpdate` callback. (This is useful if you want to have a way to cancel the stream from something removed for the details of handling the streams.)

```ts
import { createChat, CancelledCompletionError } from "completions";

const chat = createChat({
apiKey: OPENAI_API_KEY,
model: "gpt-3.5-turbo",
});

try {
const responsePromise = chat.sendMessage("continue sequence: a b c");
// in practice this would be linked to something external
chat.cancelStream();
await responsePromise;
} catch (error) {
if (error instanceof CancelledCompletion) {
console.log("cancelled");
}

throw error;
}
```

### Overriding API

If you want to use `completions` library against another API endpoint that is compatible with the official API, you can do so by passing `apiUrl` parameter:
Expand Down
8 changes: 8 additions & 0 deletions src/createChat.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,14 @@ test("cancel response", async () => {
},
})
);

const chatPromise = chat.sendMessage("continue sequence: a b c");
chat.cancelStream();
await assert.rejects(chatPromise);

// make sure that the chat still functions after cancelling
const response = await chat.sendMessage("continue sequence: a b c");
assert(response.content);
});

test("calls user defined function", async () => {
Expand Down
24 changes: 18 additions & 6 deletions src/createChat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ export type Chat = {
addMessage: (message: Message) => void;
getMessages: () => Message[];
sendMessage: SendMessage;
cancelStream: () => void;
};

/**
Expand Down Expand Up @@ -97,6 +98,7 @@ export const createChat = (
options: Omit<CompletionsOptions, "messages" | "n" | "onUpdate">
): Chat => {
const messages: Message[] = [];
const cancel = { cancelled: false };

const userFunctions: Record<string, UserFunction> = {};

Expand All @@ -106,12 +108,15 @@ export const createChat = (

const complete = async (messageOptions?: MessageOptions) => {
const response = await retry(() => {
return createCompletions({
messages,
onUpdate: messageOptions?.onUpdate,
...options,
...(messageOptions ? omit(messageOptions, "expect") : {}),
});
return createCompletions(
{
messages,
onUpdate: messageOptions?.onUpdate,
...options,
...(messageOptions ? omit(messageOptions, "expect") : {}),
},
cancel
);
});

if (!response) {
Expand Down Expand Up @@ -173,6 +178,8 @@ export const createChat = (
role: "user",
};

cancel.cancelled = false;

messages.push(message);

let choice = await complete(messageOptions);
Expand Down Expand Up @@ -218,9 +225,14 @@ export const createChat = (
messages.push(message);
};

const cancelStream = () => {
cancel.cancelled = true;
};

return {
addMessage,
getMessages: () => messages,
sendMessage,
cancelStream,
};
};
9 changes: 4 additions & 5 deletions src/createCompletions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,8 @@ export type CompletionResponse = {
};

export const createCompletions = async (
options: CompletionsOptions
options: CompletionsOptions,
cancel: { cancelled: boolean }
): Promise<CompletionResponse> => {
CompletionsOptionsZodSchema.parse(options);

Expand Down Expand Up @@ -208,8 +209,6 @@ export const createCompletions = async (

const choices: Choice[] = [];

let cancelled = false;

while (true) {
const { value, done } = await reader.read();

Expand Down Expand Up @@ -260,7 +259,7 @@ export const createCompletions = async (

options.onUpdate?.({
cancel: () => {
cancelled = true;
cancel.cancelled = true;

reader.cancel();
},
Expand Down Expand Up @@ -302,7 +301,7 @@ export const createCompletions = async (
}
}

if (cancelled) {
if (cancel.cancelled) {
throw new CancelledCompletionError(choices);
}

Expand Down