@adminforth/completion-adapter-anthropic-messages 1.1.0 → 1.2.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/index.ts CHANGED
@@ -1,344 +1,50 @@
1
1
  import type { AdapterOptions } from "./types.js";
2
2
  import type {
3
3
  CompletionAdapter,
4
- CompletionStreamEvent,
5
4
  CompletionTool,
6
5
  } from "adminforth";
7
- import { ChatAnthropic } from "@langchain/anthropic";
8
- import Anthropic from "@anthropic-ai/sdk";
9
- import { jsonSchemaOutputFormat } from "@anthropic-ai/sdk/helpers/json-schema";
6
+ import {
7
+ AnthropicMessagesService,
8
+ type CompletionRequestInput,
9
+ type CompletionResult,
10
+ type ReasoningEffort,
11
+ type StreamChunkCallback,
12
+ } from "./anthropic.js";
13
+ import {
14
+ createLangChainAgentSpec,
15
+ type AgentModelPurpose,
16
+ } from "./langchain.js";
10
17
 
11
18
  export type { AdapterOptions } from "./types.js";
12
19
 
13
- type StreamChunkCallback = (
14
- chunk: string,
15
- event?: CompletionStreamEvent,
16
- ) => void | Promise<void>;
17
-
18
- type ReasoningEffort =
19
- | "none"
20
- | "minimal"
21
- | "low"
22
- | "medium"
23
- | "high"
24
- | "xhigh";
25
-
26
- type AgentModelPurpose = "primary" | "summary";
27
-
28
- type CompletionRequestInput = {
29
- content: string;
30
- maxTokens?: number;
31
- outputSchema?: any;
32
- reasoningEffort?: ReasoningEffort;
33
- tools?: CompletionTool[];
34
- onChunk?: StreamChunkCallback;
35
- };
36
-
37
- type JsonSchemaObject = {
38
- type: "object";
39
- [key: string]: unknown;
40
- };
41
-
42
- type AnthropicMessageLike = {
43
- content?: Array<any>;
44
- stop_reason?: string | null;
45
- parsed_output?: unknown;
46
- usage?: AnthropicUsage;
47
- };
48
-
49
- type AnthropicToolUseBlock = {
50
- type: "tool_use";
51
- id: string;
52
- name: string;
53
- input: unknown;
54
- };
55
-
56
- type LangChainMessageLike = {
57
- content?: unknown;
58
- text?: string;
59
- type?: string;
60
- getType?: () => string;
61
- _getType?: () => string;
62
- };
63
-
64
- type LangChainModelCallRequest = {
65
- systemMessage: LangChainMessageLike & {
66
- concat: (content: string) => LangChainMessageLike;
67
- };
68
- messages: LangChainMessageLike[];
69
- };
70
-
71
- type AnthropicUsage = {
72
- input_tokens?: number;
73
- cache_creation_input_tokens?: number | null;
74
- cache_read_input_tokens?: number | null;
75
- output_tokens?: number;
76
- };
77
-
78
- type UsedTokens = {
79
- input_uncached: number;
80
- input_cached: number;
81
- output: number;
82
- };
83
-
84
- function getApiKey(options: AdapterOptions): string | undefined {
85
- return options.anthropicApiKey || options.antropicApiKey;
86
- }
87
-
88
- function getErrorMessage(error: unknown): string {
89
- if (error instanceof Error && error.message) return error.message;
90
- return String(error || "Unknown error");
91
- }
92
-
93
- function normalizeOutputSchema(outputSchema: any): JsonSchemaObject | undefined {
94
- if (!outputSchema || typeof outputSchema !== "object") return undefined;
95
- const candidate = outputSchema.schema || outputSchema.json_schema || outputSchema;
96
- if (!candidate || typeof candidate !== "object") {
97
- return undefined;
98
- }
99
- if (candidate.type !== "object") {
100
- return undefined;
101
- }
102
- return candidate as JsonSchemaObject;
103
- }
104
-
105
- function extractOutputText(data: AnthropicMessageLike): string {
106
- let text = "";
107
-
108
- for (const block of data.content ?? []) {
109
- if (block?.type === "text" && typeof block.text === "string") {
110
- text += block.text;
111
- }
112
- }
113
-
114
- return text;
115
- }
116
-
117
- function extractReasoning(data: AnthropicMessageLike): string | undefined {
118
- let reasoning = "";
119
-
120
- for (const block of data.content ?? []) {
121
- if (block?.type === "thinking" && typeof block.thinking === "string") {
122
- reasoning += block.thinking;
123
- }
124
- }
125
-
126
- return reasoning || undefined;
127
- }
128
-
129
- function extractUsedTokens(data: AnthropicMessageLike): UsedTokens | undefined {
130
- const usage = data.usage;
131
- if (!usage) return undefined;
132
-
133
- const inputTokens = usage.input_tokens ?? 0;
134
- const cacheWriteTokens = usage.cache_creation_input_tokens ?? 0;
135
- const cacheReadTokens = usage.cache_read_input_tokens ?? 0;
136
-
137
- return {
138
- input_uncached: inputTokens + cacheWriteTokens,
139
- input_cached: cacheReadTokens,
140
- output: usage.output_tokens ?? 0,
141
- };
142
- }
143
-
144
- function extractToolUse(data: AnthropicMessageLike): AnthropicToolUseBlock | undefined {
145
- for (const block of data.content ?? []) {
146
- if (block?.type === "tool_use") {
147
- return block as AnthropicToolUseBlock;
148
- }
149
- }
150
-
151
- return undefined;
152
- }
153
-
154
- function stringifyToolResult(toolResult: unknown): string {
155
- if (typeof toolResult === "string") return toolResult;
156
- if (typeof toolResult === "undefined") return "";
157
- return JSON.stringify(toolResult);
158
- }
159
-
160
- async function executeToolCall(
161
- toolCall: AnthropicToolUseBlock,
162
- tools?: CompletionTool[],
163
- ): Promise<string> {
164
- const tool = tools?.find((candidate) => candidate.name === toolCall.name);
165
- if (!tool) {
166
- throw new Error(`Tool "${toolCall.name}" not found`);
167
- }
168
-
169
- const toolResult = await tool.handler(toolCall.input || {});
170
- return stringifyToolResult(toolResult);
171
- }
172
-
173
- function mapTools(tools?: CompletionTool[]) {
174
- if (!tools?.length) return undefined;
175
- return tools.map((tool) => ({
176
- name: tool.name,
177
- description: tool.description,
178
- input_schema: tool.input_schema,
179
- }));
180
- }
181
-
182
- function mapReasoningToThinking(
183
- reasoningEffort: ReasoningEffort,
184
- maxTokens: number,
185
- ): { type: "enabled"; budget_tokens: number } | undefined {
186
- if (reasoningEffort === "none") return undefined;
187
-
188
- const availableBudget = maxTokens - 128;
189
- if (availableBudget < 1024) return undefined;
190
-
191
- const ratioByEffort: Record<Exclude<ReasoningEffort, "none">, number> = {
192
- minimal: 0.25,
193
- low: 0.35,
194
- medium: 0.5,
195
- high: 0.7,
196
- xhigh: 0.85,
197
- };
198
- const targetBudget = Math.floor(maxTokens * ratioByEffort[reasoningEffort]);
199
-
200
- return {
201
- type: "enabled",
202
- budget_tokens: Math.max(1024, Math.min(availableBudget, targetBudget)),
203
- };
204
- }
205
-
206
- function getAgentReasoningEffort(
207
- purpose: AgentModelPurpose,
208
- ): ReasoningEffort {
209
- return purpose === "summary" ? "minimal" : "low";
210
- }
211
-
212
- function isSystemMessage(message: LangChainMessageLike): boolean {
213
- return (
214
- message._getType?.() === "system" ||
215
- message.getType?.() === "system" ||
216
- message.type === "system"
217
- );
218
- }
219
-
220
- function contentToText(content: unknown, text?: string): string {
221
- if (text) return text;
222
- if (typeof content === "string") return content;
223
- if (!Array.isArray(content)) return "";
224
-
225
- return content
226
- .map((block) => {
227
- if (typeof block === "string") return block;
228
- if (block && typeof block === "object" && "text" in block) {
229
- return String(block.text ?? "");
230
- }
231
- return "";
232
- })
233
- .join("");
234
- }
235
-
236
- function normalizeAnthropicSystemMessages<T extends LangChainModelCallRequest>(
237
- request: T,
238
- ): T {
239
- const existingSystemText = contentToText(
240
- request.systemMessage.content,
241
- request.systemMessage.text,
242
- );
243
- const extraSystemText = request.messages
244
- .filter(isSystemMessage)
245
- .map((message) => contentToText(message.content, message.text))
246
- .filter((text) => text && text !== existingSystemText)
247
- .join("\n\n");
248
-
249
- if (!extraSystemText) {
250
- return {
251
- ...request,
252
- messages: request.messages.filter((message) => !isSystemMessage(message)),
253
- };
254
- }
255
-
256
- const systemMessage = request.systemMessage.concat(extraSystemText);
257
-
258
- return {
259
- ...request,
260
- systemMessage,
261
- messages: request.messages.filter((message) => !isSystemMessage(message)),
262
- };
263
- }
264
-
265
- function createAnthropicSystemMessageMiddleware() {
266
- return {
267
- name: "AnthropicSystemMessageMiddleware",
268
- async wrapModelCall(
269
- request: LangChainModelCallRequest,
270
- handler: (request: LangChainModelCallRequest) => unknown,
271
- ) {
272
- return handler(normalizeAnthropicSystemMessages(request));
273
- },
274
- };
275
- }
276
-
277
- export default class CompletionAdapterAnthropicMessages
20
+ class CompletionAdapterAnthropicMessages
278
21
  implements CompletionAdapter
