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