Skip to content
Snippets Groups Projects
Unverified Commit a9c6144e authored by Marcus Schiesser's avatar Marcus Schiesser Committed by GitHub
Browse files

feat: stream thinking tokens for claude 3.7 (#1679)

parent 3564244c
No related branches found
No related tags found
No related merge requests found
---
"@llamaindex/anthropic": patch
---
Stream thinking tokens
...@@ -2,7 +2,6 @@ import { Anthropic } from "@llamaindex/anthropic"; ...@@ -2,7 +2,6 @@ import { Anthropic } from "@llamaindex/anthropic";
(async () => { (async () => {
const anthropic = new Anthropic({ const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
model: "claude-3-7-sonnet", model: "claude-3-7-sonnet",
maxTokens: 20000, maxTokens: 20000,
additionalChatOptions: { additionalChatOptions: {
...@@ -20,6 +19,14 @@ import { Anthropic } from "@llamaindex/anthropic"; ...@@ -20,6 +19,14 @@ import { Anthropic } from "@llamaindex/anthropic";
"Are there an infinite number of prime numbers such that n mod 4 == 3?", "Are there an infinite number of prime numbers such that n mod 4 == 3?",
}, },
], ],
stream: true,
}); });
console.log(result.message); console.log("Thinking...");
for await (const chunk of result) {
if (chunk.delta) {
process.stdout.write(chunk.delta);
} else if (chunk.options?.thinking) {
process.stdout.write(chunk.options.thinking);
}
}
})(); })();
...@@ -133,6 +133,7 @@ export type AnthropicAdditionalChatOptions = Pick< ...@@ -133,6 +133,7 @@ export type AnthropicAdditionalChatOptions = Pick<
>; >;
export type AnthropicToolCallLLMMessageOptions = ToolCallLLMMessageOptions & { export type AnthropicToolCallLLMMessageOptions = ToolCallLLMMessageOptions & {
cache_control?: BetaCacheControlEphemeral | null; cache_control?: BetaCacheControlEphemeral | null;
thinking?: string | undefined;
}; };
export class Anthropic extends ToolCallLLM< export class Anthropic extends ToolCallLLM<
...@@ -504,20 +505,26 @@ export class Anthropic extends ToolCallLLM< ...@@ -504,20 +505,26 @@ export class Anthropic extends ToolCallLLM<
let idx_counter: number = 0; let idx_counter: number = 0;
for await (const part of stream) { for await (const part of stream) {
const content = const textContent =
part.type === "content_block_delta" part.type === "content_block_delta" && part.delta.type === "text_delta"
? part.delta.type === "text_delta" ? part.delta.text
? part.delta.text
: part.delta
: undefined; : undefined;
if (typeof content !== "string") continue; const thinking =
part.type === "content_block_delta" &&
part.delta.type === "thinking_delta"
? part.delta.thinking
: undefined;
if (!textContent && !thinking) continue;
idx_counter++; idx_counter++;
yield { yield {
raw: part, raw: part,
delta: content, delta: textContent ?? "",
options: {}, options: {
thinking: thinking,
},
}; };
} }
return; return;
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment