@prompty/anthropic 2.0.0-alpha.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/dist/index.cjs ADDED
@@ -0,0 +1,427 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ AnthropicExecutor: () => AnthropicExecutor,
24
+ AnthropicProcessor: () => AnthropicProcessor,
25
+ buildChatArgs: () => buildChatArgs,
26
+ messageToWire: () => messageToWire,
27
+ outputSchemaToWire: () => outputSchemaToWire,
28
+ processResponse: () => processResponse,
29
+ toolsToWire: () => toolsToWire
30
+ });
31
+ module.exports = __toCommonJS(index_exports);
32
+
33
+ // src/executor.ts
34
+ var import_core = require("@prompty/core");
35
+ var import_core2 = require("@prompty/core");
36
+ var import_core3 = require("@prompty/core");
37
+
38
+ // src/wire.ts
39
+ function messageToWire(msg) {
40
+ const wire = { role: msg.role };
41
+ if (msg.metadata.tool_results && Array.isArray(msg.metadata.tool_results)) {
42
+ wire.role = "user";
43
+ wire.content = msg.metadata.tool_results;
44
+ return wire;
45
+ }
46
+ if (msg.metadata.tool_use_id || msg.metadata.tool_call_id) {
47
+ const toolUseId = msg.metadata.tool_use_id ?? msg.metadata.tool_call_id;
48
+ wire.role = "user";
49
+ wire.content = [
50
+ {
51
+ type: "tool_result",
52
+ tool_use_id: toolUseId,
53
+ content: msg.toTextContent()
54
+ }
55
+ ];
56
+ return wire;
57
+ }
58
+ if (msg.role === "assistant" && msg.metadata.content && Array.isArray(msg.metadata.content)) {
59
+ wire.content = msg.metadata.content;
60
+ return wire;
61
+ }
62
+ const content = msg.toTextContent();
63
+ if (typeof content === "string") {
64
+ wire.content = content;
65
+ } else {
66
+ wire.content = msg.parts.map(partToWire);
67
+ }
68
+ return wire;
69
+ }
70
+ function partToWire(part) {
71
+ switch (part.kind) {
72
+ case "text":
73
+ return { type: "text", text: part.value };
74
+ case "image": {
75
+ if (part.source.startsWith("data:") || part.source.startsWith("/")) {
76
+ const [header, data] = part.source.split(",", 2);
77
+ const mediaType = header?.match(/data:(.*?);/)?.[1] ?? "image/png";
78
+ return {
79
+ type: "image",
80
+ source: {
81
+ type: "base64",
82
+ media_type: mediaType,
83
+ data: data ?? part.source
84
+ }
85
+ };
86
+ }
87
+ return {
88
+ type: "image",
89
+ source: { type: "url", url: part.source }
90
+ };
91
+ }
92
+ case "file":
93
+ return { type: "text", text: `[file: ${part.source}]` };
94
+ case "audio":
95
+ return { type: "text", text: `[audio: ${part.source}]` };
96
+ }
97
+ }
98
+ var DEFAULT_MAX_TOKENS = 1024;
99
+ function buildChatArgs(agent, messages) {
100
+ const model = agent.model?.id || "claude-sonnet-4-5-20250929";
101
+ const systemParts = [];
102
+ const conversationMessages = [];
103
+ for (const msg of messages) {
104
+ if (msg.role === "system") {
105
+ systemParts.push(msg.text);
106
+ } else {
107
+ conversationMessages.push(messageToWire(msg));
108
+ }
109
+ }
110
+ const args = {
111
+ model,
112
+ messages: conversationMessages,
113
+ max_tokens: agent.model?.options?.maxOutputTokens ?? DEFAULT_MAX_TOKENS,
114
+ ...buildOptions(agent)
115
+ };
116
+ if (systemParts.length > 0) {
117
+ args.system = systemParts.join("\n\n");
118
+ }
119
+ const tools = toolsToWire(agent);
120
+ if (tools.length > 0) {
121
+ args.tools = tools;
122
+ }
123
+ const outputConfig = outputSchemaToWire(agent);
124
+ if (outputConfig) {
125
+ args.output_config = outputConfig;
126
+ }
127
+ return args;
128
+ }
129
+ var KIND_TO_JSON_TYPE = {
130
+ string: "string",
131
+ integer: "integer",
132
+ float: "number",
133
+ number: "number",
134
+ boolean: "boolean",
135
+ array: "array",
136
+ object: "object"
137
+ };
138
+ function buildOptions(agent) {
139
+ const opts = agent.model?.options;
140
+ if (!opts) return {};
141
+ const result = {};
142
+ if (opts.temperature !== void 0) result.temperature = opts.temperature;
143
+ if (opts.topP !== void 0) result.top_p = opts.topP;
144
+ if (opts.topK !== void 0) result.top_k = opts.topK;
145
+ if (opts.stopSequences !== void 0) result.stop_sequences = opts.stopSequences;
146
+ if (opts.additionalProperties) {
147
+ for (const [k, v] of Object.entries(opts.additionalProperties)) {
148
+ if (!(k in result) && k !== "max_tokens") {
149
+ result[k] = v;
150
+ }
151
+ }
152
+ }
153
+ return result;
154
+ }
155
+ function schemaToWire(properties) {
156
+ const props = {};
157
+ const required = [];
158
+ for (const p of properties) {
159
+ if (!p.name) continue;
160
+ const schema = {
161
+ type: KIND_TO_JSON_TYPE[p.kind ?? "string"] ?? "string"
162
+ };
163
+ if (p.description) schema.description = p.description;
164
+ if (p.enumValues && p.enumValues.length > 0) schema.enum = p.enumValues;
165
+ props[p.name] = schema;
166
+ if (p.required) required.push(p.name);
167
+ }
168
+ const result = { type: "object", properties: props };
169
+ if (required.length > 0) result.required = required;
170
+ return result;
171
+ }
172
+ function propertyToJsonSchema(prop) {
173
+ const schema = {
174
+ type: KIND_TO_JSON_TYPE[prop.kind ?? "string"] ?? "string"
175
+ };
176
+ if (prop.description) schema.description = prop.description;
177
+ if (prop.enumValues && prop.enumValues.length > 0) schema.enum = prop.enumValues;
178
+ if (prop.kind === "array") {
179
+ schema.items = prop.items ? propertyToJsonSchema(prop.items) : { type: "string" };
180
+ }
181
+ if (prop.kind === "object") {
182
+ if (prop.properties) {
183
+ const nested = {};
184
+ const req = [];
185
+ for (const p of prop.properties) {
186
+ if (!p.name) continue;
187
+ nested[p.name] = propertyToJsonSchema(p);
188
+ req.push(p.name);
189
+ }
190
+ schema.properties = nested;
191
+ schema.required = req;
192
+ } else {
193
+ schema.properties = {};
194
+ schema.required = [];
195
+ }
196
+ schema.additionalProperties = false;
197
+ }
198
+ return schema;
199
+ }
200
+ function toolsToWire(agent) {
201
+ const tools = agent.tools;
202
+ if (!tools || tools.length === 0) return [];
203
+ const result = [];
204
+ for (const t of tools) {
205
+ if (t.kind !== "function") continue;
206
+ const tool = { name: t.name };
207
+ if (t.description) tool.description = t.description;
208
+ const params = t.parameters;
209
+ if (params && Array.isArray(params)) {
210
+ tool.input_schema = schemaToWire(params);
211
+ } else {
212
+ tool.input_schema = { type: "object", properties: {} };
213
+ }
214
+ result.push(tool);
215
+ }
216
+ return result;
217
+ }
218
+ function outputSchemaToWire(agent) {
219
+ const outputs = agent.outputs;
220
+ if (!outputs || outputs.length === 0) return null;
221
+ const properties = {};
222
+ const required = [];
223
+ for (const prop of outputs) {
224
+ if (!prop.name) continue;
225
+ properties[prop.name] = propertyToJsonSchema(
226
+ prop
227
+ );
228
+ required.push(prop.name);
229
+ }
230
+ return {
231
+ format: {
232
+ type: "json_schema",
233
+ schema: {
234
+ type: "object",
235
+ properties,
236
+ required,
237
+ additionalProperties: false
238
+ }
239
+ }
240
+ };
241
+ }
242
+
243
+ // src/executor.ts
244
+ var AnthropicExecutor = class {
245
+ async execute(agent, messages) {
246
+ return (0, import_core3.traceSpan)("AnthropicExecutor", async (emit) => {
247
+ emit("signature", "prompty.anthropic.executor.AnthropicExecutor.invoke");
248
+ emit("inputs", { data: messages });
249
+ const client = this.resolveClient(agent);
250
+ const clientName = "Anthropic";
251
+ await (0, import_core3.traceSpan)(clientName, async (ctorEmit) => {
252
+ ctorEmit("signature", `${clientName}.ctor`);
253
+ const conn = agent.model?.connection;
254
+ if (conn instanceof import_core.ReferenceConnection) {
255
+ ctorEmit("inputs", { source: "reference", name: conn.name });
256
+ } else {
257
+ ctorEmit("inputs", (0, import_core3.sanitizeValue)("ctor", this.clientKwargs(agent)));
258
+ }
259
+ ctorEmit("result", clientName);
260
+ });
261
+ const apiType = agent.model?.apiType ?? "chat";
262
+ const result = await this.executeApiCall(client, clientName, agent, messages, apiType);
263
+ emit("result", result);
264
+ return result;
265
+ });
266
+ }
267
+ /** Dispatch to the appropriate API and trace the call. */
268
+ async executeApiCall(client, clientName, agent, messages, apiType) {
269
+ switch (apiType) {
270
+ case "chat": {
271
+ const args = buildChatArgs(agent, messages);
272
+ const isStreaming = !!args.stream;
273
+ return (0, import_core3.traceSpan)("create", async (callEmit) => {
274
+ callEmit("signature", `${clientName}.messages.create`);
275
+ callEmit("inputs", (0, import_core3.sanitizeValue)("create", args));
276
+ if (isStreaming) {
277
+ const stream = client.messages.stream(
278
+ args
279
+ );
280
+ return new import_core.PromptyStream(
281
+ `${clientName}Executor`,
282
+ stream
283
+ );
284
+ }
285
+ const result = await client.messages.create(
286
+ args
287
+ );
288
+ callEmit("result", result);
289
+ return result;
290
+ });
291
+ }
292
+ default:
293
+ throw new Error(
294
+ `Unsupported apiType "${apiType}" for Anthropic. Anthropic only supports "chat" (Messages API).`
295
+ );
296
+ }
297
+ }
298
+ resolveClient(agent) {
299
+ const conn = agent.model?.connection;
300
+ if (conn instanceof import_core.ReferenceConnection) {
301
+ return (0, import_core2.getConnection)(conn.name);
302
+ }
303
+ const kwargs = this.clientKwargs(agent);
304
+ const AnthropicSDK = require("@anthropic-ai/sdk").default;
305
+ return new AnthropicSDK(kwargs);
306
+ }
307
+ clientKwargs(agent) {
308
+ const kwargs = {};
309
+ const conn = agent.model?.connection;
310
+ if (conn instanceof import_core.ApiKeyConnection) {
311
+ if (conn.apiKey) kwargs.apiKey = conn.apiKey;
312
+ if (conn.endpoint) kwargs.baseURL = conn.endpoint;
313
+ }
314
+ return kwargs;
315
+ }
316
+ };
317
+
318
+ // src/processor.ts
319
+ var import_core4 = require("@prompty/core");
320
+ var AnthropicProcessor = class {
321
+ async process(agent, response) {
322
+ return (0, import_core4.traceSpan)("AnthropicProcessor", async (emit) => {
323
+ emit("signature", "prompty.anthropic.processor.AnthropicProcessor.invoke");
324
+ emit("inputs", { data: response });
325
+ const result = processResponse(agent, response);
326
+ if (!isAsyncIterable(response)) {
327
+ emit("result", result);
328
+ }
329
+ return result;
330
+ });
331
+ }
332
+ };
333
+ function processResponse(agent, response) {
334
+ if (typeof response !== "object" || response === null) return response;
335
+ if (isAsyncIterable(response)) {
336
+ return streamGenerator(response);
337
+ }
338
+ const r = response;
339
+ if (Array.isArray(r.content) && r.role === "assistant") {
340
+ return processMessages(agent, r);
341
+ }
342
+ return response;
343
+ }
344
+ function isAsyncIterable(value) {
345
+ return typeof value === "object" && value !== null && Symbol.asyncIterator in value;
346
+ }
347
+ async function* streamGenerator(response) {
348
+ const toolCallAcc = /* @__PURE__ */ new Map();
349
+ for await (const event of response) {
350
+ const e = event;
351
+ const eventType = e.type;
352
+ if (eventType === "content_block_delta") {
353
+ const delta = e.delta;
354
+ if (!delta) continue;
355
+ if (delta.type === "text_delta") {
356
+ yield delta.text;
357
+ } else if (delta.type === "input_json_delta") {
358
+ const idx = e.index;
359
+ const acc = toolCallAcc.get(idx);
360
+ if (acc) {
361
+ acc.arguments += delta.partial_json ?? "";
362
+ }
363
+ }
364
+ } else if (eventType === "content_block_start") {
365
+ const block = e.content_block;
366
+ if (block?.type === "tool_use") {
367
+ const idx = e.index;
368
+ toolCallAcc.set(idx, {
369
+ id: block.id ?? "",
370
+ name: block.name ?? "",
371
+ arguments: ""
372
+ });
373
+ }
374
+ }
375
+ }
376
+ const sortedIndices = [...toolCallAcc.keys()].sort((a, b) => a - b);
377
+ for (const idx of sortedIndices) {
378
+ const tc = toolCallAcc.get(idx);
379
+ yield { id: tc.id, name: tc.name, arguments: tc.arguments };
380
+ }
381
+ }
382
+ function processMessages(agent, response) {
383
+ const content = response.content;
384
+ if (!content || content.length === 0) return null;
385
+ const toolCalls = [];
386
+ const textParts = [];
387
+ for (const block of content) {
388
+ if (block.type === "tool_use") {
389
+ toolCalls.push({
390
+ id: block.id,
391
+ name: block.name,
392
+ arguments: typeof block.input === "string" ? block.input : JSON.stringify(block.input)
393
+ });
394
+ } else if (block.type === "text") {
395
+ textParts.push(block.text);
396
+ }
397
+ }
398
+ if (toolCalls.length > 0) {
399
+ return toolCalls;
400
+ }
401
+ const text = textParts.join("");
402
+ if (!text) return null;
403
+ if (agent.outputs && agent.outputs.length > 0) {
404
+ try {
405
+ return JSON.parse(text);
406
+ } catch {
407
+ return text;
408
+ }
409
+ }
410
+ return text;
411
+ }
412
+
413
+ // src/index.ts
414
+ var import_core5 = require("@prompty/core");
415
+ (0, import_core5.registerExecutor)("anthropic", new AnthropicExecutor());
416
+ (0, import_core5.registerProcessor)("anthropic", new AnthropicProcessor());
417
+ // Annotate the CommonJS export names for ESM import in node:
418
+ 0 && (module.exports = {
419
+ AnthropicExecutor,
420
+ AnthropicProcessor,
421
+ buildChatArgs,
422
+ messageToWire,
423
+ outputSchemaToWire,
424
+ processResponse,
425
+ toolsToWire
426
+ });
427
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/executor.ts","../src/wire.ts","../src/processor.ts"],"sourcesContent":["/**\r\n * @prompty/anthropic — Anthropic provider for Prompty.\r\n *\r\n * Importing this package auto-registers the \"anthropic\" executor and processor.\r\n *\r\n * @module @prompty/anthropic\r\n */\r\n\r\nexport { AnthropicExecutor } from \"./executor.js\";\r\nexport { AnthropicProcessor, processResponse } from \"./processor.js\";\r\nexport { buildChatArgs, messageToWire, toolsToWire, outputSchemaToWire } from \"./wire.js\";\r\n\r\n// Auto-register on import\r\nimport { registerExecutor, registerProcessor } from \"@prompty/core\";\r\nimport { AnthropicExecutor } from \"./executor.js\";\r\nimport { AnthropicProcessor } from \"./processor.js\";\r\n\r\nregisterExecutor(\"anthropic\", new AnthropicExecutor());\r\nregisterProcessor(\"anthropic\", new AnthropicProcessor());\r\n","/**\r\n * Anthropic executor — sends messages to Anthropic Messages API.\r\n *\r\n * Dispatches on `agent.model.apiType`: only `chat` is supported\r\n * (Anthropic has no embedding or image APIs).\r\n * The agent loop (tool-call iteration) is handled by the pipeline,\r\n * not the executor.\r\n *\r\n * @module\r\n */\r\n\r\nimport type Anthropic from \"@anthropic-ai/sdk\";\r\nimport type { Prompty } from \"@prompty/core\";\r\nimport { ApiKeyConnection, ReferenceConnection, PromptyStream } from \"@prompty/core\";\r\nimport type { Executor } from \"@prompty/core\";\r\nimport type { Message } from \"@prompty/core\";\r\nimport { getConnection } from \"@prompty/core\";\r\nimport { traceSpan, sanitizeValue } from \"@prompty/core\";\r\nimport { buildChatArgs } from \"./wire.js\";\r\n\r\nexport class AnthropicExecutor implements Executor {\r\n async execute(agent: Prompty, messages: Message[]): Promise<unknown> {\r\n return traceSpan(\"AnthropicExecutor\", async (emit) => {\r\n emit(\"signature\", \"prompty.anthropic.executor.AnthropicExecutor.invoke\");\r\n emit(\"inputs\", { data: messages });\r\n\r\n const client = this.resolveClient(agent);\r\n const clientName = \"Anthropic\";\r\n\r\n // Trace client construction\r\n await traceSpan(clientName, async (ctorEmit) => {\r\n ctorEmit(\"signature\", `${clientName}.ctor`);\r\n const conn = agent.model?.connection;\r\n if (conn instanceof ReferenceConnection) {\r\n ctorEmit(\"inputs\", { source: \"reference\", name: conn.name });\r\n } else {\r\n ctorEmit(\"inputs\", sanitizeValue(\"ctor\", this.clientKwargs(agent)));\r\n }\r\n ctorEmit(\"result\", clientName);\r\n });\r\n\r\n const apiType = agent.model?.apiType ?? \"chat\";\r\n const result = await this.executeApiCall(client, clientName, agent, messages, apiType);\r\n emit(\"result\", result);\r\n return result;\r\n });\r\n }\r\n\r\n /** Dispatch to the appropriate API and trace the call. */\r\n private async executeApiCall(\r\n client: Anthropic,\r\n clientName: string,\r\n agent: Prompty,\r\n messages: Message[],\r\n apiType: string,\r\n ): Promise<unknown> {\r\n switch (apiType) {\r\n case \"chat\": {\r\n const args = buildChatArgs(agent, messages);\r\n const isStreaming = !!args.stream;\r\n\r\n return traceSpan(\"create\", async (callEmit) => {\r\n callEmit(\"signature\", `${clientName}.messages.create`);\r\n callEmit(\"inputs\", sanitizeValue(\"create\", args));\r\n\r\n if (isStreaming) {\r\n const stream = client.messages.stream(\r\n args as unknown as Parameters<typeof client.messages.stream>[0],\r\n );\r\n return new PromptyStream(\r\n `${clientName}Executor`,\r\n stream as unknown as AsyncIterable<unknown>,\r\n );\r\n }\r\n\r\n const result = await client.messages.create(\r\n args as unknown as Parameters<typeof client.messages.create>[0],\r\n );\r\n callEmit(\"result\", result);\r\n return result;\r\n });\r\n }\r\n default:\r\n throw new Error(\r\n `Unsupported apiType \"${apiType}\" for Anthropic. ` +\r\n `Anthropic only supports \"chat\" (Messages API).`,\r\n );\r\n }\r\n }\r\n\r\n protected resolveClient(agent: Prompty): Anthropic {\r\n const conn = agent.model?.connection;\r\n\r\n if (conn instanceof ReferenceConnection) {\r\n return getConnection(conn.name) as Anthropic;\r\n }\r\n\r\n const kwargs = this.clientKwargs(agent);\r\n\r\n // Lazy import — only needed when actually called\r\n // eslint-disable-next-line @typescript-eslint/no-require-imports\r\n const AnthropicSDK = require(\"@anthropic-ai/sdk\").default;\r\n return new AnthropicSDK(kwargs);\r\n }\r\n\r\n protected clientKwargs(agent: Prompty): Record<string, unknown> {\r\n const kwargs: Record<string, unknown> = {};\r\n const conn = agent.model?.connection;\r\n\r\n if (conn instanceof ApiKeyConnection) {\r\n if (conn.apiKey) kwargs.apiKey = conn.apiKey;\r\n if (conn.endpoint) kwargs.baseURL = conn.endpoint;\r\n }\r\n\r\n return kwargs;\r\n }\r\n}\r\n","/**\r\n * Wire format conversion: Message → Anthropic Messages API JSON.\r\n *\r\n * Key differences from OpenAI:\r\n * - `system` is a separate top-level parameter (not in messages)\r\n * - Tools use `input_schema` (not nested `{type: \"function\", function: {...}}`)\r\n * - `max_tokens` is required\r\n * - Structured output uses `output_config.format` with `json_schema`\r\n *\r\n * @module\r\n */\r\n\r\nimport type { Prompty } from \"@prompty/core\";\r\nimport type { ContentPart, Message } from \"@prompty/core\";\r\n\r\n// ---------------------------------------------------------------------------\r\n// Message conversion\r\n// ---------------------------------------------------------------------------\r\n\r\n/**\r\n * Convert an abstract Message to Anthropic wire format.\r\n * System messages are excluded — they go in a separate `system` parameter.\r\n */\r\nexport function messageToWire(msg: Message): Record<string, unknown> {\r\n const wire: Record<string, unknown> = { role: msg.role };\r\n\r\n // Batched tool results → single user message with all tool_result blocks\r\n if (msg.metadata.tool_results && Array.isArray(msg.metadata.tool_results)) {\r\n wire.role = \"user\";\r\n wire.content = msg.metadata.tool_results;\r\n return wire;\r\n }\r\n\r\n // Legacy single tool result messages (backward compat)\r\n if (msg.metadata.tool_use_id || msg.metadata.tool_call_id) {\r\n const toolUseId = (msg.metadata.tool_use_id ?? msg.metadata.tool_call_id) as string;\r\n wire.role = \"user\";\r\n wire.content = [\r\n {\r\n type: \"tool_result\",\r\n tool_use_id: toolUseId,\r\n content: msg.toTextContent(),\r\n },\r\n ];\r\n return wire;\r\n }\r\n\r\n // Assistant messages with raw content blocks (tool_use) — preserve them\r\n if (msg.role === \"assistant\" && msg.metadata.content && Array.isArray(msg.metadata.content)) {\r\n wire.content = msg.metadata.content;\r\n return wire;\r\n }\r\n\r\n const content = msg.toTextContent();\r\n if (typeof content === \"string\") {\r\n wire.content = content;\r\n } else {\r\n // Multimodal — convert parts to Anthropic format\r\n wire.content = msg.parts.map(partToWire);\r\n }\r\n\r\n return wire;\r\n}\r\n\r\n/**\r\n * Convert a ContentPart to Anthropic wire format.\r\n */\r\nfunction partToWire(part: ContentPart): Record<string, unknown> {\r\n switch (part.kind) {\r\n case \"text\":\r\n return { type: \"text\", text: part.value };\r\n case \"image\": {\r\n // Anthropic uses base64 source blocks or URL\r\n if (part.source.startsWith(\"data:\") || part.source.startsWith(\"/\")) {\r\n // Base64 encoded\r\n const [header, data] = part.source.split(\",\", 2);\r\n const mediaType = header?.match(/data:(.*?);/)?.[1] ?? \"image/png\";\r\n return {\r\n type: \"image\",\r\n source: {\r\n type: \"base64\",\r\n media_type: mediaType,\r\n data: data ?? part.source,\r\n },\r\n };\r\n }\r\n // URL\r\n return {\r\n type: \"image\",\r\n source: { type: \"url\", url: part.source },\r\n };\r\n }\r\n case \"file\":\r\n return { type: \"text\", text: `[file: ${part.source}]` };\r\n case \"audio\":\r\n return { type: \"text\", text: `[audio: ${part.source}]` };\r\n }\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Build API arguments\r\n// ---------------------------------------------------------------------------\r\n\r\nconst DEFAULT_MAX_TOKENS = 1024;\r\n\r\n/**\r\n * Build Anthropic Messages API arguments from agent config and messages.\r\n */\r\nexport function buildChatArgs(\r\n agent: Prompty,\r\n messages: Message[],\r\n): Record<string, unknown> {\r\n const model = agent.model?.id || \"claude-sonnet-4-5-20250929\";\r\n\r\n // Separate system messages from conversation messages\r\n const systemParts: string[] = [];\r\n const conversationMessages: Record<string, unknown>[] = [];\r\n\r\n for (const msg of messages) {\r\n if (msg.role === \"system\") {\r\n systemParts.push(msg.text);\r\n } else {\r\n conversationMessages.push(messageToWire(msg));\r\n }\r\n }\r\n\r\n const args: Record<string, unknown> = {\r\n model,\r\n messages: conversationMessages,\r\n max_tokens: agent.model?.options?.maxOutputTokens ?? DEFAULT_MAX_TOKENS,\r\n ...buildOptions(agent),\r\n };\r\n\r\n // System prompt as separate parameter\r\n if (systemParts.length > 0) {\r\n args.system = systemParts.join(\"\\n\\n\");\r\n }\r\n\r\n // Tools\r\n const tools = toolsToWire(agent);\r\n if (tools.length > 0) {\r\n args.tools = tools;\r\n }\r\n\r\n // Structured output\r\n const outputConfig = outputSchemaToWire(agent);\r\n if (outputConfig) {\r\n args.output_config = outputConfig;\r\n }\r\n\r\n return args;\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Helpers\r\n// ---------------------------------------------------------------------------\r\n\r\n/** Map AgentSchema kind strings to JSON Schema type strings. */\r\nconst KIND_TO_JSON_TYPE: Record<string, string> = {\r\n string: \"string\",\r\n integer: \"integer\",\r\n float: \"number\",\r\n number: \"number\",\r\n boolean: \"boolean\",\r\n array: \"array\",\r\n object: \"object\",\r\n};\r\n\r\nfunction buildOptions(agent: Prompty): Record<string, unknown> {\r\n const opts = agent.model?.options;\r\n if (!opts) return {};\r\n\r\n const result: Record<string, unknown> = {};\r\n\r\n if (opts.temperature !== undefined) result.temperature = opts.temperature;\r\n if (opts.topP !== undefined) result.top_p = opts.topP;\r\n if (opts.topK !== undefined) result.top_k = opts.topK;\r\n if (opts.stopSequences !== undefined) result.stop_sequences = opts.stopSequences;\r\n\r\n // Pass through additionalProperties — but don't overwrite mapped keys\r\n if (opts.additionalProperties) {\r\n for (const [k, v] of Object.entries(opts.additionalProperties)) {\r\n if (!(k in result) && k !== \"max_tokens\") {\r\n result[k] = v;\r\n }\r\n }\r\n }\r\n\r\n return result;\r\n}\r\n\r\n/** Convert a Property list to a JSON Schema `{type: \"object\", properties: ...}`. */\r\nfunction schemaToWire(properties: unknown[]): Record<string, unknown> {\r\n const props: Record<string, unknown> = {};\r\n const required: string[] = [];\r\n\r\n for (const p of properties as Array<{\r\n name?: string;\r\n kind?: string;\r\n description?: string;\r\n required?: boolean;\r\n enumValues?: unknown[];\r\n }>) {\r\n if (!p.name) continue;\r\n const schema: Record<string, unknown> = {\r\n type: KIND_TO_JSON_TYPE[p.kind ?? \"string\"] ?? \"string\",\r\n };\r\n if (p.description) schema.description = p.description;\r\n if (p.enumValues && p.enumValues.length > 0) schema.enum = p.enumValues;\r\n props[p.name] = schema;\r\n if (p.required) required.push(p.name);\r\n }\r\n\r\n const result: Record<string, unknown> = { type: \"object\", properties: props };\r\n if (required.length > 0) result.required = required;\r\n return result;\r\n}\r\n\r\n/** Convert a single Property to a JSON Schema definition. */\r\nfunction propertyToJsonSchema(prop: {\r\n kind?: string;\r\n description?: string;\r\n enumValues?: unknown[];\r\n items?: unknown;\r\n properties?: unknown[];\r\n}): Record<string, unknown> {\r\n const schema: Record<string, unknown> = {\r\n type: KIND_TO_JSON_TYPE[prop.kind ?? \"string\"] ?? \"string\",\r\n };\r\n\r\n if (prop.description) schema.description = prop.description;\r\n if (prop.enumValues && prop.enumValues.length > 0) schema.enum = prop.enumValues;\r\n\r\n if (prop.kind === \"array\") {\r\n schema.items = prop.items\r\n ? propertyToJsonSchema(prop.items as typeof prop)\r\n : { type: \"string\" };\r\n }\r\n\r\n if (prop.kind === \"object\") {\r\n if (prop.properties) {\r\n const nested: Record<string, unknown> = {};\r\n const req: string[] = [];\r\n for (const p of prop.properties as Array<{ name?: string } & typeof prop>) {\r\n if (!p.name) continue;\r\n nested[p.name] = propertyToJsonSchema(p);\r\n req.push(p.name);\r\n }\r\n schema.properties = nested;\r\n schema.required = req;\r\n } else {\r\n schema.properties = {};\r\n schema.required = [];\r\n }\r\n schema.additionalProperties = false;\r\n }\r\n\r\n return schema;\r\n}\r\n\r\n/**\r\n * Convert agent tools to Anthropic tool format.\r\n *\r\n * Anthropic uses: { name, description, input_schema }\r\n * (no `{type: \"function\", function: {...}}` wrapper like OpenAI)\r\n */\r\nexport function toolsToWire(agent: Prompty): Record<string, unknown>[] {\r\n const tools = agent.tools;\r\n if (!tools || tools.length === 0) return [];\r\n\r\n const result: Record<string, unknown>[] = [];\r\n\r\n for (const t of tools) {\r\n if (t.kind !== \"function\") continue;\r\n\r\n const tool: Record<string, unknown> = { name: t.name };\r\n if (t.description) tool.description = t.description;\r\n\r\n const params = (t as { parameters?: unknown[] }).parameters;\r\n if (params && Array.isArray(params)) {\r\n tool.input_schema = schemaToWire(params);\r\n } else {\r\n tool.input_schema = { type: \"object\", properties: {} };\r\n }\r\n\r\n result.push(tool);\r\n }\r\n\r\n return result;\r\n}\r\n\r\n/**\r\n * Convert outputSchema to Anthropic structured output config.\r\n *\r\n * Anthropic uses: output_config: { format: { type: \"json_schema\", schema: {...} } }\r\n */\r\nexport function outputSchemaToWire(agent: Prompty): Record<string, unknown> | null {\r\n const outputs = agent.outputs;\r\n if (!outputs || outputs.length === 0) return null;\r\n\r\n const properties: Record<string, unknown> = {};\r\n const required: string[] = [];\r\n\r\n for (const prop of outputs) {\r\n if (!prop.name) continue;\r\n properties[prop.name] = propertyToJsonSchema(\r\n prop as Parameters<typeof propertyToJsonSchema>[0],\r\n );\r\n required.push(prop.name);\r\n }\r\n\r\n return {\r\n format: {\r\n type: \"json_schema\",\r\n schema: {\r\n type: \"object\",\r\n properties,\r\n required,\r\n additionalProperties: false,\r\n },\r\n },\r\n };\r\n}\r\n","/**\r\n * Anthropic processor — extracts clean results from Anthropic Messages API responses.\r\n *\r\n * Handles:\r\n * - Text content from `content[]` blocks\r\n * - Tool use blocks → ToolCall objects\r\n * - Streaming responses (content_block_delta events)\r\n * - Structured output (JSON parse when outputSchema present)\r\n *\r\n * @module\r\n */\r\n\r\nimport type { Prompty } from \"@prompty/core\";\r\nimport type { Processor } from \"@prompty/core\";\r\nimport type { ToolCall } from \"@prompty/core\";\r\nimport { traceSpan } from \"@prompty/core\";\r\n\r\nexport class AnthropicProcessor implements Processor {\r\n async process(agent: Prompty, response: unknown): Promise<unknown> {\r\n return traceSpan(\"AnthropicProcessor\", async (emit) => {\r\n emit(\"signature\", \"prompty.anthropic.processor.AnthropicProcessor.invoke\");\r\n emit(\"inputs\", { data: response });\r\n const result = processResponse(agent, response);\r\n // Don't emit result for streaming — it's a generator, not a value\r\n if (!isAsyncIterable(response)) {\r\n emit(\"result\", result);\r\n }\r\n return result;\r\n });\r\n }\r\n}\r\n\r\n/**\r\n * Extract clean content from an Anthropic Messages API response.\r\n */\r\nexport function processResponse(agent: Prompty, response: unknown): unknown {\r\n if (typeof response !== \"object\" || response === null) return response;\r\n\r\n // Streaming response — return content-extracting async generator\r\n if (isAsyncIterable(response)) {\r\n return streamGenerator(response);\r\n }\r\n\r\n const r = response as Record<string, unknown>;\r\n\r\n // Anthropic Messages response — has `content` array and `role`\r\n if (Array.isArray(r.content) && r.role === \"assistant\") {\r\n return processMessages(agent, r);\r\n }\r\n\r\n return response;\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Streaming\r\n// ---------------------------------------------------------------------------\r\n\r\n/** Type guard for async iterables (PromptyStream or raw SDK stream). */\r\nfunction isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {\r\n return (\r\n typeof value === \"object\" &&\r\n value !== null &&\r\n Symbol.asyncIterator in value\r\n );\r\n}\r\n\r\n/**\r\n * Yield content chunks from an Anthropic streaming response.\r\n *\r\n * Anthropic streaming events include:\r\n * - `content_block_delta` with `delta.type === \"text_delta\"` → yield text\r\n * - `content_block_start` with `content_block.type === \"tool_use\"` → accumulate tool call\r\n * - `input_json` deltas for tool arguments\r\n * - `message_stop` → end of stream\r\n *\r\n * Tool calls are accumulated and yielded at the end of the stream.\r\n */\r\nasync function* streamGenerator(\r\n response: AsyncIterable<unknown>,\r\n): AsyncGenerator<string | ToolCall> {\r\n const toolCallAcc: Map<\r\n number,\r\n { id: string; name: string; arguments: string }\r\n > = new Map();\r\n\r\n for await (const event of response) {\r\n const e = event as Record<string, unknown>;\r\n const eventType = e.type as string | undefined;\r\n\r\n if (eventType === \"content_block_delta\") {\r\n const delta = e.delta as Record<string, unknown> | undefined;\r\n if (!delta) continue;\r\n\r\n if (delta.type === \"text_delta\") {\r\n yield delta.text as string;\r\n } else if (delta.type === \"input_json_delta\") {\r\n // Accumulate partial JSON for tool arguments\r\n const idx = e.index as number;\r\n const acc = toolCallAcc.get(idx);\r\n if (acc) {\r\n acc.arguments += (delta.partial_json ?? \"\") as string;\r\n }\r\n }\r\n } else if (eventType === \"content_block_start\") {\r\n const block = e.content_block as Record<string, unknown> | undefined;\r\n if (block?.type === \"tool_use\") {\r\n const idx = e.index as number;\r\n toolCallAcc.set(idx, {\r\n id: (block.id ?? \"\") as string,\r\n name: (block.name ?? \"\") as string,\r\n arguments: \"\",\r\n });\r\n }\r\n }\r\n }\r\n\r\n // Yield accumulated tool calls at the end of the stream\r\n const sortedIndices = [...toolCallAcc.keys()].sort((a, b) => a - b);\r\n for (const idx of sortedIndices) {\r\n const tc = toolCallAcc.get(idx)!;\r\n yield { id: tc.id, name: tc.name, arguments: tc.arguments } as ToolCall;\r\n }\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Non-streaming response processing\r\n// ---------------------------------------------------------------------------\r\n\r\n/**\r\n * Process an Anthropic Messages API response.\r\n *\r\n * Response shape:\r\n * ```json\r\n * {\r\n * \"role\": \"assistant\",\r\n * \"content\": [\r\n * { \"type\": \"text\", \"text\": \"...\" },\r\n * { \"type\": \"tool_use\", \"id\": \"...\", \"name\": \"...\", \"input\": {...} }\r\n * ],\r\n * \"stop_reason\": \"end_turn\" | \"tool_use\" | \"max_tokens\" | \"stop_sequence\"\r\n * }\r\n * ```\r\n */\r\nfunction processMessages(\r\n agent: Prompty,\r\n response: Record<string, unknown>,\r\n): unknown {\r\n const content = response.content as Record<string, unknown>[];\r\n if (!content || content.length === 0) return null;\r\n\r\n // Check for tool_use blocks\r\n const toolCalls: ToolCall[] = [];\r\n const textParts: string[] = [];\r\n\r\n for (const block of content) {\r\n if (block.type === \"tool_use\") {\r\n toolCalls.push({\r\n id: block.id as string,\r\n name: block.name as string,\r\n arguments:\r\n typeof block.input === \"string\"\r\n ? (block.input as string)\r\n : JSON.stringify(block.input),\r\n });\r\n } else if (block.type === \"text\") {\r\n textParts.push(block.text as string);\r\n }\r\n }\r\n\r\n // If tool calls present, return them (pipeline handles the loop)\r\n if (toolCalls.length > 0) {\r\n return toolCalls;\r\n }\r\n\r\n // Text content\r\n const text = textParts.join(\"\");\r\n if (!text) return null;\r\n\r\n // Structured output — JSON parse when outputs schema exists\r\n if (agent.outputs && agent.outputs.length > 0) {\r\n try {\r\n return JSON.parse(text);\r\n } catch {\r\n return text;\r\n }\r\n }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 import Anthropic from '@anthropic-ai/sdk';
2
+ import { Executor, Prompty, Message, Processor } from '@prompty/core';
3
+
4
+ /**
5
+ * Anthropic executor — sends messages to Anthropic Messages API.
6
+ *
7
+ * Dispatches on `agent.model.apiType`: only `chat` is supported
8
+ * (Anthropic has no embedding or image APIs).
9
+ * The agent loop (tool-call iteration) is handled by the pipeline,
10
+ * not the executor.
11
+ *
12
+ * @module
13
+ */
14
+
15
+ declare class AnthropicExecutor implements Executor {
16
+ execute(agent: Prompty, messages: Message[]): Promise<unknown>;
17
+ /** Dispatch to the appropriate API and trace the call. */
18
+ private executeApiCall;
19
+ protected resolveClient(agent: Prompty): Anthropic;
20
+ protected clientKwargs(agent: Prompty): Record<string, unknown>;
21
+ }
22
+
23
+ /**
24
+ * Anthropic processor — extracts clean results from Anthropic Messages API responses.
25
+ *
26
+ * Handles:
27
+ * - Text content from `content[]` blocks
28
+ * - Tool use blocks → ToolCall objects
29
+ * - Streaming responses (content_block_delta events)
30
+ * - Structured output (JSON parse when outputSchema present)
31
+ *
32
+ * @module
33
+ */
34
+
35
+ declare class AnthropicProcessor implements Processor {
36
+ process(agent: Prompty, response: unknown): Promise<unknown>;
37
+ }
38
+ /**
39
+ * Extract clean content from an Anthropic Messages API response.
40
+ */
41
+ declare function processResponse(agent: Prompty, response: unknown): unknown;
42
+
43
+ /**
44
+ * Wire format conversion: Message → Anthropic Messages API JSON.
45
+ *
46
+ * Key differences from OpenAI:
47
+ * - `system` is a separate top-level parameter (not in messages)
48
+ * - Tools use `input_schema` (not nested `{type: "function", function: {...}}`)
49
+ * - `max_tokens` is required
50
+ * - Structured output uses `output_config.format` with `json_schema`
51
+ *
52
+ * @module
53
+ */
54
+
55
+ /**
56
+ * Convert an abstract Message to Anthropic wire format.
57
+ * System messages are excluded — they go in a separate `system` parameter.
58
+ */
59
+ declare function messageToWire(msg: Message): Record<string, unknown>;
60
+ /**
61
+ * Build Anthropic Messages API arguments from agent config and messages.
62
+ */
63
+ declare function buildChatArgs(agent: Prompty, messages: Message[]): Record<string, unknown>;
64
+ /**
65
+ * Convert agent tools to Anthropic tool format.
66
+ *
67
+ * Anthropic uses: { name, description, input_schema }
68
+ * (no `{type: "function", function: {...}}` wrapper like OpenAI)
69
+ */
70
+ declare function toolsToWire(agent: Prompty): Record<string, unknown>[];
71
+ /**
72
+ * Convert outputSchema to Anthropic structured output config.
73
+ *
74
+ * Anthropic uses: output_config: { format: { type: "json_schema", schema: {...} } }
75
+ */
76
+ declare function outputSchemaToWire(agent: Prompty): Record<string, unknown> | null;
77
+
78
+ export { AnthropicExecutor, AnthropicProcessor, buildChatArgs, messageToWire, outputSchemaToWire, processResponse, toolsToWire };
@@ -0,0 +1,78 @@
1
+ import Anthropic from '@anthropic-ai/sdk';
2
+ import { Executor, Prompty, Message, Processor } from '@prompty/core';
3
+
4
+ /**
5
+ * Anthropic executor — sends messages to Anthropic Messages API.
6
+ *
7
+ * Dispatches on `agent.model.apiType`: only `chat` is supported
8
+ * (Anthropic has no embedding or image APIs).
9
+ * The agent loop (tool-call iteration) is handled by the pipeline,
10
+ * not the executor.
11
+ *
12
+ * @module
13
+ */
14
+
15
+ declare class AnthropicExecutor implements Executor {
16
+ execute(agent: Prompty, messages: Message[]): Promise<unknown>;
17
+ /** Dispatch to the appropriate API and trace the call. */
18
+ private executeApiCall;
19
+ protected resolveClient(agent: Prompty): Anthropic;
20
+ protected clientKwargs(agent: Prompty): Record<string, unknown>;
21
+ }
22
+
23
+ /**
24
+ * Anthropic processor — extracts clean results from Anthropic Messages API responses.
25
+ *
26
+ * Handles:
27
+ * - Text content from `content[]` blocks
28
+ * - Tool use blocks → ToolCall objects
29
+ * - Streaming responses (content_block_delta events)
30
+ * - Structured output (JSON parse when outputSchema present)
31
+ *
32
+ * @module
33
+ */
34
+
35
+ declare class AnthropicProcessor implements Processor {
36
+ process(agent: Prompty, response: unknown): Promise<unknown>;
37
+ }
38
+ /**
39
+ * Extract clean content from an Anthropic Messages API response.
40
+ */
41
+ declare function processResponse(agent: Prompty, response: unknown): unknown;
42
+
43
+ /**
44
+ * Wire format conversion: Message → Anthropic Messages API JSON.
45
+ *
46
+ * Key differences from OpenAI:
47
+ * - `system` is a separate top-level parameter (not in messages)
48
+ * - Tools use `input_schema` (not nested `{type: "function", function: {...}}`)
49
+ * - `max_tokens` is required
50
+ * - Structured output uses `output_config.format` with `json_schema`
51
+ *
52
+ * @module
53
+ */
54
+
55
+ /**
56
+ * Convert an abstract Message to Anthropic wire format.
57
+ * System messages are excluded — they go in a separate `system` parameter.
58
+ */
59
+ declare function messageToWire(msg: Message): Record<string, unknown>;
60
+ /**
61
+ * Build Anthropic Messages API arguments from agent config and messages.
62
+ */
63
+ declare function buildChatArgs(agent: Prompty, messages: Message[]): Record<string, unknown>;
64
+ /**
65
+ * Convert agent tools to Anthropic tool format.
66
+ *
67
+ * Anthropic uses: { name, description, input_schema }
68
+ * (no `{type: "function", function: {...}}` wrapper like OpenAI)
69
+ */
70
+ declare function toolsToWire(agent: Prompty): Record<string, unknown>[];
71
+ /**
72
+ * Convert outputSchema to Anthropic structured output config.
73
+ *
74
+ * Anthropic uses: output_config: { format: { type: "json_schema", schema: {...} } }
75
+ */
76
+ declare function outputSchemaToWire(agent: Prompty): Record<string, unknown> | null;
77
+
78
+ export { AnthropicExecutor, AnthropicProcessor, buildChatArgs, messageToWire, outputSchemaToWire, processResponse, toolsToWire };
package/dist/index.js ADDED
@@ -0,0 +1,401 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
8
+ // src/executor.ts
9
+ import { ApiKeyConnection, ReferenceConnection, PromptyStream } from "@prompty/core";
10
+ import { getConnection } from "@prompty/core";
11
+ import { traceSpan, sanitizeValue } from "@prompty/core";
12
+
13
+ // src/wire.ts
14
+ function messageToWire(msg) {
15
+ const wire = { role: msg.role };
16
+ if (msg.metadata.tool_results && Array.isArray(msg.metadata.tool_results)) {
17
+ wire.role = "user";
18
+ wire.content = msg.metadata.tool_results;
19
+ return wire;
20
+ }
21
+ if (msg.metadata.tool_use_id || msg.metadata.tool_call_id) {
22
+ const toolUseId = msg.metadata.tool_use_id ?? msg.metadata.tool_call_id;
23
+ wire.role = "user";
24
+ wire.content = [
25
+ {
26
+ type: "tool_result",
27
+ tool_use_id: toolUseId,
28
+ content: msg.toTextContent()
29
+ }
30
+ ];
31
+ return wire;
32
+ }
33
+ if (msg.role === "assistant" && msg.metadata.content && Array.isArray(msg.metadata.content)) {
34
+ wire.content = msg.metadata.content;
35
+ return wire;
36
+ }
37
+ const content = msg.toTextContent();
38
+ if (typeof content === "string") {
39
+ wire.content = content;
40
+ } else {
41
+ wire.content = msg.parts.map(partToWire);
42
+ }
43
+ return wire;
44
+ }
45
+ function partToWire(part) {
46
+ switch (part.kind) {
47
+ case "text":
48
+ return { type: "text", text: part.value };
49
+ case "image": {
50
+ if (part.source.startsWith("data:") || part.source.startsWith("/")) {
51
+ const [header, data] = part.source.split(",", 2);
52
+ const mediaType = header?.match(/data:(.*?);/)?.[1] ?? "image/png";
53
+ return {
54
+ type: "image",
55
+ source: {
56
+ type: "base64",
57
+ media_type: mediaType,
58
+ data: data ?? part.source
59
+ }
60
+ };
61
+ }
62
+ return {
63
+ type: "image",
64
+ source: { type: "url", url: part.source }
65
+ };
66
+ }
67
+ case "file":
68
+ return { type: "text", text: `[file: ${part.source}]` };
69
+ case "audio":
70
+ return { type: "text", text: `[audio: ${part.source}]` };
71
+ }
72
+ }
73
+ var DEFAULT_MAX_TOKENS = 1024;
74
+ function buildChatArgs(agent, messages) {
75
+ const model = agent.model?.id || "claude-sonnet-4-5-20250929";
76
+ const systemParts = [];
77
+ const conversationMessages = [];
78
+ for (const msg of messages) {
79
+ if (msg.role === "system") {
80
+ systemParts.push(msg.text);
81
+ } else {
82
+ conversationMessages.push(messageToWire(msg));
83
+ }
84
+ }
85
+ const args = {
86
+ model,
87
+ messages: conversationMessages,
88
+ max_tokens: agent.model?.options?.maxOutputTokens ?? DEFAULT_MAX_TOKENS,
89
+ ...buildOptions(agent)
90
+ };
91
+ if (systemParts.length > 0) {
92
+ args.system = systemParts.join("\n\n");
93
+ }
94
+ const tools = toolsToWire(agent);
95
+ if (tools.length > 0) {
96
+ args.tools = tools;
97
+ }
98
+ const outputConfig = outputSchemaToWire(agent);
99
+ if (outputConfig) {
100
+ args.output_config = outputConfig;
101
+ }
102
+ return args;
103
+ }
104
+ var KIND_TO_JSON_TYPE = {
105
+ string: "string",
106
+ integer: "integer",
107
+ float: "number",
108
+ number: "number",
109
+ boolean: "boolean",
110
+ array: "array",
111
+ object: "object"
112
+ };
113
+ function buildOptions(agent) {
114
+ const opts = agent.model?.options;
115
+ if (!opts) return {};
116
+ const result = {};
117
+ if (opts.temperature !== void 0) result.temperature = opts.temperature;
118
+ if (opts.topP !== void 0) result.top_p = opts.topP;
119
+ if (opts.topK !== void 0) result.top_k = opts.topK;
120
+ if (opts.stopSequences !== void 0) result.stop_sequences = opts.stopSequences;
121
+ if (opts.additionalProperties) {
122
+ for (const [k, v] of Object.entries(opts.additionalProperties)) {
123
+ if (!(k in result) && k !== "max_tokens") {
124
+ result[k] = v;
125
+ }
126
+ }
127
+ }
128
+ return result;
129
+ }
130
+ function schemaToWire(properties) {
131
+ const props = {};
132
+ const required = [];
133
+ for (const p of properties) {
134
+ if (!p.name) continue;
135
+ const schema = {
136
+ type: KIND_TO_JSON_TYPE[p.kind ?? "string"] ?? "string"
137
+ };
138
+ if (p.description) schema.description = p.description;
139
+ if (p.enumValues && p.enumValues.length > 0) schema.enum = p.enumValues;
140
+ props[p.name] = schema;
141
+ if (p.required) required.push(p.name);
142
+ }
143
+ const result = { type: "object", properties: props };
144
+ if (required.length > 0) result.required = required;
145
+ return result;
146
+ }
147
+ function propertyToJsonSchema(prop) {
148
+ const schema = {
149
+ type: KIND_TO_JSON_TYPE[prop.kind ?? "string"] ?? "string"
150
+ };
151
+ if (prop.description) schema.description = prop.description;
152
+ if (prop.enumValues && prop.enumValues.length > 0) schema.enum = prop.enumValues;
153
+ if (prop.kind === "array") {
154
+ schema.items = prop.items ? propertyToJsonSchema(prop.items) : { type: "string" };
155
+ }
156
+ if (prop.kind === "object") {
157
+ if (prop.properties) {
158
+ const nested = {};
159
+ const req = [];
160
+ for (const p of prop.properties) {
161
+ if (!p.name) continue;
162
+ nested[p.name] = propertyToJsonSchema(p);
163
+ req.push(p.name);
164
+ }
165
+ schema.properties = nested;
166
+ schema.required = req;
167
+ } else {
168
+ schema.properties = {};
169
+ schema.required = [];
170
+ }
171
+ schema.additionalProperties = false;
172
+ }
173
+ return schema;
174
+ }
175
+ function toolsToWire(agent) {
176
+ const tools = agent.tools;
177
+ if (!tools || tools.length === 0) return [];
178
+ const result = [];
179
+ for (const t of tools) {
180
+ if (t.kind !== "function") continue;
181
+ const tool = { name: t.name };
182
+ if (t.description) tool.description = t.description;
183
+ const params = t.parameters;
184
+ if (params && Array.isArray(params)) {
185
+ tool.input_schema = schemaToWire(params);
186
+ } else {
187
+ tool.input_schema = { type: "object", properties: {} };
188
+ }
189
+ result.push(tool);
190
+ }
191
+ return result;
192
+ }
193
+ function outputSchemaToWire(agent) {
194
+ const outputs = agent.outputs;
195
+ if (!outputs || outputs.length === 0) return null;
196
+ const properties = {};
197
+ const required = [];
198
+ for (const prop of outputs) {
199
+ if (!prop.name) continue;
200
+ properties[prop.name] = propertyToJsonSchema(
201
+ prop
202
+ );
203
+ required.push(prop.name);
204
+ }
205
+ return {
206
+ format: {
207
+ type: "json_schema",
208
+ schema: {
209
+ type: "object",
210
+ properties,
211
+ required,
212
+ additionalProperties: false
213
+ }
214
+ }
215
+ };
216
+ }
217
+
218
+ // src/executor.ts
219
+ var AnthropicExecutor = class {
220
+ async execute(agent, messages) {
221
+ return traceSpan("AnthropicExecutor", async (emit) => {
222
+ emit("signature", "prompty.anthropic.executor.AnthropicExecutor.invoke");
223
+ emit("inputs", { data: messages });
224
+ const client = this.resolveClient(agent);
225
+ const clientName = "Anthropic";
226
+ await traceSpan(clientName, async (ctorEmit) => {
227
+ ctorEmit("signature", `${clientName}.ctor`);
228
+ const conn = agent.model?.connection;
229
+ if (conn instanceof ReferenceConnection) {
230
+ ctorEmit("inputs", { source: "reference", name: conn.name });
231
+ } else {
232
+ ctorEmit("inputs", sanitizeValue("ctor", this.clientKwargs(agent)));
233
+ }
234
+ ctorEmit("result", clientName);
235
+ });
236
+ const apiType = agent.model?.apiType ?? "chat";
237
+ const result = await this.executeApiCall(client, clientName, agent, messages, apiType);
238
+ emit("result", result);
239
+ return result;
240
+ });
241
+ }
242
+ /** Dispatch to the appropriate API and trace the call. */
243
+ async executeApiCall(client, clientName, agent, messages, apiType) {
244
+ switch (apiType) {
245
+ case "chat": {
246
+ const args = buildChatArgs(agent, messages);
247
+ const isStreaming = !!args.stream;
248
+ return traceSpan("create", async (callEmit) => {
249
+ callEmit("signature", `${clientName}.messages.create`);
250
+ callEmit("inputs", sanitizeValue("create", args));
251
+ if (isStreaming) {
252
+ const stream = client.messages.stream(
253
+ args
254
+ );
255
+ return new PromptyStream(
256
+ `${clientName}Executor`,
257
+ stream
258
+ );
259
+ }
260
+ const result = await client.messages.create(
261
+ args
262
+ );
263
+ callEmit("result", result);
264
+ return result;
265
+ });
266
+ }
267
+ default:
268
+ throw new Error(
269
+ `Unsupported apiType "${apiType}" for Anthropic. Anthropic only supports "chat" (Messages API).`
270
+ );
271
+ }
272
+ }
273
+ resolveClient(agent) {
274
+ const conn = agent.model?.connection;
275
+ if (conn instanceof ReferenceConnection) {
276
+ return getConnection(conn.name);
277
+ }
278
+ const kwargs = this.clientKwargs(agent);
279
+ const AnthropicSDK = __require("@anthropic-ai/sdk").default;
280
+ return new AnthropicSDK(kwargs);
281
+ }
282
+ clientKwargs(agent) {
283
+ const kwargs = {};
284
+ const conn = agent.model?.connection;
285
+ if (conn instanceof ApiKeyConnection) {
286
+ if (conn.apiKey) kwargs.apiKey = conn.apiKey;
287
+ if (conn.endpoint) kwargs.baseURL = conn.endpoint;
288
+ }
289
+ return kwargs;
290
+ }
291
+ };
292
+
293
+ // src/processor.ts
294
+ import { traceSpan as traceSpan2 } from "@prompty/core";
295
+ var AnthropicProcessor = class {
296
+ async process(agent, response) {
297
+ return traceSpan2("AnthropicProcessor", async (emit) => {
298
+ emit("signature", "prompty.anthropic.processor.AnthropicProcessor.invoke");
299
+ emit("inputs", { data: response });
300
+ const result = processResponse(agent, response);
301
+ if (!isAsyncIterable(response)) {
302
+ emit("result", result);
303
+ }
304
+ return result;
305
+ });
306
+ }
307
+ };
308
+ function processResponse(agent, response) {
309
+ if (typeof response !== "object" || response === null) return response;
310
+ if (isAsyncIterable(response)) {
311
+ return streamGenerator(response);
312
+ }
313
+ const r = response;
314
+ if (Array.isArray(r.content) && r.role === "assistant") {
315
+ return processMessages(agent, r);
316
+ }
317
+ return response;
318
+ }
319
+ function isAsyncIterable(value) {
320
+ return typeof value === "object" && value !== null && Symbol.asyncIterator in value;
321
+ }
322
+ async function* streamGenerator(response) {
323
+ const toolCallAcc = /* @__PURE__ */ new Map();
324
+ for await (const event of response) {
325
+ const e = event;
326
+ const eventType = e.type;
327
+ if (eventType === "content_block_delta") {
328
+ const delta = e.delta;
329
+ if (!delta) continue;
330
+ if (delta.type === "text_delta") {
331
+ yield delta.text;
332
+ } else if (delta.type === "input_json_delta") {
333
+ const idx = e.index;
334
+ const acc = toolCallAcc.get(idx);
335
+ if (acc) {
336
+ acc.arguments += delta.partial_json ?? "";
337
+ }
338
+ }
339
+ } else if (eventType === "content_block_start") {
340
+ const block = e.content_block;
341
+ if (block?.type === "tool_use") {
342
+ const idx = e.index;
343
+ toolCallAcc.set(idx, {
344
+ id: block.id ?? "",
345
+ name: block.name ?? "",
346
+ arguments: ""
347
+ });
348
+ }
349
+ }
350
+ }
351
+ const sortedIndices = [...toolCallAcc.keys()].sort((a, b) => a - b);
352
+ for (const idx of sortedIndices) {
353
+ const tc = toolCallAcc.get(idx);
354
+ yield { id: tc.id, name: tc.name, arguments: tc.arguments };
355
+ }
356
+ }
357
+ function processMessages(agent, response) {
358
+ const content = response.content;
359
+ if (!content || content.length === 0) return null;
360
+ const toolCalls = [];
361
+ const textParts = [];
362
+ for (const block of content) {
363
+ if (block.type === "tool_use") {
364
+ toolCalls.push({
365
+ id: block.id,
366
+ name: block.name,
367
+ arguments: typeof block.input === "string" ? block.input : JSON.stringify(block.input)
368
+ });
369
+ } else if (block.type === "text") {
370
+ textParts.push(block.text);
371
+ }
372
+ }
373
+ if (toolCalls.length > 0) {
374
+ return toolCalls;
375
+ }
376
+ const text = textParts.join("");
377
+ if (!text) return null;
378
+ if (agent.outputs && agent.outputs.length > 0) {
379
+ try {
380
+ return JSON.parse(text);
381
+ } catch {
382
+ return text;
383
+ }
384
+ }
385
+ return text;
386
+ }
387
+
388
+ // src/index.ts
389
+ import { registerExecutor, registerProcessor } from "@prompty/core";
390
+ registerExecutor("anthropic", new AnthropicExecutor());
391
+ registerProcessor("anthropic", new AnthropicProcessor());
392
+ export {
393
+ AnthropicExecutor,
394
+ AnthropicProcessor,
395
+ buildChatArgs,
396
+ messageToWire,
397
+ outputSchemaToWire,
398
+ processResponse,
399
+ toolsToWire
400
+ };
401
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/executor.ts","../src/wire.ts","../src/processor.ts","../src/index.ts"],"sourcesContent":["/**\r\n * Anthropic executor — sends messages to Anthropic Messages API.\r\n *\r\n * Dispatches on `agent.model.apiType`: only `chat` is supported\r\n * (Anthropic has no embedding or image APIs).\r\n * The agent loop (tool-call iteration) is handled by the pipeline,\r\n * not the executor.\r\n *\r\n * @module\r\n */\r\n\r\nimport type Anthropic from \"@anthropic-ai/sdk\";\r\nimport type { Prompty } from \"@prompty/core\";\r\nimport { ApiKeyConnection, ReferenceConnection, PromptyStream } from \"@prompty/core\";\r\nimport type { Executor } from \"@prompty/core\";\r\nimport type { Message } from \"@prompty/core\";\r\nimport { getConnection } from \"@prompty/core\";\r\nimport { traceSpan, sanitizeValue } from \"@prompty/core\";\r\nimport { buildChatArgs } from \"./wire.js\";\r\n\r\nexport class AnthropicExecutor implements Executor {\r\n async execute(agent: Prompty, messages: Message[]): Promise<unknown> {\r\n return traceSpan(\"AnthropicExecutor\", async (emit) => {\r\n emit(\"signature\", \"prompty.anthropic.executor.AnthropicExecutor.invoke\");\r\n emit(\"inputs\", { data: messages });\r\n\r\n const client = this.resolveClient(agent);\r\n const clientName = \"Anthropic\";\r\n\r\n // Trace client construction\r\n await traceSpan(clientName, async (ctorEmit) => {\r\n ctorEmit(\"signature\", `${clientName}.ctor`);\r\n const conn = agent.model?.connection;\r\n if (conn instanceof ReferenceConnection) {\r\n ctorEmit(\"inputs\", { source: \"reference\", name: conn.name });\r\n } else {\r\n ctorEmit(\"inputs\", sanitizeValue(\"ctor\", this.clientKwargs(agent)));\r\n }\r\n ctorEmit(\"result\", clientName);\r\n });\r\n\r\n const apiType = agent.model?.apiType ?? \"chat\";\r\n const result = await this.executeApiCall(client, clientName, agent, messages, apiType);\r\n emit(\"result\", result);\r\n return result;\r\n });\r\n }\r\n\r\n /** Dispatch to the appropriate API and trace the call. */\r\n private async executeApiCall(\r\n client: Anthropic,\r\n clientName: string,\r\n agent: Prompty,\r\n messages: Message[],\r\n apiType: string,\r\n ): Promise<unknown> {\r\n switch (apiType) {\r\n case \"chat\": {\r\n const args = buildChatArgs(agent, messages);\r\n const isStreaming = !!args.stream;\r\n\r\n return traceSpan(\"create\", async (callEmit) => {\r\n callEmit(\"signature\", `${clientName}.messages.create`);\r\n callEmit(\"inputs\", sanitizeValue(\"create\", args));\r\n\r\n if (isStreaming) {\r\n const stream = client.messages.stream(\r\n args as unknown as Parameters<typeof client.messages.stream>[0],\r\n );\r\n return new PromptyStream(\r\n `${clientName}Executor`,\r\n stream as unknown as AsyncIterable<unknown>,\r\n );\r\n }\r\n\r\n const result = await client.messages.create(\r\n args as unknown as Parameters<typeof client.messages.create>[0],\r\n );\r\n callEmit(\"result\", result);\r\n return result;\r\n });\r\n }\r\n default:\r\n throw new Error(\r\n `Unsupported apiType \"${apiType}\" for Anthropic. ` +\r\n `Anthropic only supports \"chat\" (Messages API).`,\r\n );\r\n }\r\n }\r\n\r\n protected resolveClient(agent: Prompty): Anthropic {\r\n const conn = agent.model?.connection;\r\n\r\n if (conn instanceof ReferenceConnection) {\r\n return getConnection(conn.name) as Anthropic;\r\n }\r\n\r\n const kwargs = this.clientKwargs(agent);\r\n\r\n // Lazy import — only needed when actually called\r\n // eslint-disable-next-line @typescript-eslint/no-require-imports\r\n const AnthropicSDK = require(\"@anthropic-ai/sdk\").default;\r\n return new AnthropicSDK(kwargs);\r\n }\r\n\r\n protected clientKwargs(agent: Prompty): Record<string, unknown> {\r\n const kwargs: Record<string, unknown> = {};\r\n const conn = agent.model?.connection;\r\n\r\n if (conn instanceof ApiKeyConnection) {\r\n if (conn.apiKey) kwargs.apiKey = conn.apiKey;\r\n if (conn.endpoint) kwargs.baseURL = conn.endpoint;\r\n }\r\n\r\n return kwargs;\r\n }\r\n}\r\n","/**\r\n * Wire format conversion: Message → Anthropic Messages API JSON.\r\n *\r\n * Key differences from OpenAI:\r\n * - `system` is a separate top-level parameter (not in messages)\r\n * - Tools use `input_schema` (not nested `{type: \"function\", function: {...}}`)\r\n * - `max_tokens` is required\r\n * - Structured output uses `output_config.format` with `json_schema`\r\n *\r\n * @module\r\n */\r\n\r\nimport type { Prompty } from \"@prompty/core\";\r\nimport type { ContentPart, Message } from \"@prompty/core\";\r\n\r\n// ---------------------------------------------------------------------------\r\n// Message conversion\r\n// ---------------------------------------------------------------------------\r\n\r\n/**\r\n * Convert an abstract Message to Anthropic wire format.\r\n * System messages are excluded — they go in a separate `system` parameter.\r\n */\r\nexport function messageToWire(msg: Message): Record<string, unknown> {\r\n const wire: Record<string, unknown> = { role: msg.role };\r\n\r\n // Batched tool results → single user message with all tool_result blocks\r\n if (msg.metadata.tool_results && Array.isArray(msg.metadata.tool_results)) {\r\n wire.role = \"user\";\r\n wire.content = msg.metadata.tool_results;\r\n return wire;\r\n }\r\n\r\n // Legacy single tool result messages (backward compat)\r\n if (msg.metadata.tool_use_id || msg.metadata.tool_call_id) {\r\n const toolUseId = (msg.metadata.tool_use_id ?? msg.metadata.tool_call_id) as string;\r\n wire.role = \"user\";\r\n wire.content = [\r\n {\r\n type: \"tool_result\",\r\n tool_use_id: toolUseId,\r\n content: msg.toTextContent(),\r\n },\r\n ];\r\n return wire;\r\n }\r\n\r\n // Assistant messages with raw content blocks (tool_use) — preserve them\r\n if (msg.role === \"assistant\" && msg.metadata.content && Array.isArray(msg.metadata.content)) {\r\n wire.content = msg.metadata.content;\r\n return wire;\r\n }\r\n\r\n const content = msg.toTextContent();\r\n if (typeof content === \"string\") {\r\n wire.content = content;\r\n } else {\r\n // Multimodal — convert parts to Anthropic format\r\n wire.content = msg.parts.map(partToWire);\r\n }\r\n\r\n return wire;\r\n}\r\n\r\n/**\r\n * Convert a ContentPart to Anthropic wire format.\r\n */\r\nfunction partToWire(part: ContentPart): Record<string, unknown> {\r\n switch (part.kind) {\r\n case \"text\":\r\n return { type: \"text\", text: part.value };\r\n case \"image\": {\r\n // Anthropic uses base64 source blocks or URL\r\n if (part.source.startsWith(\"data:\") || part.source.startsWith(\"/\")) {\r\n // Base64 encoded\r\n const [header, data] = part.source.split(\",\", 2);\r\n const mediaType = header?.match(/data:(.*?);/)?.[1] ?? \"image/png\";\r\n return {\r\n type: \"image\",\r\n source: {\r\n type: \"base64\",\r\n media_type: mediaType,\r\n data: data ?? part.source,\r\n },\r\n };\r\n }\r\n // URL\r\n return {\r\n type: \"image\",\r\n source: { type: \"url\", url: part.source },\r\n };\r\n }\r\n case \"file\":\r\n return { type: \"text\", text: `[file: ${part.source}]` };\r\n case \"audio\":\r\n return { type: \"text\", text: `[audio: ${part.source}]` };\r\n }\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Build API arguments\r\n// ---------------------------------------------------------------------------\r\n\r\nconst DEFAULT_MAX_TOKENS = 1024;\r\n\r\n/**\r\n * Build Anthropic Messages API arguments from agent config and messages.\r\n */\r\nexport function buildChatArgs(\r\n agent: Prompty,\r\n messages: Message[],\r\n): Record<string, unknown> {\r\n const model = agent.model?.id || \"claude-sonnet-4-5-20250929\";\r\n\r\n // Separate system messages from conversation messages\r\n const systemParts: string[] = [];\r\n const conversationMessages: Record<string, unknown>[] = [];\r\n\r\n for (const msg of messages) {\r\n if (msg.role === \"system\") {\r\n systemParts.push(msg.text);\r\n } else {\r\n conversationMessages.push(messageToWire(msg));\r\n }\r\n }\r\n\r\n const args: Record<string, unknown> = {\r\n model,\r\n messages: conversationMessages,\r\n max_tokens: agent.model?.options?.maxOutputTokens ?? DEFAULT_MAX_TOKENS,\r\n ...buildOptions(agent),\r\n };\r\n\r\n // System prompt as separate parameter\r\n if (systemParts.length > 0) {\r\n args.system = systemParts.join(\"\\n\\n\");\r\n }\r\n\r\n // Tools\r\n const tools = toolsToWire(agent);\r\n if (tools.length > 0) {\r\n args.tools = tools;\r\n }\r\n\r\n // Structured output\r\n const outputConfig = outputSchemaToWire(agent);\r\n if (outputConfig) {\r\n args.output_config = outputConfig;\r\n }\r\n\r\n return args;\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Helpers\r\n// ---------------------------------------------------------------------------\r\n\r\n/** Map AgentSchema kind strings to JSON Schema type strings. */\r\nconst KIND_TO_JSON_TYPE: Record<string, string> = {\r\n string: \"string\",\r\n integer: \"integer\",\r\n float: \"number\",\r\n number: \"number\",\r\n boolean: \"boolean\",\r\n array: \"array\",\r\n object: \"object\",\r\n};\r\n\r\nfunction buildOptions(agent: Prompty): Record<string, unknown> {\r\n const opts = agent.model?.options;\r\n if (!opts) return {};\r\n\r\n const result: Record<string, unknown> = {};\r\n\r\n if (opts.temperature !== undefined) result.temperature = opts.temperature;\r\n if (opts.topP !== undefined) result.top_p = opts.topP;\r\n if (opts.topK !== undefined) result.top_k = opts.topK;\r\n if (opts.stopSequences !== undefined) result.stop_sequences = opts.stopSequences;\r\n\r\n // Pass through additionalProperties — but don't overwrite mapped keys\r\n if (opts.additionalProperties) {\r\n for (const [k, v] of Object.entries(opts.additionalProperties)) {\r\n if (!(k in result) && k !== \"max_tokens\") {\r\n result[k] = v;\r\n }\r\n }\r\n }\r\n\r\n return result;\r\n}\r\n\r\n/** Convert a Property list to a JSON Schema `{type: \"object\", properties: ...}`. */\r\nfunction schemaToWire(properties: unknown[]): Record<string, unknown> {\r\n const props: Record<string, unknown> = {};\r\n const required: string[] = [];\r\n\r\n for (const p of properties as Array<{\r\n name?: string;\r\n kind?: string;\r\n description?: string;\r\n required?: boolean;\r\n enumValues?: unknown[];\r\n }>) {\r\n if (!p.name) continue;\r\n const schema: Record<string, unknown> = {\r\n type: KIND_TO_JSON_TYPE[p.kind ?? \"string\"] ?? \"string\",\r\n };\r\n if (p.description) schema.description = p.description;\r\n if (p.enumValues && p.enumValues.length > 0) schema.enum = p.enumValues;\r\n props[p.name] = schema;\r\n if (p.required) required.push(p.name);\r\n }\r\n\r\n const result: Record<string, unknown> = { type: \"object\", properties: props };\r\n if (required.length > 0) result.required = required;\r\n return result;\r\n}\r\n\r\n/** Convert a single Property to a JSON Schema definition. */\r\nfunction propertyToJsonSchema(prop: {\r\n kind?: string;\r\n description?: string;\r\n enumValues?: unknown[];\r\n items?: unknown;\r\n properties?: unknown[];\r\n}): Record<string, unknown> {\r\n const schema: Record<string, unknown> = {\r\n type: KIND_TO_JSON_TYPE[prop.kind ?? \"string\"] ?? \"string\",\r\n };\r\n\r\n if (prop.description) schema.description = prop.description;\r\n if (prop.enumValues && prop.enumValues.length > 0) schema.enum = prop.enumValues;\r\n\r\n if (prop.kind === \"array\") {\r\n schema.items = prop.items\r\n ? propertyToJsonSchema(prop.items as typeof prop)\r\n : { type: \"string\" };\r\n }\r\n\r\n if (prop.kind === \"object\") {\r\n if (prop.properties) {\r\n const nested: Record<string, unknown> = {};\r\n const req: string[] = [];\r\n for (const p of prop.properties as Array<{ name?: string } & typeof prop>) {\r\n if (!p.name) continue;\r\n nested[p.name] = propertyToJsonSchema(p);\r\n req.push(p.name);\r\n }\r\n schema.properties = nested;\r\n schema.required = req;\r\n } else {\r\n schema.properties = {};\r\n schema.required = [];\r\n }\r\n schema.additionalProperties = false;\r\n }\r\n\r\n return schema;\r\n}\r\n\r\n/**\r\n * Convert agent tools to Anthropic tool format.\r\n *\r\n * Anthropic uses: { name, description, input_schema }\r\n * (no `{type: \"function\", function: {...}}` wrapper like OpenAI)\r\n */\r\nexport function toolsToWire(agent: Prompty): Record<string, unknown>[] {\r\n const tools = agent.tools;\r\n if (!tools || tools.length === 0) return [];\r\n\r\n const result: Record<string, unknown>[] = [];\r\n\r\n for (const t of tools) {\r\n if (t.kind !== \"function\") continue;\r\n\r\n const tool: Record<string, unknown> = { name: t.name };\r\n if (t.description) tool.description = t.description;\r\n\r\n const params = (t as { parameters?: unknown[] }).parameters;\r\n if (params && Array.isArray(params)) {\r\n tool.input_schema = schemaToWire(params);\r\n } else {\r\n tool.input_schema = { type: \"object\", properties: {} };\r\n }\r\n\r\n result.push(tool);\r\n }\r\n\r\n return result;\r\n}\r\n\r\n/**\r\n * Convert outputSchema to Anthropic structured output config.\r\n *\r\n * Anthropic uses: output_config: { format: { type: \"json_schema\", schema: {...} } }\r\n */\r\nexport function outputSchemaToWire(agent: Prompty): Record<string, unknown> | null {\r\n const outputs = agent.outputs;\r\n if (!outputs || outputs.length === 0) return null;\r\n\r\n const properties: Record<string, unknown> = {};\r\n const required: string[] = [];\r\n\r\n for (const prop of outputs) {\r\n if (!prop.name) continue;\r\n properties[prop.name] = propertyToJsonSchema(\r\n prop as Parameters<typeof propertyToJsonSchema>[0],\r\n );\r\n required.push(prop.name);\r\n }\r\n\r\n return {\r\n format: {\r\n type: \"json_schema\",\r\n schema: {\r\n type: \"object\",\r\n properties,\r\n required,\r\n additionalProperties: false,\r\n },\r\n },\r\n };\r\n}\r\n","/**\r\n * Anthropic processor — extracts clean results from Anthropic Messages API responses.\r\n *\r\n * Handles:\r\n * - Text content from `content[]` blocks\r\n * - Tool use blocks → ToolCall objects\r\n * - Streaming responses (content_block_delta events)\r\n * - Structured output (JSON parse when outputSchema present)\r\n *\r\n * @module\r\n */\r\n\r\nimport type { Prompty } from \"@prompty/core\";\r\nimport type { Processor } from \"@prompty/core\";\r\nimport type { ToolCall } from \"@prompty/core\";\r\nimport { traceSpan } from \"@prompty/core\";\r\n\r\nexport class AnthropicProcessor implements Processor {\r\n async process(agent: Prompty, response: unknown): Promise<unknown> {\r\n return traceSpan(\"AnthropicProcessor\", async (emit) => {\r\n emit(\"signature\", \"prompty.anthropic.processor.AnthropicProcessor.invoke\");\r\n emit(\"inputs\", { data: response });\r\n const result = processResponse(agent, response);\r\n // Don't emit result for streaming — it's a generator, not a value\r\n if (!isAsyncIterable(response)) {\r\n emit(\"result\", result);\r\n }\r\n return result;\r\n });\r\n }\r\n}\r\n\r\n/**\r\n * Extract clean content from an Anthropic Messages API response.\r\n */\r\nexport function processResponse(agent: Prompty, response: unknown): unknown {\r\n if (typeof response !== \"object\" || response === null) return response;\r\n\r\n // Streaming response — return content-extracting async generator\r\n if (isAsyncIterable(response)) {\r\n return streamGenerator(response);\r\n }\r\n\r\n const r = response as Record<string, unknown>;\r\n\r\n // Anthropic Messages response — has `content` array and `role`\r\n if (Array.isArray(r.content) && r.role === \"assistant\") {\r\n return processMessages(agent, r);\r\n }\r\n\r\n return response;\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Streaming\r\n// ---------------------------------------------------------------------------\r\n\r\n/** Type guard for async iterables (PromptyStream or raw SDK stream). */\r\nfunction isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {\r\n return (\r\n typeof value === \"object\" &&\r\n value !== null &&\r\n Symbol.asyncIterator in value\r\n );\r\n}\r\n\r\n/**\r\n * Yield content chunks from an Anthropic streaming response.\r\n *\r\n * Anthropic streaming events include:\r\n * - `content_block_delta` with `delta.type === \"text_delta\"` → yield text\r\n * - `content_block_start` with `content_block.type === \"tool_use\"` → accumulate tool call\r\n * - `input_json` deltas for tool arguments\r\n * - `message_stop` → end of stream\r\n *\r\n * Tool calls are accumulated and yielded at the end of the stream.\r\n */\r\nasync function* streamGenerator(\r\n response: AsyncIterable<unknown>,\r\n): AsyncGenerator<string | ToolCall> {\r\n const toolCallAcc: Map<\r\n number,\r\n { id: string; name: string; arguments: string }\r\n > = new Map();\r\n\r\n for await (const event of response) {\r\n const e = event as Record<string, unknown>;\r\n const eventType = e.type as string | undefined;\r\n\r\n if (eventType === \"content_block_delta\") {\r\n const delta = e.delta as Record<string, unknown> | undefined;\r\n if (!delta) continue;\r\n\r\n if (delta.type === \"text_delta\") {\r\n yield delta.text as string;\r\n } else if (delta.type === \"input_json_delta\") {\r\n // Accumulate partial JSON for tool arguments\r\n const idx = e.index as number;\r\n const acc = toolCallAcc.get(idx);\r\n if (acc) {\r\n acc.arguments += (delta.partial_json ?? \"\") as string;\r\n }\r\n }\r\n } else if (eventType === \"content_block_start\") {\r\n const block = e.content_block as Record<string, unknown> | undefined;\r\n if (block?.type === \"tool_use\") {\r\n const idx = e.index as number;\r\n toolCallAcc.set(idx, {\r\n id: (block.id ?? \"\") as string,\r\n name: (block.name ?? \"\") as string,\r\n arguments: \"\",\r\n });\r\n }\r\n }\r\n }\r\n\r\n // Yield accumulated tool calls at the end of the stream\r\n const sortedIndices = [...toolCallAcc.keys()].sort((a, b) => a - b);\r\n for (const idx of sortedIndices) {\r\n const tc = toolCallAcc.get(idx)!;\r\n yield { id: tc.id, name: tc.name, arguments: tc.arguments } as ToolCall;\r\n }\r\n}\r\n\r\n// ---------------------------------------------------------------------------\r\n// Non-streaming response processing\r\n// ---------------------------------------------------------------------------\r\n\r\n/**\r\n * Process an Anthropic Messages API response.\r\n *\r\n * Response shape:\r\n * ```json\r\n * {\r\n * \"role\": \"assistant\",\r\n * \"content\": [\r\n * { \"type\": \"text\", \"text\": \"...\" },\r\n * { \"type\": \"tool_use\", \"id\": \"...\", \"name\": \"...\", \"input\": {...} }\r\n * ],\r\n * \"stop_reason\": \"end_turn\" | \"tool_use\" | \"max_tokens\" | \"stop_sequence\"\r\n * }\r\n * ```\r\n */\r\nfunction processMessages(\r\n agent: Prompty,\r\n response: Record<string, unknown>,\r\n): unknown {\r\n const content = response.content as Record<string, unknown>[];\r\n if (!content || content.length === 0) return null;\r\n\r\n // Check for tool_use blocks\r\n const toolCalls: ToolCall[] = [];\r\n const textParts: string[] = [];\r\n\r\n for (const block of content) {\r\n if (block.type === \"tool_use\") {\r\n toolCalls.push({\r\n id: block.id as string,\r\n name: block.name as string,\r\n arguments:\r\n typeof block.input === \"string\"\r\n ? (block.input as string)\r\n : JSON.stringify(block.input),\r\n });\r\n } else if (block.type === \"text\") {\r\n textParts.push(block.text as string);\r\n }\r\n }\r\n\r\n // If tool calls present, return them (pipeline handles the loop)\r\n if (toolCalls.length > 0) {\r\n return toolCalls;\r\n }\r\n\r\n // Text content\r\n const text = textParts.join(\"\");\r\n if (!text) return null;\r\n\r\n // Structured output — JSON parse when outputs schema exists\r\n if (agent.outputs && agent.outputs.length > 0) {\r\n try {\r\n return JSON.parse(text);\r\n } catch {\r\n return text;\r\n }\r\n }\r\n\r\n return text;\r\n}\r\n","/**\r\n * @prompty/anthropic — Anthropic provider for Prompty.\r\n *\r\n * Importing this package auto-registers the \"anthropic\" executor and processor.\r\n *\r\n * @module @prompty/anthropic\r\n */\r\n\r\nexport { AnthropicExecutor } from \"./executor.js\";\r\nexport { AnthropicProcessor, processResponse } from \"./processor.js\";\r\nexport { buildChatArgs, messageToWire, toolsToWire, outputSchemaToWire } from \"./wire.js\";\r\n\r\n// Auto-register on import\r\nimport { registerExecutor, registerProcessor } from \"@prompty/core\";\r\nimport { AnthropicExecutor } from \"./executor.js\";\r\nimport { AnthropicProcessor } from \"./processor.js\";\r\n\r\nregisterExecutor(\"anthropic\", new AnthropicExecutor());\r\nregisterProcessor(\"anthropic\", new AnthropicProcessor());\r\n"],"mappings":";;;;;;;;AAaA,SAAS,kBAAkB,qBAAqB,qBAAqB;AAGrE,SAAS,qBAAqB;AAC9B,SAAS,WAAW,qBAAqB;;;ACMlC,SAAS,cAAc,KAAuC;AACnE,QAAM,OAAgC,EAAE,MAAM,IAAI,KAAK;AAGvD,MAAI,IAAI,SAAS,gBAAgB,MAAM,QAAQ,IAAI,SAAS,YAAY,GAAG;AACzE,SAAK,OAAO;AACZ,SAAK,UAAU,IAAI,SAAS;AAC5B,WAAO;AAAA,EACT;AAGA,MAAI,IAAI,SAAS,eAAe,IAAI,SAAS,cAAc;AACzD,UAAM,YAAa,IAAI,SAAS,eAAe,IAAI,SAAS;AAC5D,SAAK,OAAO;AACZ,SAAK,UAAU;AAAA,MACb;AAAA,QACE,MAAM;AAAA,QACN,aAAa;AAAA,QACb,SAAS,IAAI,cAAc;AAAA,MAC7B;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAGA,MAAI,IAAI,SAAS,eAAe,IAAI,SAAS,WAAW,MAAM,QAAQ,IAAI,SAAS,OAAO,GAAG;AAC3F,SAAK,UAAU,IAAI,SAAS;AAC5B,WAAO;AAAA,EACT;AAEA,QAAM,UAAU,IAAI,cAAc;AAClC,MAAI,OAAO,YAAY,UAAU;AAC/B,SAAK,UAAU;AAAA,EACjB,OAAO;AAEL,SAAK,UAAU,IAAI,MAAM,IAAI,UAAU;AAAA,EACzC;AAEA,SAAO;AACT;AAKA,SAAS,WAAW,MAA4C;AAC9D,UAAQ,KAAK,MAAM;AAAA,IACjB,KAAK;AACH,aAAO,EAAE,MAAM,QAAQ,MAAM,KAAK,MAAM;AAAA,IAC1C,KAAK,SAAS;AAEZ,UAAI,KAAK,OAAO,WAAW,OAAO,KAAK,KAAK,OAAO,WAAW,GAAG,GAAG;AAElE,cAAM,CAAC,QAAQ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
package/package.json ADDED
@@ -0,0 +1,64 @@
1
+ {
2
+ "name": "@prompty/anthropic",
3
+ "version": "2.0.0-alpha.1",
4
+ "description": "Anthropic provider for Prompty — executor and processor for Anthropic Messages API",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.cjs"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "scripts": {
20
+ "build": "tsup",
21
+ "dev": "tsup --watch",
22
+ "test": "vitest run --passWithNoTests",
23
+ "test:watch": "vitest",
24
+ "lint": "tsc --noEmit",
25
+ "clean": "rimraf dist"
26
+ },
27
+ "keywords": [
28
+ "prompty",
29
+ "anthropic",
30
+ "claude",
31
+ "llm",
32
+ "ai"
33
+ ],
34
+ "author": "Microsoft",
35
+ "license": "MIT",
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "git+https://github.com/microsoft/prompty.git",
42
+ "directory": "runtime/typescript/packages/anthropic"
43
+ },
44
+ "engines": {
45
+ "node": ">=18.0.0"
46
+ },
47
+ "peerDependencies": {
48
+ "@prompty/core": "^2.0.0-alpha.1",
49
+ "@anthropic-ai/sdk": ">=0.39.0"
50
+ },
51
+ "peerDependenciesMeta": {
52
+ "@anthropic-ai/sdk": {
53
+ "optional": false
54
+ }
55
+ },
56
+ "devDependencies": {
57
+ "@prompty/core": "file:../core",
58
+ "@anthropic-ai/sdk": "^0.39.0",
59
+ "@types/node": "^20.11.0",
60
+ "tsup": "^8.4.0",
61
+ "typescript": "^5.7.0",
62
+ "vitest": "^3.0.0"
63
+ }
64
+ }