-
Notifications
You must be signed in to change notification settings - Fork 86
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #13 from anthropics/justin/cancellation
Add cancellation support using AbortController/AbortSignal
- Loading branch information
Showing
3 changed files
with
75 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters