@livekit/agents-plugin-anthropic 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@livekit/agents-plugin-anthropic",
3
+ "version": "1.0.0",
4
+ "description": "Anthropic plugin for LiveKit Node Agents",
5
+ "main": "dist/index.js",
6
+ "require": "dist/index.cjs",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ "import": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ },
13
+ "require": {
14
+ "types": "./dist/index.d.cts",
15
+ "default": "./dist/index.cjs"
16
+ }
17
+ },
18
+ "author": "LiveKit",
19
+ "type": "module",
20
+ "repository": "git@github.com:livekit/agents-js.git",
21
+ "license": "Apache-2.0",
22
+ "files": [
23
+ "dist",
24
+ "src",
25
+ "README.md"
26
+ ],
27
+ "devDependencies": {
28
+ "@livekit/rtc-node": "^0.13.30",
29
+ "@microsoft/api-extractor": "^7.35.0",
30
+ "tsup": "^8.3.5",
31
+ "typescript": "^5.0.0",
32
+ "zod": "^3.25.76 || ^4.1.8",
33
+ "@livekit/agents": "1.5.0",
34
+ "@livekit/agents-plugins-test": "1.5.0"
35
+ },
36
+ "dependencies": {
37
+ "@anthropic-ai/sdk": "^0.33.1"
38
+ },
39
+ "peerDependencies": {
40
+ "@livekit/rtc-node": "^0.13.30",
41
+ "@livekit/agents": "1.5.0"
42
+ },
43
+ "scripts": {
44
+ "build": "tsup --onSuccess \"pnpm build:types\"",
45
+ "build:types": "tsc --declaration --emitDeclarationOnly && node ../../scripts/copyDeclarationOutput.js",
46
+ "clean": "rm -rf dist",
47
+ "clean:build": "pnpm clean && pnpm build",
48
+ "lint": "eslint -f unix \"src/**/*.{ts,js}\"",
49
+ "api:check": "api-extractor run --typescript-compiler-folder ../../node_modules/typescript",
50
+ "api:update": "api-extractor run --local --typescript-compiler-folder ../../node_modules/typescript --verbose"
51
+ }
52
+ }
package/src/index.ts ADDED
@@ -0,0 +1,19 @@
1
+ // SPDX-FileCopyrightText: 2026 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import { Plugin } from '@livekit/agents';
5
+
6
+ export { LLM, LLMStream, type LLMOptions } from './llm.js';
7
+ export * from './models.js';
8
+
9
+ class AnthropicPlugin extends Plugin {
10
+ constructor() {
11
+ super({
12
+ title: 'anthropic',
13
+ version: __PACKAGE_VERSION__,
14
+ package: __PACKAGE_NAME__,
15
+ });
16
+ }
17
+ }
18
+
19
+ Plugin.registerPlugin(new AnthropicPlugin());
@@ -0,0 +1,317 @@
1
+ // SPDX-FileCopyrightText: 2026 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import type Anthropic from '@anthropic-ai/sdk';
5
+ import { llm } from '@livekit/agents';
6
+ import { describe, expect, it } from 'vitest';
7
+ import { z } from 'zod';
8
+ import { LLM } from './llm.js';
9
+
10
+ function messageStartEvent(): Anthropic.MessageStreamEvent {
11
+ return {
12
+ type: 'message_start',
13
+ message: {
14
+ id: 'msg_123',
15
+ usage: { input_tokens: 0, output_tokens: 0 },
16
+ },
17
+ } as Anthropic.MessageStreamEvent;
18
+ }
19
+
20
+ function textDeltaEvent(text: string): Anthropic.MessageStreamEvent {
21
+ return {
22
+ type: 'content_block_delta',
23
+ delta: { type: 'text_delta', text },
24
+ } as Anthropic.MessageStreamEvent;
25
+ }
26
+
27
+ async function collectTextFromEvents(
28
+ events: Anthropic.MessageStreamEvent[],
29
+ toolCtx?: llm.ToolContextLike,
30
+ ): Promise<string> {
31
+ const client = {
32
+ messages: {
33
+ create: async () =>
34
+ (async function* (): AsyncGenerator<Anthropic.MessageStreamEvent> {
35
+ yield* events;
36
+ })(),
37
+ },
38
+ } as unknown as Anthropic;
39
+ const anthropicLlm = new LLM({
40
+ apiKey: 'dummy',
41
+ client,
42
+ model: 'claude-3-5-sonnet-20241022',
43
+ });
44
+ const chatCtx = new llm.ChatContext();
45
+ chatCtx.addMessage({ role: 'user', content: 'Hello, world!' });
46
+
47
+ const stream = anthropicLlm.chat({ chatCtx, toolCtx });
48
+ const textChunks: string[] = [];
49
+ for await (const chunk of stream) {
50
+ if (chunk.delta?.content) {
51
+ textChunks.push(chunk.delta.content);
52
+ }
53
+ }
54
+ return textChunks.join('');
55
+ }
56
+
57
+ describe('Anthropic LLM', () => {
58
+ it('correctly maps ChatContext to Anthropic system and messages arrays', () => {
59
+ const anthropicLlm = new LLM({ apiKey: 'dummy', model: 'claude-3-5-sonnet-20241022' });
60
+
61
+ const chatCtx = new llm.ChatContext();
62
+ chatCtx.addMessage({
63
+ role: 'system',
64
+ content: 'You are a mock agent.',
65
+ });
66
+ chatCtx.addMessage({
67
+ role: 'user',
68
+ content: 'Hello, world!',
69
+ });
70
+
71
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
72
+ const { system, messages } = (anthropicLlm as any)._buildAnthropicContext(chatCtx);
73
+
74
+ // Assert that system prompts were correctly isolated
75
+ expect(system).toHaveLength(1);
76
+ expect(system[0].text).toBe('You are a mock agent.');
77
+
78
+ // Assert that strictly user messages ended up in the messages payload
79
+ expect(messages).toHaveLength(1);
80
+ expect(messages[0].role).toBe('user');
81
+ expect(messages[0].content).toBe('Hello, world!');
82
+ });
83
+
84
+ it('merges consecutive same-role messages', () => {
85
+ const anthropicLlm = new LLM({ apiKey: 'dummy', model: 'claude-3-5-sonnet-20241022' });
86
+
87
+ const chatCtx = new llm.ChatContext();
88
+ chatCtx.addMessage({ role: 'user', content: 'First message' });
89
+ chatCtx.addMessage({ role: 'user', content: 'Second message' });
90
+ chatCtx.addMessage({ role: 'assistant', content: 'Reply' });
91
+
92
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
93
+ const { messages } = (anthropicLlm as any)._buildAnthropicContext(chatCtx);
94
+
95
+ // Two user messages should be merged into one with array content, followed by a
96
+ // trailing dummy user turn for Claude 4.6+.
97
+ expect(messages).toHaveLength(3);
98
+ expect(messages[0].role).toBe('user');
99
+ expect(Array.isArray(messages[0].content)).toBe(true);
100
+ expect(messages[0].content).toHaveLength(2);
101
+ expect(messages[1].role).toBe('assistant');
102
+ expect(messages[2].role).toBe('user');
103
+ expect(messages[2].content).toEqual([{ type: 'text', text: '.' }]);
104
+ });
105
+
106
+ it('injects a dummy user message if conversation starts with assistant', () => {
107
+ const anthropicLlm = new LLM({ apiKey: 'dummy', model: 'claude-3-5-sonnet-20241022' });
108
+
109
+ const chatCtx = new llm.ChatContext();
110
+ chatCtx.addMessage({ role: 'system', content: 'System prompt' });
111
+ chatCtx.addMessage({ role: 'assistant', content: 'I start talking' });
112
+
113
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
114
+ const { messages } = (anthropicLlm as any)._buildAnthropicContext(chatCtx);
115
+
116
+ // Should have injected a dummy user message at the start
117
+ expect(messages[0].role).toBe('user');
118
+ expect(messages[0].content).toBe('(empty)');
119
+ expect(messages[1].role).toBe('assistant');
120
+ });
121
+
122
+ it('handles function_call and function_call_output items', () => {
123
+ const anthropicLlm = new LLM({ apiKey: 'dummy', model: 'claude-3-5-sonnet-20241022' });
124
+
125
+ const chatCtx = new llm.ChatContext();
126
+ chatCtx.addMessage({ role: 'user', content: 'What is the weather?' });
127
+
128
+ // Simulate a function call from the assistant
129
+ chatCtx.items.push(
130
+ new llm.FunctionCall({
131
+ callId: 'call_123',
132
+ name: 'get_weather',
133
+ args: '{"city":"London"}',
134
+ }),
135
+ );
136
+
137
+ // Simulate the tool result
138
+ chatCtx.items.push(
139
+ new llm.FunctionCallOutput({
140
+ callId: 'call_123',
141
+ name: 'get_weather',
142
+ output: '{"temp": 20}',
143
+ isError: false,
144
+ }),
145
+ );
146
+
147
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
148
+ const { messages } = (anthropicLlm as any)._buildAnthropicContext(chatCtx);
149
+
150
+ // user message, then assistant tool_use, then user tool_result
151
+ expect(messages).toHaveLength(3);
152
+ expect(messages[0].role).toBe('user');
153
+ expect(messages[1].role).toBe('assistant');
154
+ expect(Array.isArray(messages[1].content)).toBe(true);
155
+ expect(messages[1].content[0].type).toBe('tool_use');
156
+ expect(messages[1].content[0].id).toBe('call_123');
157
+ expect(messages[2].role).toBe('user');
158
+ expect(Array.isArray(messages[2].content)).toBe(true);
159
+ expect(messages[2].content[0].type).toBe('tool_result');
160
+ });
161
+
162
+ it('creates a fresh stream on retry', async () => {
163
+ let calls = 0;
164
+ const client = {
165
+ messages: {
166
+ create: async () => {
167
+ calls += 1;
168
+ if (calls === 1) {
169
+ throw new Error('transient connect failure');
170
+ }
171
+ return (async function* (): AsyncGenerator<Anthropic.MessageStreamEvent> {})();
172
+ },
173
+ },
174
+ } as unknown as Anthropic;
175
+ const anthropicLlm = new LLM({
176
+ apiKey: 'dummy',
177
+ client,
178
+ model: 'claude-3-5-sonnet-20241022',
179
+ });
180
+ anthropicLlm.on('error', () => {});
181
+ const chatCtx = new llm.ChatContext();
182
+ chatCtx.addMessage({ role: 'user', content: 'Hello, world!' });
183
+
184
+ const stream = anthropicLlm.chat({
185
+ chatCtx,
186
+ connOptions: { maxRetry: 1, retryIntervalMs: 0, timeoutMs: 1000 },
187
+ });
188
+ const chunks: llm.ChatChunk[] = [];
189
+ for await (const chunk of stream) {
190
+ chunks.push(chunk);
191
+ }
192
+
193
+ expect(calls).toBe(2);
194
+ expect(chunks.at(-1)?.usage).toEqual({
195
+ completionTokens: 0,
196
+ promptTokens: 0,
197
+ promptCachedTokens: 0,
198
+ totalTokens: 0,
199
+ });
200
+ });
201
+
202
+ it('sends function tool schemas from a real ToolContext', async () => {
203
+ let capturedParams: Anthropic.MessageCreateParamsStreaming | undefined;
204
+ const client = {
205
+ messages: {
206
+ create: async (params: Anthropic.MessageCreateParamsStreaming) => {
207
+ capturedParams = params;
208
+ return (async function* (): AsyncGenerator<Anthropic.MessageStreamEvent> {
209
+ yield messageStartEvent();
210
+ })();
211
+ },
212
+ },
213
+ } as unknown as Anthropic;
214
+ const anthropicLlm = new LLM({
215
+ apiKey: 'dummy',
216
+ client,
217
+ model: 'claude-3-5-sonnet-20241022',
218
+ });
219
+ const chatCtx = new llm.ChatContext();
220
+ chatCtx.addMessage({ role: 'user', content: 'What is the weather in Tokyo?' });
221
+
222
+ const toolCtx = llm.toToolContext({
223
+ getWeather: llm.tool({
224
+ description: 'Get the weather for a given location.',
225
+ parameters: z.object({ location: z.string() }),
226
+ execute: async () => 'sunny',
227
+ }),
228
+ });
229
+
230
+ const stream = anthropicLlm.chat({ chatCtx, toolCtx });
231
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
232
+ for await (const _ of stream) {
233
+ // drain
234
+ }
235
+
236
+ expect(capturedParams?.tools).toHaveLength(1);
237
+ const toolSchema = capturedParams!.tools![0] as Anthropic.Tool;
238
+ expect(toolSchema.name).toBe('getWeather');
239
+ expect(toolSchema.description).toBe('Get the weather for a given location.');
240
+ expect(toolSchema.input_schema.type).toBe('object');
241
+ expect(Object.keys(toolSchema.input_schema.properties ?? {})).toEqual(['location']);
242
+ });
243
+
244
+ it('does not emit an empty delta for a fully-filtered thinking block', async () => {
245
+ const client = {
246
+ messages: {
247
+ create: async () =>
248
+ (async function* (): AsyncGenerator<Anthropic.MessageStreamEvent> {
249
+ yield messageStartEvent();
250
+ yield textDeltaEvent('<thinking>only reasoning</thinking>');
251
+ })(),
252
+ },
253
+ } as unknown as Anthropic;
254
+ const anthropicLlm = new LLM({
255
+ apiKey: 'dummy',
256
+ client,
257
+ model: 'claude-3-5-sonnet-20241022',
258
+ });
259
+ const chatCtx = new llm.ChatContext();
260
+ chatCtx.addMessage({ role: 'user', content: 'Hello, world!' });
261
+
262
+ const stream = anthropicLlm.chat({ chatCtx, toolCtx: llm.ToolContext.empty() });
263
+ const contentChunks: string[] = [];
264
+ for await (const chunk of stream) {
265
+ if (chunk.delta?.content !== undefined) {
266
+ contentChunks.push(chunk.delta.content);
267
+ }
268
+ }
269
+
270
+ // The whole delta was a thinking block: nothing (not even '') is emitted.
271
+ expect(contentChunks).toEqual([]);
272
+ });
273
+
274
+ it('filters thinking blocks when tools are active', async () => {
275
+ const text = await collectTextFromEvents(
276
+ [
277
+ messageStartEvent(),
278
+ textDeltaEvent('<thinking>hidden'),
279
+ textDeltaEvent('still hidden</thinking>visible'),
280
+ ],
281
+ llm.ToolContext.empty(),
282
+ );
283
+
284
+ expect(text).toBe('visible');
285
+ });
286
+
287
+ it('does not filter thinking blocks without tools', async () => {
288
+ const text = await collectTextFromEvents([
289
+ messageStartEvent(),
290
+ textDeltaEvent('<thinking>visible without tools</thinking>'),
291
+ ]);
292
+
293
+ expect(text).toBe('<thinking>visible without tools</thinking>');
294
+ });
295
+
296
+ it('preserves text around same-delta thinking blocks', async () => {
297
+ const text = await collectTextFromEvents(
298
+ [messageStartEvent(), textDeltaEvent('before <thinking>hidden</thinking> after')],
299
+ llm.ToolContext.empty(),
300
+ );
301
+
302
+ expect(text).toBe('before after');
303
+ });
304
+
305
+ it('preserves text before split thinking blocks', async () => {
306
+ const text = await collectTextFromEvents(
307
+ [
308
+ messageStartEvent(),
309
+ textDeltaEvent('before <thinking>hidden'),
310
+ textDeltaEvent('still hidden</thinking> after'),
311
+ ],
312
+ llm.ToolContext.empty(),
313
+ );
314
+
315
+ expect(text).toBe('before after');
316
+ });
317
+ });