279
22
  {
280
23
  options: AdapterOptions;
281
- private client?: Anthropic;
24
+ private anthropic: AnthropicMessagesService;
282
25
 
283
26
  constructor(options: AdapterOptions) {
284
27
  this.options = options;
285
- }
286
-
287
- private getClient(): Anthropic {
288
- if (!this.client) {
289
- const apiKey = getApiKey(this.options);
290
- if (!apiKey) {
291
- throw new Error("anthropicApiKey is required");
292
- }
293
- this.client = new Anthropic({ apiKey });
294
- }
295
-
296
- return this.client;
28
+ this.anthropic = new AnthropicMessagesService(options);
297
29
  }
298
30
 
299
31
  validate() {
300
- if (!getApiKey(this.options)) {
301
- throw new Error("anthropicApiKey is required");
302
- }
32
+ this.anthropic.validate();
303
33
  }
304
34
 
305
- async measureTokensCount(content: string): Promise<number> {
306
- const response = await this.getClient().messages.countTokens({
307
- model: this.options.model || "claude-sonnet-4-5-20250929",
308
- messages: [{ role: "user", content }],
309
- });
310
-
311
- return response.input_tokens;
35
+ measureTokensCount(content: string): Promise<number> {
36
+ return this.anthropic.measureTokensCount(content);
312
37
  }
313
38
 
314
39
  getLangChainAgentSpec(params: {
315
40
  maxTokens: number;
316
41
  purpose: AgentModelPurpose;
317
42
  }) {
318
- const extraRequestBodyParameters = {
319
- ...(this.options.extraRequestBodyParameters || {}),
320
- } as Record<string, unknown> & {
321
- thinking?: { type: "enabled"; budget_tokens: number };
322
- };
323
- const thinking =
324
- extraRequestBodyParameters.thinking ||
325
- mapReasoningToThinking(
326
- getAgentReasoningEffort(params.purpose),
327
- params.maxTokens,
328
- );
329
-
330
- delete extraRequestBodyParameters.thinking;
331
-
332
- return {
333
- model: new ChatAnthropic({
334
- model: this.options.model || "claude-sonnet-4-5-20250929",
335
- apiKey: getApiKey(this.options),
336
- maxTokens: params.maxTokens,
337
- ...(thinking ? { thinking } : {}),
338
- invocationKwargs: extraRequestBodyParameters,
339
- } as any),
340
- middleware: [createAnthropicSystemMessageMiddleware()],
341
- };
43
+ return createLangChainAgentSpec({
44
+ options: this.options,
45
+ maxTokens: params.maxTokens,
46
+ purpose: params.purpose,
47
+ });
342
48
  }
343
49
 
344
50
  complete = async (
@@ -348,12 +54,7 @@ export default class CompletionAdapterAnthropicMessages
348
54
  reasoningEffort: ReasoningEffort = "low",
349
55
  toolsOrOnChunk?: CompletionTool[] | StreamChunkCallback,
350
56
  onChunk?: StreamChunkCallback,
351
- ): Promise<{
352
- content?: string;
353
- finishReason?: string;
354
- error?: string;
355
- used_tokens?: UsedTokens;
356
- }> => {
57
+ ): Promise<CompletionResult> => {
357
58
  const request =
358
59
  typeof requestOrContent === "string"
359
60
  ? {
@@ -368,239 +69,10 @@ export default class CompletionAdapterAnthropicMessages
368
69
  : onChunk,
369
70
  }
370
71
  : requestOrContent;
371
- const {
372
- content,
373
- maxTokens: requestMaxTokens = 50,
374
- outputSchema: requestOutputSchema,
375
- reasoningEffort: requestReasoningEffort = "low",
376
- tools,
377
- onChunk: streamChunkCallback,
378
- } = request;
379
- const model = this.options.model || "claude-sonnet-4-5-20250929";
380
- const isStreaming = typeof streamChunkCallback === "function";
381
- const normalizedSchema = normalizeOutputSchema(requestOutputSchema);
382
- const extra = {
383
- ...(this.options.extraRequestBodyParameters || {}),
384
- } as Record<string, unknown>;
385
- const thinking = extra.thinking || mapReasoningToThinking(
386
- requestReasoningEffort,
387
- requestMaxTokens,
388
- );
389
-
390
- const body = {
391
- model,
392
- max_tokens: requestMaxTokens,
393
- messages: [{ role: "user", content }],
394
- tools: mapTools(tools),
395
- ...(thinking ? { thinking } : {}),
396
- ...extra,
397
- } as Record<string, unknown>;
398
-
399
- try {
400
- if (requestOutputSchema && !normalizedSchema) {
401
- return {
402
- error:
403
- "Anthropic structured output requires a top-level JSON schema object with type: \"object\"",
404
- };
405
- }
406
-
407
- if (normalizedSchema) {
408
- const parsedMessage = (await this.getClient().messages.parse({
409
- ...(body as any),
410
- output_config: {
411
- format: jsonSchemaOutputFormat(normalizedSchema),
412
- },
413
- } as any)) as AnthropicMessageLike;
414
- const parsedOutput =
415
- typeof parsedMessage.parsed_output === "undefined"
416
- ? extractOutputText(parsedMessage)
417
- : JSON.stringify(parsedMessage.parsed_output);
418
- const parsedReasoning = extractReasoning(parsedMessage);
419
- const usedTokens = extractUsedTokens(parsedMessage);
420
-
421
- if (parsedReasoning && isStreaming) {
422
- await streamChunkCallback?.(parsedReasoning, {
423
- type: "reasoning",
424
- delta: parsedReasoning,
425
- text: parsedReasoning,
426
- });
427
- }
428
- if (parsedOutput && isStreaming) {
429
- await streamChunkCallback?.(parsedOutput, {
430
- type: "output",
431
- delta: parsedOutput,
432
- text: parsedOutput,
433
- });
434
- }
435
-
436
- const toolUse = extractToolUse(parsedMessage);
437
- if (toolUse) {
438
- try {
439
- const toolResult = await executeToolCall(toolUse, tools);
440
- if (toolResult && isStreaming) {
441
- await streamChunkCallback?.(toolResult, {
442
- type: "output",
443
- delta: toolResult,
444
- text: toolResult,
445
- });
446
- }
447
-
448
- return {
449
- content: toolResult,
450
- finishReason: "tool_call",
451
- used_tokens: usedTokens,
452
- };
453
- } catch (error) {
454
- return {
455
- error: getErrorMessage(error),
456
- finishReason: "tool_call",
457
- used_tokens: usedTokens,
458
- };
459
- }
460
- }
461
-
462
- return {
463
- content: parsedOutput || undefined,
464
- finishReason: parsedMessage.stop_reason || undefined,
465
- used_tokens: usedTokens,
466
- };
467
- }
468
-
469
- if (!isStreaming) {
470
- const message = (await this.getClient().messages.create(
471
- body as any,
472
- )) as AnthropicMessageLike;
473
- const usedTokens = extractUsedTokens(message);
474
-
475
- const toolUse = extractToolUse(message);
476
- if (toolUse) {
477
- try {
478
- const toolResult = await executeToolCall(toolUse, tools);
479
- return {
480
- content: toolResult,
481
- finishReason: "tool_call",
482
- used_tokens: usedTokens,
483
- };
484
- } catch (error) {
485
- return {
486
- error: getErrorMessage(error),
487
- finishReason: "tool_call",
488
- used_tokens: usedTokens,
489
- };
490
- }
491
- }
492
72
 
493
- return {
494
- content: extractOutputText(message) || undefined,
495
- finishReason: message.stop_reason || undefined,
496
- used_tokens: usedTokens,
497
- };
498
- }
499
-
500
- const stream = this.getClient().messages.stream(body as any);
501
- let fullContent = "";
502
- let fullReasoning = "";
503
-
504
- for await (const event of stream as any) {
505
- if (event?.type !== "content_block_delta") continue;
506
-
507
- if (event.delta?.type === "text_delta" && typeof event.delta.text === "string") {
508
- fullContent += event.delta.text;
509
- await streamChunkCallback?.(event.delta.text, {
510
- type: "output",
511
- delta: event.delta.text,
512
- text: fullContent,
513
- });
514
- continue;
515
- }
516
-
517
- if (
518
- event.delta?.type === "thinking_delta" &&
519
- typeof event.delta.thinking === "string"
520
- ) {
521
- fullReasoning += event.delta.thinking;
522
- await streamChunkCallback?.(event.delta.thinking, {
523
- type: "reasoning",
524
- delta: event.delta.thinking,
525
- text: fullReasoning,
526
- });
527
- }
528
- }
529
-
530
- const message = (await stream.finalMessage()) as AnthropicMessageLike;
531
- const finalContent = extractOutputText(message);
532
- const finalReasoning = extractReasoning(message) || "";
533
- const usedTokens = extractUsedTokens(message);
534
-
535
- if (finalReasoning && finalReasoning !== fullReasoning) {
536
- const delta = finalReasoning.startsWith(fullReasoning)
537
- ? finalReasoning.slice(fullReasoning.length)
538
- : finalReasoning;
539
- if (delta) {
540
- fullReasoning = finalReasoning;
541
- await streamChunkCallback?.(delta, {
542
- type: "reasoning",
543
- delta,
544
- text: finalReasoning,
545
- });
546
- }
547
- }
548
-
549
- if (finalContent && finalContent !== fullContent) {
550
- const delta = finalContent.startsWith(fullContent)
551
- ? finalContent.slice(fullContent.length)
552
- : finalContent;
553
- if (delta) {
554
- fullContent = finalContent;
555
- await streamChunkCallback?.(delta, {
556
- type: "output",
557
- delta,
558
- text: finalContent,
559
- });
560
- }
561
- }
562
-
563
- const toolUse = extractToolUse(message);
564
- if (toolUse) {
565
- try {
566
- const toolResult = await executeToolCall(toolUse, tools);
567
- if (toolResult) {
568
- const delta = toolResult.startsWith(fullContent)
569
- ? toolResult.slice(fullContent.length)
570
- : toolResult;
571
- if (delta) {
572
- await streamChunkCallback?.(delta, {
573
- type: "output",
574
- delta,
575
- text: toolResult,
576
- });
577
- }
578
- }
579
-
580
- return {
581
- content: toolResult,
582
- finishReason: "tool_call",
583
- used_tokens: usedTokens,
584
- };
585
- } catch (error) {
586
- return {
587
- error: getErrorMessage(error),
588
- content: fullContent || undefined,
589
- finishReason: "tool_call",
590
- used_tokens: usedTokens,
591
- };
592
- }
593
- }
594
-
595
- return {
596
- content: fullContent || undefined,
597
- finishReason: message.stop_reason || undefined,
598
- used_tokens: usedTokens,
599
- };
600
- } catch (error) {
601
- return {
602
- error: getErrorMessage(error),
603
- };
604
- }
73
+ return this.anthropic.complete(request);
605
74
  };
606
75
  }
76
+
77
+ export { CompletionAdapterAnthropicMessages };
78
+ export default CompletionAdapterAnthropicMessages;