@namzu/anthropic 0.0.1

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.
package/src/client.ts ADDED
@@ -0,0 +1,531 @@
1
+ import Anthropic from '@anthropic-ai/sdk'
2
+ import type {
3
+ ChatCompletionParams,
4
+ ChatCompletionResponse,
5
+ LLMProvider,
6
+ ModelInfo,
7
+ StreamChunk,
8
+ TokenUsage,
9
+ ToolChoice,
10
+ } from '@namzu/sdk'
11
+ import type { AnthropicConfig } from './types.js'
12
+
13
+ const DEFAULT_MAX_TOKENS = 4096
14
+ const DEFAULT_TIMEOUT_MS = 120_000
15
+
16
+ // --------------------------------------------------------------------------------------
17
+ // Message translation: @namzu/sdk → Anthropic Messages API
18
+ // --------------------------------------------------------------------------------------
19
+
20
+ interface AnthropicTextBlock {
21
+ type: 'text'
22
+ text: string
23
+ }
24
+
25
+ interface AnthropicToolUseBlock {
26
+ type: 'tool_use'
27
+ id: string
28
+ name: string
29
+ input: unknown
30
+ }
31
+
32
+ interface AnthropicToolResultBlock {
33
+ type: 'tool_result'
34
+ tool_use_id: string
35
+ content: string
36
+ }
37
+
38
+ type AnthropicContentBlock = AnthropicTextBlock | AnthropicToolUseBlock | AnthropicToolResultBlock
39
+
40
+ interface AnthropicMessageParam {
41
+ role: 'user' | 'assistant'
42
+ content: string | AnthropicContentBlock[]
43
+ }
44
+
45
+ function extractSystem(messages: ChatCompletionParams['messages']): string | undefined {
46
+ const parts: string[] = []
47
+ for (const msg of messages) {
48
+ if (msg.role === 'system' && typeof msg.content === 'string') {
49
+ parts.push(msg.content)
50
+ }
51
+ }
52
+ return parts.length > 0 ? parts.join('\n\n') : undefined
53
+ }
54
+
55
+ function toAnthropicMessages(messages: ChatCompletionParams['messages']): AnthropicMessageParam[] {
56
+ const out: AnthropicMessageParam[] = []
57
+ let pendingToolResults: AnthropicToolResultBlock[] = []
58
+
59
+ const flushToolResults = () => {
60
+ if (pendingToolResults.length > 0) {
61
+ out.push({ role: 'user', content: pendingToolResults })
62
+ pendingToolResults = []
63
+ }
64
+ }
65
+
66
+ for (const msg of messages) {
67
+ if (msg.role === 'system') continue
68
+
69
+ if (msg.role === 'tool') {
70
+ const toolMsg = msg as { toolCallId?: string; content?: unknown }
71
+ pendingToolResults.push({
72
+ type: 'tool_result',
73
+ tool_use_id: toolMsg.toolCallId ?? 'unknown',
74
+ content:
75
+ typeof toolMsg.content === 'string' ? toolMsg.content : JSON.stringify(toolMsg.content),
76
+ })
77
+ continue
78
+ }
79
+
80
+ flushToolResults()
81
+
82
+ if (msg.role === 'assistant' && 'toolCalls' in msg && msg.toolCalls) {
83
+ const blocks: AnthropicContentBlock[] = []
84
+ if (msg.content && typeof msg.content === 'string') {
85
+ blocks.push({ type: 'text', text: msg.content })
86
+ }
87
+ for (const tc of msg.toolCalls) {
88
+ let parsedInput: unknown = {}
89
+ try {
90
+ parsedInput = JSON.parse(tc.function.arguments || '{}')
91
+ } catch {
92
+ parsedInput = {}
93
+ }
94
+ blocks.push({
95
+ type: 'tool_use',
96
+ id: tc.id,
97
+ name: tc.function.name,
98
+ input: parsedInput,
99
+ })
100
+ }
101
+ out.push({ role: 'assistant', content: blocks })
102
+ continue
103
+ }
104
+
105
+ const content = typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content)
106
+ out.push({
107
+ role: msg.role === 'assistant' ? 'assistant' : 'user',
108
+ content,
109
+ })
110
+ }
111
+
112
+ flushToolResults()
113
+ return out
114
+ }
115
+
116
+ function toAnthropicTools(params: ChatCompletionParams): unknown[] | undefined {
117
+ if (!params.tools || params.tools.length === 0) return undefined
118
+ return params.tools.map((t) => ({
119
+ name: t.function.name,
120
+ description: t.function.description ?? '',
121
+ input_schema: t.function.parameters ?? { type: 'object' },
122
+ }))
123
+ }
124
+
125
+ function toAnthropicToolChoice(tc?: ToolChoice): unknown {
126
+ if (tc === undefined) return undefined
127
+ if (tc === 'auto') return { type: 'auto' }
128
+ if (tc === 'required') return { type: 'any' }
129
+ // 'none' — Anthropic has no direct equivalent. Map to auto (omitting tools at call-site
130
+ // is the proper way to forbid tool use); we leave it as auto here for safety.
131
+ if (tc === 'none') return { type: 'auto' }
132
+ if (typeof tc === 'object' && tc.type === 'function') {
133
+ return { type: 'tool', name: tc.function.name }
134
+ }
135
+ return undefined
136
+ }
137
+
138
+ // --------------------------------------------------------------------------------------
139
+ // Usage parsing
140
+ // --------------------------------------------------------------------------------------
141
+
142
+ interface RawAnthropicUsage {
143
+ input_tokens?: number
144
+ output_tokens?: number
145
+ cache_read_input_tokens?: number | null
146
+ cache_creation_input_tokens?: number | null
147
+ }
148
+
149
+ function emptyUsage(): TokenUsage {
150
+ return {
151
+ promptTokens: 0,
152
+ completionTokens: 0,
153
+ totalTokens: 0,
154
+ cachedTokens: 0,
155
+ cacheWriteTokens: 0,
156
+ }
157
+ }
158
+
159
+ function parseUsage(raw?: RawAnthropicUsage): TokenUsage {
160
+ if (!raw) return emptyUsage()
161
+ const input = raw.input_tokens ?? 0
162
+ const output = raw.output_tokens ?? 0
163
+ return {
164
+ promptTokens: input,
165
+ completionTokens: output,
166
+ totalTokens: input + output,
167
+ cachedTokens: raw.cache_read_input_tokens ?? 0,
168
+ cacheWriteTokens: raw.cache_creation_input_tokens ?? 0,
169
+ }
170
+ }
171
+
172
+ // --------------------------------------------------------------------------------------
173
+ // Finish reason mapping
174
+ // --------------------------------------------------------------------------------------
175
+
176
+ type NamzuFinishReason = ChatCompletionResponse['finishReason']
177
+
178
+ function mapStopReason(reason?: string | null): NamzuFinishReason {
179
+ switch (reason) {
180
+ case 'end_turn':
181
+ case 'stop_sequence':
182
+ return 'stop'
183
+ case 'tool_use':
184
+ return 'tool_calls'
185
+ case 'max_tokens':
186
+ return 'length'
187
+ default:
188
+ return 'stop'
189
+ }
190
+ }
191
+
192
+ // --------------------------------------------------------------------------------------
193
+ // Response content extraction
194
+ // --------------------------------------------------------------------------------------
195
+
196
+ interface RawAnthropicResponseBlock {
197
+ type: string
198
+ text?: string
199
+ id?: string
200
+ name?: string
201
+ input?: unknown
202
+ }
203
+
204
+ function extractResponseContent(content?: RawAnthropicResponseBlock[]): {
205
+ text: string | null
206
+ toolCalls: ChatCompletionResponse['message']['toolCalls']
207
+ } {
208
+ if (!content || content.length === 0) return { text: null, toolCalls: undefined }
209
+
210
+ let text: string | null = null
211
+ const toolCalls: NonNullable<ChatCompletionResponse['message']['toolCalls']> = []
212
+
213
+ for (const block of content) {
214
+ if (block.type === 'text' && typeof block.text === 'string') {
215
+ text = (text ?? '') + block.text
216
+ } else if (block.type === 'tool_use') {
217
+ toolCalls.push({
218
+ id: block.id ?? `tool-${Date.now()}`,
219
+ type: 'function',
220
+ function: {
221
+ name: block.name ?? '',
222
+ arguments: JSON.stringify(block.input ?? {}),
223
+ },
224
+ })
225
+ }
226
+ }
227
+
228
+ return {
229
+ text,
230
+ toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
231
+ }
232
+ }
233
+
234
+ // --------------------------------------------------------------------------------------
235
+ // Stream event types
236
+ // --------------------------------------------------------------------------------------
237
+
238
+ interface StreamEvent {
239
+ type: string
240
+ message?: { id?: string; usage?: RawAnthropicUsage }
241
+ index?: number
242
+ content_block?: { type?: string; id?: string; name?: string }
243
+ delta?: {
244
+ type?: string
245
+ text?: string
246
+ partial_json?: string
247
+ stop_reason?: string | null
248
+ }
249
+ usage?: RawAnthropicUsage
250
+ }
251
+
252
+ // --------------------------------------------------------------------------------------
253
+ // AnthropicProvider
254
+ // --------------------------------------------------------------------------------------
255
+
256
+ export class AnthropicProvider implements LLMProvider {
257
+ readonly id = 'anthropic'
258
+ readonly name = 'Anthropic'
259
+
260
+ private client: Anthropic
261
+ private config: AnthropicConfig
262
+
263
+ constructor(config: AnthropicConfig) {
264
+ if (!config.apiKey) {
265
+ throw new Error('AnthropicProvider: apiKey is required')
266
+ }
267
+ this.config = config
268
+
269
+ const clientOpts: Record<string, unknown> = {
270
+ apiKey: config.apiKey,
271
+ timeout: config.timeout ?? DEFAULT_TIMEOUT_MS,
272
+ }
273
+ if (config.baseURL) clientOpts.baseURL = config.baseURL
274
+ if (config.defaultHeaders) clientOpts.defaultHeaders = config.defaultHeaders
275
+
276
+ this.client = new Anthropic(clientOpts)
277
+ }
278
+
279
+ private resolveModel(params: ChatCompletionParams): string {
280
+ const model = params.model || this.config.model
281
+ if (!model) {
282
+ throw new Error(
283
+ 'AnthropicProvider: no model specified. Pass `model` on the chat params or set a default via config.',
284
+ )
285
+ }
286
+ return model
287
+ }
288
+
289
+ private buildCreateParams(
290
+ params: ChatCompletionParams,
291
+ stream: boolean,
292
+ ): Record<string, unknown> {
293
+ const system = extractSystem(params.messages)
294
+ const messages = toAnthropicMessages(params.messages)
295
+ const tools = toAnthropicTools(params)
296
+ const toolChoice = toAnthropicToolChoice(params.toolChoice)
297
+
298
+ const body: Record<string, unknown> = {
299
+ model: this.resolveModel(params),
300
+ messages,
301
+ max_tokens: params.maxTokens ?? this.config.maxTokens ?? DEFAULT_MAX_TOKENS,
302
+ stream,
303
+ }
304
+
305
+ if (system) body.system = system
306
+ if (tools) body.tools = tools
307
+ if (toolChoice) body.tool_choice = toolChoice
308
+ if (params.temperature !== undefined) body.temperature = params.temperature
309
+ if (params.topP !== undefined) body.top_p = params.topP
310
+ if (params.topK !== undefined) body.top_k = params.topK
311
+ if (params.stop) body.stop_sequences = params.stop
312
+
313
+ return body
314
+ }
315
+
316
+ /**
317
+ * The SDK's `messages.create` is overloaded on the `stream` flag. We build
318
+ * the request as an untyped object bag and narrow the response shape ourselves.
319
+ * Casting via `unknown` keeps us out of `any` territory while acknowledging
320
+ * that the translation layer bridges two type worlds.
321
+ */
322
+ private createRaw(body: Record<string, unknown>): Promise<unknown> {
323
+ const create = this.client.messages.create as unknown as (
324
+ body: Record<string, unknown>,
325
+ ) => Promise<unknown>
326
+ return create.call(this.client.messages, body)
327
+ }
328
+
329
+ async chat(params: ChatCompletionParams): Promise<ChatCompletionResponse> {
330
+ const createParams = this.buildCreateParams(params, false)
331
+
332
+ const response = (await this.createRaw(createParams)) as {
333
+ id?: string
334
+ model?: string
335
+ content: RawAnthropicResponseBlock[]
336
+ stop_reason?: string | null
337
+ usage?: RawAnthropicUsage
338
+ }
339
+
340
+ const { text, toolCalls } = extractResponseContent(response.content)
341
+
342
+ return {
343
+ id: response.id ?? `anthropic-${Date.now()}`,
344
+ model: response.model ?? this.resolveModel(params),
345
+ message: {
346
+ role: 'assistant',
347
+ content: text,
348
+ toolCalls,
349
+ },
350
+ finishReason: mapStopReason(response.stop_reason),
351
+ usage: parseUsage(response.usage),
352
+ }
353
+ }
354
+
355
+ async *chatStream(params: ChatCompletionParams): AsyncIterable<StreamChunk> {
356
+ const createParams = this.buildCreateParams(params, true)
357
+
358
+ const stream = (await this.createRaw(createParams)) as AsyncIterable<StreamEvent>
359
+
360
+ let messageId = ''
361
+ // Track active tool-use blocks by content_block index so input_json_delta
362
+ // fragments can reference the right tool call.
363
+ const activeTools = new Map<number, { id: string; name: string }>()
364
+
365
+ for await (const event of stream) {
366
+ try {
367
+ switch (event.type) {
368
+ case 'message_start': {
369
+ if (event.message?.id) messageId = event.message.id
370
+ if (event.message?.usage) {
371
+ yield {
372
+ id: messageId,
373
+ delta: {},
374
+ usage: parseUsage(event.message.usage),
375
+ }
376
+ }
377
+ break
378
+ }
379
+ case 'content_block_start': {
380
+ const idx = event.index ?? 0
381
+ const block = event.content_block
382
+ if (block?.type === 'tool_use') {
383
+ const toolId = block.id ?? `tool-${Date.now()}`
384
+ activeTools.set(idx, { id: toolId, name: block.name ?? '' })
385
+ yield {
386
+ id: messageId,
387
+ delta: {
388
+ toolCalls: [
389
+ {
390
+ index: idx,
391
+ id: toolId,
392
+ type: 'function',
393
+ function: { name: block.name ?? '' },
394
+ },
395
+ ],
396
+ },
397
+ }
398
+ }
399
+ break
400
+ }
401
+ case 'content_block_delta': {
402
+ const idx = event.index ?? 0
403
+ const delta = event.delta
404
+ if (delta?.type === 'text_delta' && delta.text) {
405
+ yield { id: messageId, delta: { content: delta.text } }
406
+ } else if (delta?.type === 'input_json_delta' && delta.partial_json !== undefined) {
407
+ const active = activeTools.get(idx)
408
+ yield {
409
+ id: messageId,
410
+ delta: {
411
+ toolCalls: [
412
+ {
413
+ index: idx,
414
+ id: active?.id,
415
+ function: { arguments: delta.partial_json },
416
+ },
417
+ ],
418
+ },
419
+ }
420
+ }
421
+ break
422
+ }
423
+ case 'content_block_stop':
424
+ // Aggregation is consumer-side — nothing to emit.
425
+ break
426
+ case 'message_delta': {
427
+ if (event.delta?.stop_reason) {
428
+ yield {
429
+ id: messageId,
430
+ delta: {},
431
+ finishReason: mapStopReason(event.delta.stop_reason),
432
+ usage: event.usage ? parseUsage(event.usage) : undefined,
433
+ }
434
+ } else if (event.usage) {
435
+ yield {
436
+ id: messageId,
437
+ delta: {},
438
+ usage: parseUsage(event.usage),
439
+ }
440
+ }
441
+ break
442
+ }
443
+ case 'message_stop':
444
+ return
445
+ default:
446
+ // Ignore unknown / ping / opaque events.
447
+ break
448
+ }
449
+ } catch (parseErr) {
450
+ yield {
451
+ id: messageId,
452
+ delta: {},
453
+ error: `Stream event error: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`,
454
+ }
455
+ }
456
+ }
457
+ }
458
+
459
+ async listModels(): Promise<ModelInfo[]> {
460
+ try {
461
+ // Models API shipped in SDK ~0.32+. Feature-detect via unknown cast so we
462
+ // don't depend on the SDK's surface-level shape in a version-brittle way.
463
+ const clientLike = this.client as unknown as {
464
+ models?: { list?: (opts: { limit: number }) => Promise<unknown> }
465
+ }
466
+ const listFn = clientLike.models?.list
467
+ if (typeof listFn !== 'function') {
468
+ return this.knownModels()
469
+ }
470
+ const page = (await listFn({ limit: 100 })) as {
471
+ data?: Array<{ id?: string; display_name?: string; type?: string }>
472
+ }
473
+ const data = page?.data ?? []
474
+ if (data.length === 0) return this.knownModels()
475
+ return data.map((m) => ({
476
+ id: m.id ?? '',
477
+ name: m.display_name ?? m.id ?? '',
478
+ contextWindow: 0,
479
+ maxOutputTokens: 0,
480
+ inputPrice: 0,
481
+ outputPrice: 0,
482
+ supportsToolUse: true,
483
+ supportsStreaming: true,
484
+ }))
485
+ } catch {
486
+ return this.knownModels()
487
+ }
488
+ }
489
+
490
+ private knownModels(): ModelInfo[] {
491
+ return [
492
+ {
493
+ id: 'claude-sonnet-4-5-20250929',
494
+ name: 'Claude Sonnet 4.5',
495
+ contextWindow: 200_000,
496
+ maxOutputTokens: 64_000,
497
+ inputPrice: 3.0,
498
+ outputPrice: 15.0,
499
+ supportsToolUse: true,
500
+ supportsStreaming: true,
501
+ },
502
+ {
503
+ id: 'claude-opus-4-1-20250805',
504
+ name: 'Claude Opus 4.1',
505
+ contextWindow: 200_000,
506
+ maxOutputTokens: 32_000,
507
+ inputPrice: 15.0,
508
+ outputPrice: 75.0,
509
+ supportsToolUse: true,
510
+ supportsStreaming: true,
511
+ },
512
+ {
513
+ id: 'claude-haiku-4-5-20251001',
514
+ name: 'Claude Haiku 4.5',
515
+ contextWindow: 200_000,
516
+ maxOutputTokens: 64_000,
517
+ inputPrice: 1.0,
518
+ outputPrice: 5.0,
519
+ supportsToolUse: true,
520
+ supportsStreaming: true,
521
+ },
522
+ ]
523
+ }
524
+
525
+ async healthCheck(): Promise<boolean> {
526
+ // The client constructor validates the apiKey shape lazily. A no-op
527
+ // check is sufficient here — a real request costs tokens. Callers that
528
+ // want network-level verification should call `chat()` directly.
529
+ return Boolean(this.client) && Boolean(this.config.apiKey)
530
+ }
531
+ }
package/src/index.ts ADDED
@@ -0,0 +1,32 @@
1
+ import { type ProviderCapabilities, ProviderRegistry, type RegisterOptions } from '@namzu/sdk'
2
+ import { AnthropicProvider } from './client.js'
3
+ import type { AnthropicProviderConfig } from './types.js'
4
+
5
+ // Module augmentation: register anthropic's config type in the sdk's registry interface.
6
+ // This must live inside index.ts (not a .d.ts) so it executes when index.ts is imported.
7
+ declare module '@namzu/sdk' {
8
+ interface ProviderConfigRegistry {
9
+ anthropic: AnthropicProviderConfig
10
+ }
11
+ }
12
+
13
+ export const ANTHROPIC_CAPABILITIES: ProviderCapabilities = {
14
+ supportsTools: true,
15
+ supportsStreaming: true,
16
+ supportsFunctionCalling: true,
17
+ }
18
+
19
+ /**
20
+ * Register `AnthropicProvider` under the `'anthropic'` type in `@namzu/sdk`'s
21
+ * `ProviderRegistry`. Call once at app startup before
22
+ * `ProviderRegistry.create({ type: 'anthropic', ... })`.
23
+ *
24
+ * Throws `DuplicateProviderError` if `'anthropic'` is already registered.
25
+ * Pass `{ replace: true }` to override.
26
+ */
27
+ export function registerAnthropic(options?: RegisterOptions): void {
28
+ ProviderRegistry.register('anthropic', AnthropicProvider, ANTHROPIC_CAPABILITIES, options)
29
+ }
30
+
31
+ export { AnthropicProvider } from './client.js'
32
+ export type { AnthropicConfig, AnthropicProviderConfig } from './types.js'
package/src/types.ts ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Anthropic-specific provider config shapes.
3
+ *
4
+ * `AnthropicConfig` is the constructor input for `AnthropicProvider`.
5
+ * `AnthropicProviderConfig` is the shape the consumer passes to
6
+ * `ProviderRegistry.create({ type: 'anthropic', ... })` — it extends
7
+ * `AnthropicConfig` with the `type: 'anthropic'` discriminator.
8
+ */
9
+
10
+ export interface AnthropicConfig {
11
+ apiKey: string
12
+ /** Default model. Can be overridden per-call. */
13
+ model?: string
14
+ /** Override base URL (e.g. for AWS Bedrock Anthropic or Google Vertex endpoints — though use @namzu/bedrock for those). */
15
+ baseURL?: string
16
+ /** Request timeout in ms. */
17
+ timeout?: number
18
+ /** Custom headers appended to every request. */
19
+ defaultHeaders?: Record<string, string>
20
+ /** Default max_tokens (Anthropic requires this field). Default: 4096. */
21
+ maxTokens?: number
22
+ }
23
+
24
+ export interface AnthropicProviderConfig extends AnthropicConfig {
25
+ type: 'anthropic'
26
+ }