diff --git a/examples/cancellation.ts b/examples/cancellation.ts new file mode 100644 index 00000000..57d68e99 --- /dev/null +++ b/examples/cancellation.ts @@ -0,0 +1,52 @@ +import "dotenv/config"; +import { AI_PROMPT, Client, HUMAN_PROMPT } from "../src"; + +const apiKey = process.env.ANTHROPIC_API_KEY; +if (!apiKey) { + throw new Error("The ANTHROPIC_API_KEY environment variable must be set"); +} + +const client = new Client(apiKey); +const abortController = new AbortController(); + +client + .complete( + { + prompt: `${HUMAN_PROMPT} How many toes do dogs have?${AI_PROMPT}`, + stop_sequences: [HUMAN_PROMPT], + max_tokens_to_sample: 200, + model: "claude-v1", + }, + { signal: abortController.signal } + ) + .catch((error) => { + if (error.name === "AbortError") { + console.log("Cancelled complete()"); + } + }); + +client + .completeStream( + { + prompt: `${HUMAN_PROMPT} How many toes do dogs have?${AI_PROMPT}`, + stop_sequences: [HUMAN_PROMPT], + max_tokens_to_sample: 200, + model: "claude-v1", + }, + { + onOpen: (response) => { + console.log("Opened stream, HTTP status code", response.status); + }, + onUpdate: (completion) => { + console.log(completion.completion); + }, + signal: abortController.signal, + } + ) + .catch((error) => { + if (error.name === "AbortError") { + console.log("Cancelled completeStream()"); + } + }); + +abortController.abort(); diff --git a/package.json b/package.json index 4cc40869..8f5f6f7a 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,8 @@ "lint": "eslint src && prettier --check .", "format": "prettier --write .", "example:basic_stream": "tsc --build && node ./build/examples/basic_stream.js", - "example:basic_sync": "tsc --build && node ./build/examples/basic_sync.js" + "example:basic_sync": "tsc --build && node ./build/examples/basic_sync.js", + "example:cancellation": "tsc --build && node ./build/examples/cancellation.js" }, "dependencies": { "@fortaine/fetch-event-source": "^3.0.6",