|
| 1 | +/** |
| 2 | + * Copilot Runtime adapter for Anthropic. |
| 3 | + * |
| 4 | + * ## Example |
| 5 | + * |
| 6 | + * ```ts |
| 7 | + * import { CopilotRuntime, AnthropicAdapter } from "@copilotkit/runtime"; |
| 8 | + * import Anthropic from "@anthropic-ai/sdk"; |
| 9 | + * |
| 10 | + * const copilotKit = new CopilotRuntime(); |
| 11 | + * |
| 12 | + * const anthropic = new Anthropic({ |
| 13 | + * apiKey: "<your-api-key>", |
| 14 | + * }); |
| 15 | + * |
| 16 | + * const serviceAdapter = new AnthropicAdapter({ anthropic }); |
| 17 | + * |
| 18 | + * return copilotKit.streamHttpServerResponse(req, res, serviceAdapter); |
| 19 | + * ``` |
| 20 | + */ |
| 21 | +import Anthropic from "@anthropic-ai/sdk"; |
| 22 | +import { |
| 23 | + CopilotServiceAdapter, |
| 24 | + CopilotRuntimeChatCompletionRequest, |
| 25 | + CopilotRuntimeChatCompletionResponse, |
| 26 | +} from "../service-adapter"; |
| 27 | +import { |
| 28 | + convertActionInputToAnthropicTool, |
| 29 | + convertMessageToAnthropicMessage, |
| 30 | + groupAnthropicMessagesByRole, |
| 31 | + limitMessagesToTokenCount, |
| 32 | +} from "./utils"; |
| 33 | + |
| 34 | +import { randomId } from "@copilotkit/shared"; |
| 35 | +import { TextMessage } from "../../graphql/types/converted"; |
| 36 | + |
| 37 | +const DEFAULT_MODEL = "claude-3-opus-20240229"; |
| 38 | + |
| 39 | +export interface AnthropicAdapterParams { |
| 40 | + /** |
| 41 | + * An optional Anthropic instance to use. If not provided, a new instance will be |
| 42 | + * created. |
| 43 | + */ |
| 44 | + anthropic?: Anthropic; |
| 45 | + |
| 46 | + /** |
| 47 | + * The model to use. |
| 48 | + */ |
| 49 | + model?: string; |
| 50 | +} |
| 51 | + |
| 52 | +export class AnthropicAdapter implements CopilotServiceAdapter { |
| 53 | + private model: string = DEFAULT_MODEL; |
| 54 | + |
| 55 | + private _anthropic: Anthropic; |
| 56 | + public get anthropic(): Anthropic { |
| 57 | + return this._anthropic; |
| 58 | + } |
| 59 | + |
| 60 | + constructor(params?: AnthropicAdapterParams) { |
| 61 | + this._anthropic = params?.anthropic || new Anthropic({}); |
| 62 | + if (params?.model) { |
| 63 | + this.model = params.model; |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + async process( |
| 68 | + request: CopilotRuntimeChatCompletionRequest, |
| 69 | + ): Promise<CopilotRuntimeChatCompletionResponse> { |
| 70 | + const { |
| 71 | + threadId, |
| 72 | + model = this.model, |
| 73 | + messages: rawMessages, |
| 74 | + actions, |
| 75 | + eventSource, |
| 76 | + forwardedParameters, |
| 77 | + } = request; |
| 78 | + const tools = actions.map(convertActionInputToAnthropicTool); |
| 79 | + |
| 80 | + const messages = [...rawMessages]; |
| 81 | + |
| 82 | + // get the instruction message |
| 83 | + const instructionsMessage = messages.shift(); |
| 84 | + const instructions = |
| 85 | + instructionsMessage instanceof TextMessage ? instructionsMessage.content : ""; |
| 86 | + |
| 87 | + let anthropicMessages = messages.map(convertMessageToAnthropicMessage); |
| 88 | + anthropicMessages = limitMessagesToTokenCount(anthropicMessages, tools, model); |
| 89 | + anthropicMessages = groupAnthropicMessagesByRole(anthropicMessages); |
| 90 | + |
| 91 | + let toolChoice: any = forwardedParameters?.toolChoice; |
| 92 | + if (forwardedParameters?.toolChoice === "function") { |
| 93 | + toolChoice = { |
| 94 | + type: "tool", |
| 95 | + name: forwardedParameters.toolChoiceFunctionName, |
| 96 | + }; |
| 97 | + } |
| 98 | + |
| 99 | + const stream = this.anthropic.messages.create({ |
| 100 | + system: instructions, |
| 101 | + model: this.model, |
| 102 | + messages: anthropicMessages, |
| 103 | + max_tokens: forwardedParameters?.maxTokens || 1024, |
| 104 | + ...(tools.length > 0 && { tools }), |
| 105 | + ...(toolChoice && { tool_choice: toolChoice }), |
| 106 | + stream: true, |
| 107 | + }); |
| 108 | + |
| 109 | + eventSource.stream(async (eventStream$) => { |
| 110 | + let mode: "function" | "message" | null = null; |
| 111 | + let didOutputText = false; |
| 112 | + let currentMessageId = randomId(); |
| 113 | + let currentToolCallId = randomId(); |
| 114 | + let filterThinkingTextBuffer = new FilterThinkingTextBuffer(); |
| 115 | + |
| 116 | + for await (const chunk of await stream) { |
| 117 | + if (chunk.type === "message_start") { |
| 118 | + currentMessageId = chunk.message.id; |
| 119 | + } else if (chunk.type === "content_block_start") { |
| 120 | + if (chunk.content_block.type === "text") { |
| 121 | + didOutputText = false; |
| 122 | + filterThinkingTextBuffer.reset(); |
| 123 | + mode = "message"; |
| 124 | + } else if (chunk.content_block.type === "tool_use") { |
| 125 | + currentToolCallId = chunk.content_block.id; |
| 126 | + eventStream$.sendActionExecutionStart(currentToolCallId, chunk.content_block.name); |
| 127 | + mode = "function"; |
| 128 | + } |
| 129 | + } else if (chunk.type === "content_block_delta") { |
| 130 | + if (chunk.delta.type === "text_delta") { |
| 131 | + const text = filterThinkingTextBuffer.onTextChunk(chunk.delta.text); |
| 132 | + if (text.length > 0) { |
| 133 | + if (!didOutputText) { |
| 134 | + eventStream$.sendTextMessageStart(currentMessageId); |
| 135 | + didOutputText = true; |
| 136 | + } |
| 137 | + eventStream$.sendTextMessageContent(text); |
| 138 | + } |
| 139 | + } else if (chunk.delta.type === "input_json_delta") { |
| 140 | + eventStream$.sendActionExecutionArgs(chunk.delta.partial_json); |
| 141 | + } |
| 142 | + } else if (chunk.type === "content_block_stop") { |
| 143 | + if (mode === "message") { |
| 144 | + if (didOutputText) { |
| 145 | + eventStream$.sendTextMessageEnd(); |
| 146 | + } |
| 147 | + } else if (mode === "function") { |
| 148 | + eventStream$.sendActionExecutionEnd(); |
| 149 | + } |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + eventStream$.complete(); |
| 154 | + }); |
| 155 | + |
| 156 | + return { |
| 157 | + threadId: threadId || randomId(), |
| 158 | + }; |
| 159 | + } |
| 160 | +} |
| 161 | + |
| 162 | +const THINKING_TAG = "<thinking>"; |
| 163 | +const THINKING_TAG_END = "</thinking>"; |
| 164 | + |
| 165 | +class FilterThinkingTextBuffer { |
| 166 | + private buffer: string; |
| 167 | + private didFilterThinkingTag: boolean = false; |
| 168 | + |
| 169 | + constructor() { |
| 170 | + this.buffer = ""; |
| 171 | + } |
| 172 | + |
| 173 | + onTextChunk(text: string): string { |
| 174 | + this.buffer += text; |
| 175 | + if (this.didFilterThinkingTag) { |
| 176 | + return text; |
| 177 | + } |
| 178 | + const potentialTag = this.buffer.slice(0, THINKING_TAG.length); |
| 179 | + if (THINKING_TAG.startsWith(potentialTag)) { |
| 180 | + if (this.buffer.includes(THINKING_TAG_END)) { |
| 181 | + const end = this.buffer.indexOf(THINKING_TAG_END); |
| 182 | + const filteredText = this.buffer.slice(end + THINKING_TAG_END.length); |
| 183 | + this.buffer = filteredText; |
| 184 | + this.didFilterThinkingTag = true; |
| 185 | + return filteredText; |
| 186 | + } else { |
| 187 | + return ""; |
| 188 | + } |
| 189 | + } |
| 190 | + return text; |
| 191 | + } |
| 192 | + |
| 193 | + reset() { |
| 194 | + this.buffer = ""; |
| 195 | + this.didFilterThinkingTag = false; |
| 196 | + } |
| 197 | +} |
0 commit comments