mirascope 2.0.0-alpha.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/README.md +397 -0
- package/dist/bun.cjs +447 -0
- package/dist/bun.cjs.map +1 -0
- package/dist/bun.d.cts +53 -0
- package/dist/bun.d.ts +53 -0
- package/dist/bun.js +94 -0
- package/dist/bun.js.map +1 -0
- package/dist/chunk-2R5IW35Y.js +116 -0
- package/dist/chunk-2R5IW35Y.js.map +1 -0
- package/dist/chunk-A6ZCB7BU.js +6826 -0
- package/dist/chunk-A6ZCB7BU.js.map +1 -0
- package/dist/chunk-NSBPE2FW.js +15 -0
- package/dist/chunk-NSBPE2FW.js.map +1 -0
- package/dist/chunk-RMNCGJYW.js +49 -0
- package/dist/chunk-RMNCGJYW.js.map +1 -0
- package/dist/chunk-U4MFJ4DP.js +358 -0
- package/dist/chunk-U4MFJ4DP.js.map +1 -0
- package/dist/index.cjs +7705 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +4859 -0
- package/dist/index.d.ts +4859 -0
- package/dist/index.js +324 -0
- package/dist/index.js.map +1 -0
- package/dist/model-T6IQ7UUA.js +4 -0
- package/dist/model-T6IQ7UUA.js.map +1 -0
- package/dist/tool-schema-Dh-RLHhC.d.cts +45 -0
- package/dist/tool-schema-Dh-RLHhC.d.ts +45 -0
- package/dist/transform/index.cjs +525 -0
- package/dist/transform/index.cjs.map +1 -0
- package/dist/transform/index.d.cts +89 -0
- package/dist/transform/index.d.ts +89 -0
- package/dist/transform/index.js +6 -0
- package/dist/transform/index.js.map +1 -0
- package/dist/transform/plugins/esbuild.cjs +472 -0
- package/dist/transform/plugins/esbuild.cjs.map +1 -0
- package/dist/transform/plugins/esbuild.d.cts +46 -0
- package/dist/transform/plugins/esbuild.d.ts +46 -0
- package/dist/transform/plugins/esbuild.js +5 -0
- package/dist/transform/plugins/esbuild.js.map +1 -0
- package/dist/transform/plugins/vite.cjs +405 -0
- package/dist/transform/plugins/vite.cjs.map +1 -0
- package/dist/transform/plugins/vite.d.cts +50 -0
- package/dist/transform/plugins/vite.d.ts +50 -0
- package/dist/transform/plugins/vite.js +5 -0
- package/dist/transform/plugins/vite.js.map +1 -0
- package/package.json +127 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
import { totalTokens, toolCallStart, toolCallEnd, toolCallChunk, thoughtStart, thoughtEnd, thoughtChunk, textStart, textEnd, textChunk, resolveFormat, resetProviderRegistry, registerProvider, model, messages_exports, isZodLike, isWebSearchTool, isProviderTool, isOutputParser, isFormat, isContextTool, getProviderForModel, defineTool, defineOutputParser, defineFormat, defineContextTool, createUsage, createToolkit, createContextToolkit, WebSearchTool, Toolkit, ToolOutput, ToolNotFoundError, ToolExecutionError, ToolError, TimeoutError, TOOL_TYPE, TOOL_MODE_INSTRUCTIONS, StreamResponse, ServerError, RootResponse, ResponseValidationError, Response, RateLimitError, ProviderTool, ProviderError, PermissionError, ParseError, NotFoundError, NoRegisteredProviderError, Model, MissingAPIKeyError, MirascopeError, JSON_MODE_INSTRUCTIONS, Image, FinishReason, FeatureNotSupportedError, FORMAT_TOOL_NAME, Document, ContextToolkit, ContextStreamResponse, ContextResponse, ConnectionError, CONTEXT_TOOL_TYPE, BaseResponse, BadRequestError, AuthenticationError, Audio, APIError, promoteToMessages } from './chunk-A6ZCB7BU.js';
|
|
2
|
+
import { __export, __require } from './chunk-NSBPE2FW.js';
|
|
3
|
+
|
|
4
|
+
// src/llm/index.ts
|
|
5
|
+
var llm_exports = {};
|
|
6
|
+
__export(llm_exports, {
|
|
7
|
+
APIError: () => APIError,
|
|
8
|
+
Audio: () => Audio,
|
|
9
|
+
AuthenticationError: () => AuthenticationError,
|
|
10
|
+
BadRequestError: () => BadRequestError,
|
|
11
|
+
BaseResponse: () => BaseResponse,
|
|
12
|
+
CONTEXT_MARKER: () => CONTEXT_MARKER,
|
|
13
|
+
CONTEXT_TOOL_TYPE: () => CONTEXT_TOOL_TYPE,
|
|
14
|
+
ConnectionError: () => ConnectionError,
|
|
15
|
+
ContextResponse: () => ContextResponse,
|
|
16
|
+
ContextStreamResponse: () => ContextStreamResponse,
|
|
17
|
+
ContextToolkit: () => ContextToolkit,
|
|
18
|
+
Document: () => Document,
|
|
19
|
+
FORMAT_TOOL_NAME: () => FORMAT_TOOL_NAME,
|
|
20
|
+
FeatureNotSupportedError: () => FeatureNotSupportedError,
|
|
21
|
+
FinishReason: () => FinishReason,
|
|
22
|
+
Image: () => Image,
|
|
23
|
+
JSON_MODE_INSTRUCTIONS: () => JSON_MODE_INSTRUCTIONS,
|
|
24
|
+
KNOWN_PROVIDER_IDS: () => KNOWN_PROVIDER_IDS,
|
|
25
|
+
MirascopeError: () => MirascopeError,
|
|
26
|
+
MissingAPIKeyError: () => MissingAPIKeyError,
|
|
27
|
+
Model: () => Model,
|
|
28
|
+
NoRegisteredProviderError: () => NoRegisteredProviderError,
|
|
29
|
+
NotFoundError: () => NotFoundError,
|
|
30
|
+
ParseError: () => ParseError,
|
|
31
|
+
PermissionError: () => PermissionError,
|
|
32
|
+
ProviderError: () => ProviderError,
|
|
33
|
+
ProviderTool: () => ProviderTool,
|
|
34
|
+
RateLimitError: () => RateLimitError,
|
|
35
|
+
Response: () => Response,
|
|
36
|
+
ResponseValidationError: () => ResponseValidationError,
|
|
37
|
+
RootResponse: () => RootResponse,
|
|
38
|
+
ServerError: () => ServerError,
|
|
39
|
+
StreamResponse: () => StreamResponse,
|
|
40
|
+
TOOL_MODE_INSTRUCTIONS: () => TOOL_MODE_INSTRUCTIONS,
|
|
41
|
+
TOOL_TYPE: () => TOOL_TYPE,
|
|
42
|
+
TimeoutError: () => TimeoutError,
|
|
43
|
+
ToolError: () => ToolError,
|
|
44
|
+
ToolExecutionError: () => ToolExecutionError,
|
|
45
|
+
ToolNotFoundError: () => ToolNotFoundError,
|
|
46
|
+
ToolOutput: () => ToolOutput,
|
|
47
|
+
Toolkit: () => Toolkit,
|
|
48
|
+
WebSearchTool: () => WebSearchTool,
|
|
49
|
+
createContext: () => createContext,
|
|
50
|
+
createContextToolkit: () => createContextToolkit,
|
|
51
|
+
createToolkit: () => createToolkit,
|
|
52
|
+
createUsage: () => createUsage,
|
|
53
|
+
defineCall: () => defineCall,
|
|
54
|
+
defineContextTool: () => defineContextTool,
|
|
55
|
+
defineFormat: () => defineFormat,
|
|
56
|
+
defineOutputParser: () => defineOutputParser,
|
|
57
|
+
definePrompt: () => definePrompt,
|
|
58
|
+
defineTool: () => defineTool,
|
|
59
|
+
getProviderForModel: () => getProviderForModel,
|
|
60
|
+
isContext: () => isContext,
|
|
61
|
+
isContextTool: () => isContextTool,
|
|
62
|
+
isFormat: () => isFormat,
|
|
63
|
+
isOutputParser: () => isOutputParser,
|
|
64
|
+
isProviderTool: () => isProviderTool,
|
|
65
|
+
isWebSearchTool: () => isWebSearchTool,
|
|
66
|
+
isZodLike: () => isZodLike,
|
|
67
|
+
messages: () => messages_exports,
|
|
68
|
+
model: () => model,
|
|
69
|
+
modelFromContext: () => modelFromContext,
|
|
70
|
+
registerProvider: () => registerProvider,
|
|
71
|
+
resetProviderRegistry: () => resetProviderRegistry,
|
|
72
|
+
resolveFormat: () => resolveFormat,
|
|
73
|
+
textChunk: () => textChunk,
|
|
74
|
+
textEnd: () => textEnd,
|
|
75
|
+
textStart: () => textStart,
|
|
76
|
+
thoughtChunk: () => thoughtChunk,
|
|
77
|
+
thoughtEnd: () => thoughtEnd,
|
|
78
|
+
thoughtStart: () => thoughtStart,
|
|
79
|
+
toolCallChunk: () => toolCallChunk,
|
|
80
|
+
toolCallEnd: () => toolCallEnd,
|
|
81
|
+
toolCallStart: () => toolCallStart,
|
|
82
|
+
totalTokens: () => totalTokens,
|
|
83
|
+
useModel: () => useModel,
|
|
84
|
+
withModel: () => withModel
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
// src/llm/providers/provider-id.ts
|
|
88
|
+
var KNOWN_PROVIDER_IDS = [
|
|
89
|
+
"anthropic",
|
|
90
|
+
"google",
|
|
91
|
+
"mirascope",
|
|
92
|
+
"ollama",
|
|
93
|
+
"openai",
|
|
94
|
+
"together"
|
|
95
|
+
];
|
|
96
|
+
|
|
97
|
+
// src/llm/context/context.ts
|
|
98
|
+
var CONTEXT_MARKER = /* @__PURE__ */ Symbol("mirascope.Context");
|
|
99
|
+
function isContext(value) {
|
|
100
|
+
return value !== null && typeof value === "object" && CONTEXT_MARKER in value;
|
|
101
|
+
}
|
|
102
|
+
function createContext(deps) {
|
|
103
|
+
return { [CONTEXT_MARKER]: true, deps };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// src/llm/models/model-context.ts
|
|
107
|
+
function createNodeStorage() {
|
|
108
|
+
const { AsyncLocalStorage } = __require("async_hooks");
|
|
109
|
+
const storage = new AsyncLocalStorage();
|
|
110
|
+
return {
|
|
111
|
+
get: () => storage.getStore(),
|
|
112
|
+
run: (value, fn) => storage.run(value, fn)
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
function createBrowserStorage() {
|
|
116
|
+
const stack = [];
|
|
117
|
+
return {
|
|
118
|
+
get: () => stack[stack.length - 1],
|
|
119
|
+
run: (value, fn) => {
|
|
120
|
+
stack.push(value);
|
|
121
|
+
try {
|
|
122
|
+
const result = fn();
|
|
123
|
+
if (result instanceof Promise) {
|
|
124
|
+
return result.finally(() => {
|
|
125
|
+
stack.pop();
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
stack.pop();
|
|
129
|
+
return result;
|
|
130
|
+
} catch (e) {
|
|
131
|
+
stack.pop();
|
|
132
|
+
throw e;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
function createStorage() {
|
|
138
|
+
try {
|
|
139
|
+
return createNodeStorage();
|
|
140
|
+
} catch {
|
|
141
|
+
return createBrowserStorage();
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
var modelStorage = createStorage();
|
|
145
|
+
function modelFromContext() {
|
|
146
|
+
return modelStorage.get();
|
|
147
|
+
}
|
|
148
|
+
function withModel(modelOrId, paramsOrFn, fn) {
|
|
149
|
+
let resolvedModel;
|
|
150
|
+
let resolvedFn;
|
|
151
|
+
if (typeof modelOrId === "string") {
|
|
152
|
+
if (typeof paramsOrFn === "function") {
|
|
153
|
+
resolvedModel = new Model(modelOrId);
|
|
154
|
+
resolvedFn = paramsOrFn;
|
|
155
|
+
} else {
|
|
156
|
+
resolvedModel = new Model(modelOrId, paramsOrFn);
|
|
157
|
+
resolvedFn = fn;
|
|
158
|
+
}
|
|
159
|
+
} else {
|
|
160
|
+
resolvedModel = modelOrId;
|
|
161
|
+
resolvedFn = paramsOrFn;
|
|
162
|
+
}
|
|
163
|
+
return modelStorage.run(resolvedModel, resolvedFn);
|
|
164
|
+
}
|
|
165
|
+
function useModel(model2, params) {
|
|
166
|
+
const contextModel = modelFromContext();
|
|
167
|
+
if (contextModel !== void 0) {
|
|
168
|
+
return contextModel;
|
|
169
|
+
}
|
|
170
|
+
if (typeof model2 === "string") {
|
|
171
|
+
return new Model(model2, params);
|
|
172
|
+
}
|
|
173
|
+
return model2;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// src/llm/prompts/prompt.ts
|
|
177
|
+
function definePrompt({
|
|
178
|
+
tools,
|
|
179
|
+
format,
|
|
180
|
+
template
|
|
181
|
+
}) {
|
|
182
|
+
const resolvedFormat = resolveFormat(format, "tool");
|
|
183
|
+
const messagesImpl = (...args) => {
|
|
184
|
+
const firstArg = args[0];
|
|
185
|
+
if (isContext(firstArg)) {
|
|
186
|
+
const ctx = firstArg;
|
|
187
|
+
const vars = args[1];
|
|
188
|
+
const templateArgs = { ctx, ...vars };
|
|
189
|
+
const content = template.length === 0 ? template() : template(
|
|
190
|
+
templateArgs
|
|
191
|
+
);
|
|
192
|
+
return promoteToMessages(content);
|
|
193
|
+
} else {
|
|
194
|
+
const vars = firstArg;
|
|
195
|
+
const content = template.length === 0 ? template() : template(
|
|
196
|
+
vars
|
|
197
|
+
);
|
|
198
|
+
return promoteToMessages(content);
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
const callImpl = async (...args) => {
|
|
202
|
+
const modelArg = args[0];
|
|
203
|
+
const secondArg = args[1];
|
|
204
|
+
if (isContext(secondArg)) {
|
|
205
|
+
const ctx = secondArg;
|
|
206
|
+
const vars = args[2];
|
|
207
|
+
const msgs = messagesImpl(ctx, vars);
|
|
208
|
+
return useModel(modelArg).contextCall(ctx, msgs, {
|
|
209
|
+
tools,
|
|
210
|
+
format: resolvedFormat
|
|
211
|
+
});
|
|
212
|
+
} else {
|
|
213
|
+
const vars = secondArg;
|
|
214
|
+
const msgs = messagesImpl(vars);
|
|
215
|
+
return useModel(modelArg).call(msgs, {
|
|
216
|
+
tools,
|
|
217
|
+
format: resolvedFormat
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
const callable = async (...args) => {
|
|
222
|
+
return callImpl(...args);
|
|
223
|
+
};
|
|
224
|
+
const streamImpl = async (...args) => {
|
|
225
|
+
const modelArg = args[0];
|
|
226
|
+
const secondArg = args[1];
|
|
227
|
+
if (isContext(secondArg)) {
|
|
228
|
+
const ctx = secondArg;
|
|
229
|
+
const vars = args[2];
|
|
230
|
+
const msgs = messagesImpl(ctx, vars);
|
|
231
|
+
return useModel(modelArg).contextStream(ctx, msgs, {
|
|
232
|
+
tools,
|
|
233
|
+
format: resolvedFormat
|
|
234
|
+
});
|
|
235
|
+
} else {
|
|
236
|
+
const vars = secondArg;
|
|
237
|
+
const msgs = messagesImpl(vars);
|
|
238
|
+
return useModel(modelArg).stream(msgs, {
|
|
239
|
+
tools,
|
|
240
|
+
format: resolvedFormat
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
};
|
|
244
|
+
return Object.assign(callable, {
|
|
245
|
+
call: callImpl,
|
|
246
|
+
stream: streamImpl,
|
|
247
|
+
messages: messagesImpl,
|
|
248
|
+
tools,
|
|
249
|
+
format,
|
|
250
|
+
template
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// src/llm/calls/call.ts
|
|
255
|
+
function createCall({
|
|
256
|
+
model: model2,
|
|
257
|
+
tools,
|
|
258
|
+
format,
|
|
259
|
+
template,
|
|
260
|
+
...params
|
|
261
|
+
}) {
|
|
262
|
+
if (typeof model2 !== "string" && Object.keys(params).length > 0) {
|
|
263
|
+
throw new Error(
|
|
264
|
+
"Cannot pass params when model is a Model instance. Use new Model(id, params) instead."
|
|
265
|
+
);
|
|
266
|
+
}
|
|
267
|
+
const defaultModel = typeof model2 === "string" ? new Model(model2, params) : model2;
|
|
268
|
+
const prompt = definePrompt({ tools, format, template });
|
|
269
|
+
const callImpl = async (...args) => {
|
|
270
|
+
const firstArg = args[0];
|
|
271
|
+
if (isContext(firstArg)) {
|
|
272
|
+
const ctx = firstArg;
|
|
273
|
+
const vars = args[1];
|
|
274
|
+
const contextPrompt = prompt;
|
|
275
|
+
return contextPrompt.call(useModel(defaultModel), ctx, vars);
|
|
276
|
+
} else {
|
|
277
|
+
const vars = firstArg;
|
|
278
|
+
const regularPrompt = prompt;
|
|
279
|
+
return regularPrompt.call(useModel(defaultModel), vars);
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
const callable = async (...args) => {
|
|
283
|
+
return callImpl(...args);
|
|
284
|
+
};
|
|
285
|
+
const streamImpl = async (...args) => {
|
|
286
|
+
const firstArg = args[0];
|
|
287
|
+
if (isContext(firstArg)) {
|
|
288
|
+
const ctx = firstArg;
|
|
289
|
+
const vars = args[1];
|
|
290
|
+
const contextPrompt = prompt;
|
|
291
|
+
return contextPrompt.stream(useModel(defaultModel), ctx, vars);
|
|
292
|
+
} else {
|
|
293
|
+
const vars = firstArg;
|
|
294
|
+
const regularPrompt = prompt;
|
|
295
|
+
return regularPrompt.stream(useModel(defaultModel), vars);
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
const definedCall = Object.assign(callable, {
|
|
299
|
+
defaultModel,
|
|
300
|
+
call: callImpl,
|
|
301
|
+
stream: streamImpl,
|
|
302
|
+
tools,
|
|
303
|
+
format,
|
|
304
|
+
prompt,
|
|
305
|
+
template
|
|
306
|
+
});
|
|
307
|
+
Object.defineProperty(definedCall, "model", {
|
|
308
|
+
get: () => useModel(defaultModel),
|
|
309
|
+
enumerable: true
|
|
310
|
+
});
|
|
311
|
+
return definedCall;
|
|
312
|
+
}
|
|
313
|
+
function defineCall(args) {
|
|
314
|
+
if (args === void 0) {
|
|
315
|
+
return ((builderArgs) => {
|
|
316
|
+
return createCall(builderArgs);
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
return createCall(args);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
export { llm_exports as llm };
|
|
323
|
+
//# sourceMappingURL=index.js.map
|
|
324
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/llm/index.ts","../src/llm/providers/provider-id.ts","../src/llm/context/context.ts","../src/llm/models/model-context.ts","../src/llm/prompts/prompt.ts","../src/llm/calls/call.ts"],"names":["model"],"mappings":";;;;AAAA,IAAA,WAAA,GAAA;AAAA,QAAA,CAAA,WAAA,EAAA;AAAA,EAAA,QAAA,EAAA,MAAA,QAAA;AAAA,EAAA,KAAA,EAAA,MAAA,KAAA;AAAA,EAAA,mBAAA,EAAA,MAAA,mBAAA;AAAA,EAAA,eAAA,EAAA,MAAA,eAAA;AAAA,EAAA,YAAA,EAAA,MAAA,YAAA;AAAA,EAAA,cAAA,EAAA,MAAA,cAAA;AAAA,EAAA,iBAAA,EAAA,MAAA,iBAAA;AAAA,EAAA,eAAA,EAAA,MAAA,eAAA;AAAA,EAAA,eAAA,EAAA,MAAA,eAAA;AAAA,EAAA,qBAAA,EAAA,MAAA,qBAAA;AAAA,EAAA,cAAA,EAAA,MAAA,cAAA;AAAA,EAAA,QAAA,EAAA,MAAA,QAAA;AAAA,EAAA,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,CAAA;AAAA,IAC/B,CAAA;AAAA,EACF;AAEA,EAAA,OAAO,WAAW,IAAI,CAAA;AACxB","file":"index.js","sourcesContent":["export type { Jsonable } from \"@/llm/types\";\n\nexport type {\n AnthropicModelId,\n GoogleModelId,\n OpenAIModelId,\n ApiMode,\n KnownProviderId,\n ModelId,\n Provider,\n ProviderId,\n} from \"@/llm/providers\";\nexport { KNOWN_PROVIDER_IDS } from \"@/llm/providers\";\n\nexport {\n type Context,\n createContext,\n isContext,\n CONTEXT_MARKER,\n} from \"@/llm/context\";\n\nexport type {\n AssistantContentPart,\n AssistantContentChunk,\n ContentPart,\n UserContentPart,\n} from \"@/llm/content\";\n\nexport type { Text, Thought, ToolCall } from \"@/llm/content\";\n\n// Content chunk types (from content module, like Python)\nexport type {\n TextStartChunk,\n TextChunk,\n TextEndChunk,\n ThoughtStartChunk,\n ThoughtChunk,\n ThoughtEndChunk,\n ToolCallStartChunk,\n ToolCallChunk,\n ToolCallEndChunk,\n} from \"@/llm/content\";\n\n// Content chunk factory functions\nexport {\n textStart,\n textChunk,\n textEnd,\n thoughtStart,\n thoughtChunk,\n thoughtEnd,\n toolCallStart,\n toolCallChunk,\n toolCallEnd,\n} from \"@/llm/content\";\n\nexport {\n Audio,\n type AudioMimeType,\n type Base64AudioSource,\n} from \"@/llm/content\";\n\nexport {\n Document,\n type Base64DocumentSource,\n type DocumentBase64MimeType,\n type DocumentTextMimeType,\n type TextDocumentSource,\n type URLDocumentSource,\n} from \"@/llm/content\";\n\nexport {\n Image,\n type Base64ImageSource,\n type ImageMimeType,\n type URLImageSource,\n} from \"@/llm/content\";\n\nexport { ToolOutput } from \"@/llm/content\";\n\nexport {\n defineTool,\n defineContextTool,\n isZodLike,\n isContextTool,\n Toolkit,\n ContextToolkit,\n createToolkit,\n createContextToolkit,\n TOOL_TYPE,\n CONTEXT_TOOL_TYPE,\n ProviderTool,\n isProviderTool,\n WebSearchTool,\n isWebSearchTool,\n} from \"@/llm/tools\";\n\nexport type {\n JsonSchemaProperty,\n ToolParameterSchema,\n ToolSchema,\n ZodLike,\n InferZod,\n ToolArgs,\n ContextToolArgs,\n ZodToolArgs,\n ZodContextToolArgs,\n BaseTool,\n BaseContextTool,\n Tool,\n ContextTool,\n AnyTool,\n AnyContextTool,\n Tools,\n ContextTools,\n ToolFn,\n ContextToolFn,\n AnyToolFn,\n} from \"@/llm/tools\";\n\nexport type {\n AssistantContent,\n AssistantMessage,\n Message,\n SystemContent,\n SystemMessage,\n UserContent,\n UserMessage,\n} from \"@/llm/messages\";\n\nimport * as messages from \"@/llm/messages\";\nexport { messages };\n\nexport {\n MirascopeError,\n ProviderError,\n APIError,\n AuthenticationError,\n PermissionError,\n BadRequestError,\n NotFoundError,\n RateLimitError,\n ServerError,\n ConnectionError,\n TimeoutError,\n ResponseValidationError,\n ToolError,\n ToolExecutionError,\n ToolNotFoundError,\n ParseError,\n FeatureNotSupportedError,\n NoRegisteredProviderError,\n MissingAPIKeyError,\n} from \"@/llm/exceptions\";\n\nexport type { Params, ThinkingConfig, ThinkingLevel } from \"@/llm/models\";\n\nexport {\n defineFormat,\n defineOutputParser,\n isFormat,\n isOutputParser,\n resolveFormat,\n FORMAT_TOOL_NAME,\n TOOL_MODE_INSTRUCTIONS,\n JSON_MODE_INSTRUCTIONS,\n} from \"@/llm/formatting\";\n\nexport type {\n Format,\n FormatSpec,\n FormattingMode,\n OutputParser,\n OutputParserArgs,\n DeepPartial,\n} from \"@/llm/formatting\";\nexport {\n Model,\n model,\n modelFromContext,\n useModel,\n withModel,\n} from \"@/llm/models\";\n\nexport {\n definePrompt,\n type MessageTemplate,\n type Prompt,\n type PromptArgs,\n type TemplateFunc,\n // Context-aware types (unified API)\n type ContextMessageTemplate,\n type ContextPrompt,\n type ContextPromptArgs,\n type ContextTemplateFunc,\n // Type utilities\n type ExtractDeps,\n type ExtractVars,\n type UnifiedPrompt,\n} from \"@/llm/prompts\";\n\nexport {\n defineCall,\n type Call,\n type CallArgs,\n // Context-aware types (unified API)\n type ContextCall,\n type ContextCallArgs,\n // Type utilities\n type UnifiedCall,\n} from \"@/llm/calls\";\n\nexport {\n getProviderForModel,\n registerProvider,\n resetProviderRegistry,\n} from \"@/llm/providers\";\n\nexport {\n FinishReason,\n RootResponse,\n BaseResponse,\n Response,\n ContextResponse,\n StreamResponse,\n ContextStreamResponse,\n createUsage,\n totalTokens,\n} from \"@/llm/responses\";\nexport type { AnyResponse } from \"@/llm/responses\";\nexport type {\n FinishReasonType,\n Usage,\n BaseResponseInit,\n ResponseInit,\n ContextResponseInit,\n StreamResponseInit,\n ContextStreamResponseInit,\n // Metadata streaming chunk types (content chunks exported from content above)\n FinishReasonChunk,\n UsageDeltaChunk,\n RawStreamEventChunk,\n RawMessageChunk,\n StreamResponseChunk,\n AsyncChunkIterator,\n} from \"@/llm/responses\";\n","/**\n * Identifiers for all registered providers.\n */\n\n/**\n * Array of known provider IDs for runtime checks.\n */\nexport const KNOWN_PROVIDER_IDS = [\n \"anthropic\",\n \"google\",\n \"mirascope\",\n \"ollama\",\n \"openai\",\n \"together\",\n] as const;\n\n/**\n * Known provider identifiers.\n */\nexport type KnownProviderId = (typeof KNOWN_PROVIDER_IDS)[number];\n\n/**\n * Provider identifier.\n *\n * Can be a known provider or any custom string for extensibility.\n */\nexport type ProviderId = KnownProviderId | (string & {});\n","/**\n * Context for LLM calls with dependency injection.\n *\n * Context allows you to pass dependencies (like database connections, user info,\n * configuration, etc.) through to your prompts and tools in a type-safe way.\n */\n\n/**\n * Symbol marker used to identify Context objects at runtime.\n * This enables reliable detection of Context instances in unified call/prompt functions.\n */\nexport const CONTEXT_MARKER = Symbol(\"mirascope.Context\");\n\n/**\n * Context for LLM calls with dependency injection.\n *\n * @template DepsT - The type of dependencies contained in the context.\n *\n * @example\n * ```typescript\n * interface MyDeps {\n * userId: string;\n * db: Database;\n * }\n *\n * const ctx = createContext<MyDeps>({ userId: '123', db: myDb });\n * const response = await myPrompt(model, ctx, { greeting: 'Hello' });\n * ```\n */\nexport interface Context<DepsT> {\n /**\n * Marker property for runtime Context detection.\n * @internal\n */\n readonly [CONTEXT_MARKER]: true;\n\n /**\n * The dependencies available in this context.\n */\n readonly deps: DepsT;\n}\n\n/**\n * Type guard to check if a value is a Context object.\n *\n * @param value - The value to check.\n * @returns True if the value is a Context, false otherwise.\n *\n * @example\n * ```typescript\n * const maybeCtx = getArgument();\n * if (isContext(maybeCtx)) {\n * console.log(maybeCtx.deps); // TypeScript knows this is a Context\n * }\n * ```\n */\nexport function isContext(value: unknown): value is Context<unknown> {\n return value !== null && typeof value === \"object\" && CONTEXT_MARKER in value;\n}\n\n/**\n * Create a context with the given dependencies.\n *\n * @template DepsT - The type of dependencies.\n * @param deps - The dependencies to include in the context.\n * @returns A Context containing the provided dependencies.\n *\n * @example\n * ```typescript\n * interface MyDeps {\n * userId: string;\n * db: Database;\n * }\n *\n * const ctx = createContext<MyDeps>({ userId: '123', db: myDb });\n * ```\n */\nexport function createContext<DepsT>(deps: DepsT): Context<DepsT> {\n return { [CONTEXT_MARKER]: true as const, deps };\n}\n","/**\n * Model context management for runtime model switching.\n *\n * This module provides a way to set a model context that overrides\n * the default model in `defineCall` and `definePrompt`, similar to\n * Python's `with llm.model(...):` context manager.\n *\n * ## Cross-Platform Implementation\n *\n * - **Node.js**: Uses native `AsyncLocalStorage` from `async_hooks` for proper\n * async context propagation. This handles concurrent async operations correctly.\n *\n * - **Browser**: Uses a stack-based fallback. This works correctly for:\n * - Synchronous code\n * - Sequential async/await chains\n * - Nested `withModel` calls (as long as they are sequential)\n *\n * ## Browser Limitations\n *\n * The browser fallback has a known limitation with **concurrent** async operations:\n *\n * ```typescript\n * // WARNING: In browsers, this may have unexpected behavior:\n * await Promise.all([\n * llm.withModel(modelA, async () => { await call(); }), // May see modelB!\n * llm.withModel(modelB, async () => { await call(); }), // May see modelA!\n * ]);\n * ```\n *\n * This is because the browser lacks a native async context mechanism. The stack\n * can become interleaved when multiple async operations run concurrently.\n *\n * ## Future: TC39 AsyncContext Proposal\n *\n * The TC39 \"Async Context\" proposal (https://github.com/tc39/proposal-async-context)\n * aims to bring `AsyncLocalStorage`-like functionality to all JavaScript environments.\n * Once this proposal is standardized and widely supported, we can update the browser\n * implementation to use native async context, eliminating the concurrent operation\n * limitation.\n *\n * @see https://github.com/tc39/proposal-async-context\n *\n * @example\n * ```typescript\n * const call = llm.defineCall({\n * model: llm.model(\"openai/gpt-4o\"),\n * template: () => \"Hello\"\n * });\n *\n * // Without context - uses default model\n * await call();\n *\n * // With context - overrides default\n * await llm.withModel(llm.model(\"anthropic/claude-sonnet-4-0\"), async () => {\n * await call(); // Uses Claude\n * });\n * ```\n */\n\nimport type { Params } from \"@/llm/models/params\";\nimport type { ModelId } from \"@/llm/providers/model-id\";\n\nimport { Model } from \"@/llm/models/model\";\n\n/**\n * Cross-platform context storage interface.\n * Abstracts over Node.js AsyncLocalStorage and browser fallback.\n * @internal Exported for testing purposes only\n */\nexport interface ContextStorage<T> {\n get(): T | undefined;\n run<R>(value: T, fn: () => R): R;\n}\n\n/**\n * Node.js implementation using AsyncLocalStorage.\n * Provides proper async context propagation across async/await boundaries.\n */\nfunction createNodeStorage<T>(): ContextStorage<T> {\n // Dynamic require to avoid issues in browser bundlers\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { AsyncLocalStorage } = require(\"node:async_hooks\") as {\n AsyncLocalStorage: new <T>() => {\n getStore(): T | undefined;\n run<R>(store: T, callback: () => R): R;\n };\n };\n const storage = new AsyncLocalStorage<T>();\n return {\n get: () => storage.getStore(),\n run: <R>(value: T, fn: () => R): R => storage.run(value, fn),\n };\n}\n\n/**\n * Browser fallback using a stack.\n *\n * **Limitations**: This implementation works correctly for sequential async operations\n * but does NOT properly isolate concurrent async operations. When multiple `withModel`\n * calls run in parallel via `Promise.all`, their contexts may become interleaved.\n *\n * This is a fundamental limitation of any JavaScript-based solution without native\n * async context support. The TC39 AsyncContext proposal will solve this when available.\n *\n * @see https://github.com/tc39/proposal-async-context\n * @internal Exported for testing purposes only\n */\nexport function createBrowserStorage<T>(): ContextStorage<T> {\n const stack: T[] = [];\n return {\n get: () => stack[stack.length - 1],\n run: <R>(value: T, fn: () => R): R => {\n stack.push(value);\n try {\n const result = fn();\n // Handle promises to ensure cleanup after async completion\n if (result instanceof Promise) {\n return result.finally(() => {\n stack.pop();\n }) as R;\n }\n stack.pop();\n return result;\n } catch (e) {\n stack.pop();\n throw e;\n }\n },\n };\n}\n\n/**\n * Auto-detect environment and create appropriate storage.\n * @internal Exported for testing purposes only\n */\nexport function createStorage<T>(): ContextStorage<T> {\n try {\n return createNodeStorage<T>();\n /* v8 ignore start - browser fallback only hit when AsyncLocalStorage unavailable */\n } catch {\n // This branch is only hit in browser environments where AsyncLocalStorage\n // is unavailable. Since tests run in Node.js, this is tested indirectly\n // through createBrowserStorage tests.\n return createBrowserStorage<T>();\n }\n /* v8 ignore stop */\n}\n\n// Initialize the model storage\nconst modelStorage = createStorage<Model>();\n\n/**\n * Get the model currently set via context, if any.\n *\n * @returns The current context model, or undefined if none is set.\n *\n * @example\n * ```typescript\n * await llm.withModel(llm.model(\"anthropic/claude-sonnet-4-0\"), async () => {\n * const model = llm.modelFromContext();\n * console.log(model?.modelId); // \"anthropic/claude-sonnet-4-0\"\n * });\n *\n * const outsideModel = llm.modelFromContext(); // undefined\n * ```\n */\nexport function modelFromContext(): Model | undefined {\n return modelStorage.get();\n}\n\n/**\n * Execute a function with a model set in context.\n *\n * All calls to `defineCall` and `definePrompt` within the callback\n * will use the context model instead of their default model.\n *\n * @param model - The model to set in context (Model instance or model ID string).\n * @param paramsOrFn - Either params object (if using string model ID) or the function to execute.\n * @param fn - The function to execute (if params were provided).\n * @returns The return value of the function.\n *\n * @example With Model instance\n * ```typescript\n * const response = await llm.withModel(llm.model(\"openai/gpt-4o\"), async () => {\n * return await call();\n * });\n * ```\n *\n * @example With model ID string\n * ```typescript\n * const response = await llm.withModel(\"openai/gpt-4o\", async () => {\n * return await call();\n * });\n * ```\n *\n * @example With model ID and params\n * ```typescript\n * const response = await llm.withModel(\"anthropic/claude-sonnet-4-0\", { temperature: 0.9 }, async () => {\n * return await call();\n * });\n * ```\n *\n * @example Nested contexts\n * ```typescript\n * await llm.withModel(\"anthropic/claude-sonnet-4-0\", async () => {\n * const model1 = llm.modelFromContext(); // Claude\n *\n * await llm.withModel(\"openai/gpt-4o\", async () => {\n * const model2 = llm.modelFromContext(); // GPT-4o\n * });\n *\n * const model3 = llm.modelFromContext(); // Claude (restored)\n * });\n * ```\n */\nexport function withModel<T>(model: Model, fn: () => T): T;\nexport function withModel<T>(modelId: ModelId, fn: () => T): T;\nexport function withModel<T>(modelId: ModelId, params: Params, fn: () => T): T;\nexport function withModel<T>(\n modelOrId: Model | ModelId,\n paramsOrFn: Params | (() => T),\n fn?: () => T,\n): T {\n let resolvedModel: Model;\n let resolvedFn: () => T;\n\n if (typeof modelOrId === \"string\") {\n // String model ID\n if (typeof paramsOrFn === \"function\") {\n // withModel(modelId, fn)\n resolvedModel = new Model(modelOrId);\n resolvedFn = paramsOrFn;\n } else {\n // withModel(modelId, params, fn)\n resolvedModel = new Model(modelOrId, paramsOrFn);\n resolvedFn = fn!;\n }\n } else {\n // Model instance\n resolvedModel = modelOrId;\n resolvedFn = paramsOrFn as () => T;\n }\n\n return modelStorage.run(resolvedModel, resolvedFn);\n}\n\n/**\n * Get the model from context if available, otherwise use the provided model.\n *\n * This function implements the fallback pattern:\n * 1. If a model is set in context, return it (context takes precedence)\n * 2. Otherwise, if a Model instance is provided, return it\n * 3. Otherwise, if a string model ID is provided, create a new Model\n *\n * @param modelOrId - A Model instance or model ID string.\n * @param params - Optional parameters when creating a new Model from string ID.\n * @returns The resolved Model instance.\n *\n * @example\n * ```typescript\n * // Outside context - returns the provided model\n * const model1 = llm.useModel(\"openai/gpt-4o\"); // Creates new Model\n *\n * // Inside context - returns context model\n * await llm.withModel(llm.model(\"anthropic/claude-sonnet-4-0\"), async () => {\n * const model2 = llm.useModel(\"openai/gpt-4o\"); // Returns Claude model\n * });\n * ```\n */\nexport function useModel(model: Model | ModelId, params?: Params): Model {\n const contextModel = modelFromContext();\n if (contextModel !== undefined) {\n return contextModel;\n }\n if (typeof model === \"string\") {\n return new Model(model, params);\n }\n return model;\n}\n","/**\n * Prompt definition and creation utilities.\n *\n * This module provides a unified `definePrompt` function that automatically\n * detects whether a prompt is context-aware based on the template type parameter.\n * If T includes `ctx: Context<DepsT>`, a ContextPrompt is returned; otherwise\n * a regular Prompt is returned.\n */\n\nimport type { Message, UserContent } from \"@/llm/messages\";\nimport type { ModelId } from \"@/llm/providers/model-id\";\nimport type { Response } from \"@/llm/responses\";\nimport type { StreamResponse } from \"@/llm/responses/stream-response\";\nimport type { ContextTools, Tools, ZodLike } from \"@/llm/tools\";\nimport type { NoVars } from \"@/llm/types\";\n\nimport { type Context, isContext } from \"@/llm/context\";\nimport {\n resolveFormat,\n type AnyFormatInput,\n type ExtractFormatType,\n type FormatInput,\n type Format,\n type FormatSpec,\n type OutputParser,\n} from \"@/llm/formatting\";\nimport { promoteToMessages } from \"@/llm/messages\";\nimport { Model, useModel } from \"@/llm/models\";\nimport { ContextResponse } from \"@/llm/responses/context-response\";\nimport { ContextStreamResponse } from \"@/llm/responses/context-stream-response\";\n\n// ============================================================================\n// Type Utilities for Context Detection\n// ============================================================================\n\n/**\n * Extract DepsT from T if T has a `ctx: Context<DepsT>` property.\n * Returns `never` if T doesn't have a context property.\n */\nexport type ExtractDeps<T> = T extends { ctx: Context<infer D> } ? D : never;\n\n/**\n * Extract the variables type from T by removing the `ctx` property.\n */\nexport type ExtractVars<T> = Omit<T, \"ctx\">;\n\n// ============================================================================\n// Template Types\n// ============================================================================\n\n/**\n * A template function that generates message content from variables.\n *\n * @template T - The type of variables the template accepts.\n */\nexport type MessageTemplate<T> = (vars: T) => UserContent | readonly Message[];\n\n/**\n * Template function type - either takes no args or takes vars of type T.\n */\nexport type TemplateFunc<T> =\n | (() => UserContent | readonly Message[])\n | ((vars: T) => UserContent | readonly Message[]);\n\n/**\n * The combined context and variables object passed to context template functions.\n *\n * @template T - The type of variables the template accepts.\n * @template DepsT - The type of dependencies in the context.\n */\nexport type ContextMessageTemplate<T, DepsT> = { ctx: Context<DepsT> } & T;\n\n/**\n * Context template function type - takes an object with ctx and vars.\n *\n * @template T - The type of variables the template accepts.\n * @template DepsT - The type of dependencies in the context.\n */\nexport type ContextTemplateFunc<T, DepsT> = (\n args: ContextMessageTemplate<T, DepsT>,\n) => UserContent | readonly Message[];\n\n// ============================================================================\n// Prompt Args Types\n// ============================================================================\n\n/**\n * Arguments for defining a prompt.\n *\n * @template T - The type of variables the template accepts. Defaults to NoVars.\n * @template F - The format input type. The output type F is derived via ExtractFormatType<F>.\n */\nexport interface PromptArgs<T = NoVars, F extends AnyFormatInput = undefined> {\n /** Optional tools to make available to the model. */\n tools?: Tools;\n /**\n * Optional format specification for structured output.\n * Can be a Zod schema, Format, FormatSpec, or OutputParser.\n * The output type is automatically inferred from this format.\n */\n format?: F;\n /** A function that generates message content (optionally from variables). */\n template: TemplateFunc<T>;\n}\n\n/**\n * Arguments for defining a context-aware prompt.\n * Used when T includes `ctx: Context<DepsT>`.\n *\n * @template T - The full template parameter type including ctx.\n * @template F - The format input type.\n */\nexport interface ContextPromptArgs<\n T = NoVars,\n F extends AnyFormatInput = undefined,\n> {\n /** Optional tools to make available to the model. */\n tools?: ExtractDeps<T> extends never ? Tools : ContextTools<ExtractDeps<T>>;\n /**\n * Optional format specification for structured output.\n * Can be a Zod schema, Format, FormatSpec, or OutputParser.\n */\n format?: F;\n /** A function that generates message content from context (and optionally variables). */\n template: TemplateFunc<T>;\n}\n\n// ============================================================================\n// Prompt Interface (Non-Context)\n// ============================================================================\n\n/**\n * A prompt that can be called with a model to generate a response.\n *\n * Created by `definePrompt()`. The prompt is callable and also has a\n * `messages()` method for getting the raw messages without calling the LLM.\n *\n * @template T - The type of variables the prompt accepts. Defaults to empty object.\n * @template F - The format input type. The output type F is derived via ExtractFormatType<F>.\n *\n * @example With variables\n * ```typescript\n * const recommendBook = definePrompt<{ genre: string }>({\n * template: ({ genre }) => `Recommend a ${genre} book`,\n * });\n *\n * const response = await recommendBook(model, { genre: 'fantasy' });\n * const messages = recommendBook.messages({ genre: 'fantasy' });\n * ```\n *\n * @example Without variables\n * ```typescript\n * const sayHello = definePrompt({\n * template: () => 'Hello!',\n * });\n * const response = await sayHello(model);\n * ```\n */\nexport interface Prompt<T = NoVars, F extends AnyFormatInput = undefined> {\n /**\n * Call the prompt with a model and variables to generate a response.\n *\n * @param model - The model to use, either a Model instance or model ID string.\n * @param vars - The variables to pass to the template.\n * @returns A promise that resolves to the LLM response.\n */\n (\n model: Model | ModelId,\n ...args: keyof T extends never ? [] : [vars: T]\n ): Promise<Response<ExtractFormatType<F>>>;\n\n /**\n * Call the prompt with a model and variables to generate a response.\n * This is the method form of the callable interface.\n *\n * @param model - The model to use, either a Model instance or model ID string.\n * @param vars - The variables to pass to the template.\n * @returns A promise that resolves to the LLM response.\n */\n call(\n model: Model | ModelId,\n ...args: keyof T extends never ? [] : [vars: T]\n ): Promise<Response<ExtractFormatType<F>>>;\n\n /**\n * Stream the prompt with a model and variables to generate a streaming response.\n *\n * @param model - The model to use, either a Model instance or model ID string.\n * @param vars - The variables to pass to the template.\n * @returns A promise that resolves to the streaming LLM response.\n *\n * @example\n * ```typescript\n * const response = await prompt.stream(model, { genre: 'fantasy' });\n * for await (const text of response.textStream()) {\n * process.stdout.write(text);\n * }\n * ```\n */\n stream(\n model: Model | ModelId,\n ...args: keyof T extends never ? [] : [vars: T]\n ): Promise<StreamResponse<ExtractFormatType<F>>>;\n\n /**\n * Get the messages for this prompt without calling the LLM.\n *\n * @param vars - The variables to pass to the template.\n * @returns The messages that would be sent to the LLM.\n */\n messages(...args: keyof T extends never ? [] : [vars: T]): readonly Message[];\n\n /**\n * The tools available to this prompt.\n */\n readonly tools: Tools | undefined;\n\n /**\n * The format specification for structured output, if any.\n */\n readonly format: FormatInput<ExtractFormatType<F>>;\n\n /**\n * The underlying template function.\n */\n readonly template: TemplateFunc<T>;\n}\n\n// ============================================================================\n// Context Prompt Interface\n// ============================================================================\n\n/**\n * A context-aware prompt that can be called with a model and context to generate a response.\n *\n * Created by `definePrompt()` when the template type includes `ctx: Context<DepsT>`.\n * The prompt is callable and also has a `messages()` method for getting the raw messages.\n *\n * @template T - The type of variables the prompt accepts. Defaults to empty object.\n * @template DepsT - The type of dependencies in the context.\n * @template F - The format input type. The output type is derived via ExtractFormatType<F>.\n *\n * @example With variables\n * ```typescript\n * interface MyDeps { userId: string; }\n *\n * const greetUser = definePrompt<{ ctx: Context<MyDeps>; greeting: string }>({\n * template: ({ ctx, greeting }) => `${greeting}, user ${ctx.deps.userId}!`,\n * });\n *\n * const ctx = createContext<MyDeps>({ userId: '123' });\n * const response = await greetUser(model, ctx, { greeting: 'Hello' });\n * const messages = greetUser.messages(ctx, { greeting: 'Hello' });\n * ```\n *\n * @example Without variables\n * ```typescript\n * interface MyDeps { userId: string; }\n *\n * const sayHello = definePrompt<{ ctx: Context<MyDeps> }>({\n * template: ({ ctx }) => `Hello, user ${ctx.deps.userId}!`,\n * });\n *\n * const response = await sayHello(model, ctx);\n * ```\n */\nexport interface ContextPrompt<\n T = NoVars,\n DepsT = unknown,\n F extends AnyFormatInput = undefined,\n> {\n /**\n * Call the prompt with a model, context, and variables to generate a response.\n *\n * @param model - The model to use, either a Model instance or model ID string.\n * @param ctx - The context containing dependencies.\n * @param vars - The variables to pass to the template.\n * @returns A promise that resolves to the LLM response.\n */\n (\n model: Model | ModelId,\n ctx: Context<DepsT>,\n ...args: keyof T extends never ? [] : [vars: T]\n ): Promise<ContextResponse<DepsT, ExtractFormatType<F>>>;\n\n /**\n * Call the prompt with a model, context, and variables to generate a response.\n * This is the method form of the callable interface.\n *\n * @param model - The model to use, either a Model instance or model ID string.\n * @param ctx - The context containing dependencies.\n * @param vars - The variables to pass to the template.\n * @returns A promise that resolves to the LLM response.\n */\n call(\n model: Model | ModelId,\n ctx: Context<DepsT>,\n ...args: keyof T extends never ? [] : [vars: T]\n ): Promise<ContextResponse<DepsT, ExtractFormatType<F>>>;\n\n /**\n * Stream the prompt with a model, context, and variables to generate a streaming response.\n *\n * @param model - The model to use, either a Model instance or model ID string.\n * @param ctx - The context containing dependencies.\n * @param vars - The variables to pass to the template.\n * @returns A promise that resolves to the streaming LLM response.\n *\n * @example\n * ```typescript\n * const response = await prompt.stream(model, ctx, { greeting: 'Hello' });\n * for await (const text of response.textStream()) {\n * process.stdout.write(text);\n * }\n * ```\n */\n stream(\n model: Model | ModelId,\n ctx: Context<DepsT>,\n ...args: keyof T extends never ? [] : [vars: T]\n ): Promise<ContextStreamResponse<DepsT, ExtractFormatType<F>>>;\n\n /**\n * Get the messages for this prompt without calling the LLM.\n *\n * @param ctx - The context containing dependencies.\n * @param vars - The variables to pass to the template.\n * @returns The messages that would be sent to the LLM.\n */\n messages(\n ctx: Context<DepsT>,\n ...args: keyof T extends never ? [] : [vars: T]\n ): readonly Message[];\n\n /**\n * The tools available to this prompt.\n */\n readonly tools: ContextTools<DepsT> | undefined;\n\n /**\n * The format specification for structured output, if any.\n */\n readonly format:\n | Format<ExtractFormatType<F>>\n | FormatSpec<ExtractFormatType<F>>\n | ZodLike\n | OutputParser<ExtractFormatType<F>>\n | null\n | undefined;\n\n /**\n * The underlying template function.\n */\n readonly template: ContextTemplateFunc<T, DepsT>;\n}\n\n// ============================================================================\n// Unified Prompt Type\n// ============================================================================\n\n/**\n * Unified prompt type that returns either Prompt or ContextPrompt\n * based on whether T includes `ctx: Context<DepsT>`.\n */\nexport type UnifiedPrompt<T, F extends AnyFormatInput = undefined> =\n ExtractDeps<T> extends never\n ? Prompt<T, F>\n : ContextPrompt<ExtractVars<T>, ExtractDeps<T>, F>;\n\n// ============================================================================\n// definePrompt Function Overloads\n// ============================================================================\n\n/**\n * Define a prompt that automatically detects context from the template type.\n *\n * When T includes `ctx: Context<DepsT>`, returns a ContextPrompt.\n * Otherwise returns a regular Prompt.\n *\n * @template T - The type of the template parameter (including ctx if context-aware).\n * @template F - The format input type. The output type is derived via ExtractFormatType<F>.\n * @param args - The prompt arguments including the template.\n * @returns A callable prompt (context-aware if T includes ctx).\n *\n * @example Prompt without variables\n * ```typescript\n * const sayHello = definePrompt({\n * template: () => 'Hello!',\n * });\n * const response = await sayHello(model);\n * ```\n *\n * @example Regular prompt with variables\n * ```typescript\n * const recommendBook = definePrompt<{ genre: string }>({\n * template: ({ genre }) => `Recommend a ${genre} book`,\n * });\n * const response = await recommendBook(model, { genre: 'fantasy' });\n * ```\n *\n * @example Context-aware prompt\n * ```typescript\n * interface MyDeps { userId: string; }\n *\n * const greetUser = definePrompt<{ ctx: Context<MyDeps>; greeting: string }>({\n * template: ({ ctx, greeting }) => `${greeting}, user ${ctx.deps.userId}!`,\n * });\n *\n * const ctx = createContext<MyDeps>({ userId: '123' });\n * const response = await greetUser(model, ctx, { greeting: 'Hello' });\n * ```\n */\nexport function definePrompt<\n T extends Record<string, unknown> = NoVars,\n F extends AnyFormatInput = undefined,\n>(args: PromptArgs<T, F> | ContextPromptArgs<T, F>): UnifiedPrompt<T, F>;\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n// Implementation\nexport function definePrompt<T, F extends AnyFormatInput>({\n tools,\n format,\n template,\n}: PromptArgs<T, F> | ContextPromptArgs<T, F>): UnifiedPrompt<T, F> {\n // Resolve format at definition time (uses 'tool' as default mode)\n const resolvedFormat = resolveFormat(format, \"tool\");\n\n // Create messages function that handles both context and non-context cases\n const messagesImpl = (...args: unknown[]): readonly Message[] => {\n const firstArg = args[0];\n\n // Check if first argument is a Context\n if (isContext(firstArg)) {\n // Context case: first arg is ctx, second is vars\n const ctx = firstArg;\n const vars = args[1] as ExtractVars<T> | undefined;\n const templateArgs = { ctx, ...vars } as T;\n const content =\n template.length === 0\n ? (template as () => UserContent | readonly Message[])()\n : (template as (args: T) => UserContent | readonly Message[])(\n templateArgs,\n );\n return promoteToMessages(content);\n } else {\n // Non-context case: first arg is vars (or undefined)\n const vars = firstArg as T | undefined;\n const content =\n template.length === 0\n ? (template as () => UserContent | readonly Message[])()\n : (template as (vars: T) => UserContent | readonly Message[])(\n vars as T,\n );\n return promoteToMessages(content);\n }\n };\n\n // Create call function\n const callImpl = async (\n ...args: unknown[]\n ): Promise<\n | Response<ExtractFormatType<F>>\n | ContextResponse<unknown, ExtractFormatType<F>>\n > => {\n const modelArg = args[0] as Model | ModelId;\n const secondArg = args[1];\n\n if (isContext(secondArg)) {\n // Context case: call(model, ctx, vars?)\n const ctx = secondArg;\n const vars = args[2] as ExtractVars<T> | undefined;\n const msgs = messagesImpl(ctx, vars);\n return useModel(modelArg).contextCall(ctx, msgs, {\n tools: tools as ContextTools<unknown>,\n format: resolvedFormat,\n }) as Promise<ContextResponse<unknown, ExtractFormatType<F>>>;\n } else {\n // Non-context case: call(model, vars?)\n const vars = secondArg as T | undefined;\n const msgs = messagesImpl(vars);\n return useModel(modelArg).call(msgs, {\n tools: tools as Tools,\n format: resolvedFormat,\n }) as Promise<Response<ExtractFormatType<F>>>;\n }\n };\n\n // Create callable wrapper\n const callable = async (\n ...args: unknown[]\n ): Promise<\n | Response<ExtractFormatType<F>>\n | ContextResponse<unknown, ExtractFormatType<F>>\n > => {\n return callImpl(...args);\n };\n\n // Create stream function\n const streamImpl = async (\n ...args: unknown[]\n ): Promise<\n | StreamResponse<ExtractFormatType<F>>\n | ContextStreamResponse<unknown, ExtractFormatType<F>>\n > => {\n const modelArg = args[0] as Model | ModelId;\n const secondArg = args[1];\n\n if (isContext(secondArg)) {\n // Context case: stream(model, ctx, vars?)\n const ctx = secondArg;\n const vars = args[2] as ExtractVars<T> | undefined;\n const msgs = messagesImpl(ctx, vars);\n return useModel(modelArg).contextStream(ctx, msgs, {\n tools: tools as ContextTools<unknown>,\n format: resolvedFormat,\n }) as Promise<ContextStreamResponse<unknown, ExtractFormatType<F>>>;\n } else {\n // Non-context case: stream(model, vars?)\n const vars = secondArg as T | undefined;\n const msgs = messagesImpl(vars);\n return useModel(modelArg).stream(msgs, {\n tools: tools as Tools,\n format: resolvedFormat,\n }) as Promise<StreamResponse<ExtractFormatType<F>>>;\n }\n };\n\n return Object.assign(callable, {\n call: callImpl,\n stream: streamImpl,\n messages: messagesImpl,\n tools,\n format,\n template,\n }) as UnifiedPrompt<T, F>;\n}\n","/**\n * Call definition and creation utilities.\n *\n * A Call is a Prompt with a bundled Model - it can be invoked directly\n * without passing a model argument.\n *\n * This module provides a unified `defineCall` function that automatically\n * detects whether a call is context-aware based on the template type parameter.\n * If T includes `ctx: Context<DepsT>`, a ContextCall is returned; otherwise\n * a regular Call is returned.\n */\n\nimport type {\n AnyFormatInput,\n ExtractFormatType,\n FormatInput,\n Format,\n FormatSpec,\n OutputParser,\n} from \"@/llm/formatting\";\nimport type { Params } from \"@/llm/models/params\";\nimport type { ModelId } from \"@/llm/providers/model-id\";\nimport type { Response } from \"@/llm/responses\";\nimport type { ContextResponse } from \"@/llm/responses/context-response\";\nimport type { ContextStreamResponse } from \"@/llm/responses/context-stream-response\";\nimport type { StreamResponse } from \"@/llm/responses/stream-response\";\nimport type { ContextTools, Tools, ZodLike } from \"@/llm/tools\";\nimport type { NoVars } from \"@/llm/types\";\n\nimport { type Context, isContext } from \"@/llm/context\";\nimport { Model, useModel } from \"@/llm/models\";\nimport {\n definePrompt,\n type ContextPrompt,\n type ContextTemplateFunc,\n type ExtractDeps,\n type ExtractVars,\n type Prompt,\n type PromptArgs,\n type TemplateFunc,\n} from \"@/llm/prompts\";\n\n// ============================================================================\n// Call Args Types\n// ============================================================================\n\n/**\n * Arguments for defining a call.\n *\n * @template T - The type of variables the template accepts. Defaults to NoVars.\n * @template F - The format input type. The output type F is derived via ExtractFormatType<F>.\n */\nexport interface CallArgs<\n T = NoVars,\n F extends AnyFormatInput = undefined,\n> extends Params {\n /** The model to use, either a Model instance or model ID string. */\n model: Model | ModelId;\n /** Optional tools to make available to the model. */\n tools?: Tools;\n /**\n * Optional format specification for structured output.\n * Can be a Zod schema, Format, FormatSpec, or OutputParser.\n * The output type is automatically inferred from this format.\n */\n format?: F;\n /** A function that generates message content (optionally from variables). */\n template: TemplateFunc<T>;\n}\n\n/**\n * Arguments for defining a context-aware call.\n * Used when T includes `ctx: Context<DepsT>`.\n *\n * @template T - The full template parameter type including ctx.\n * @template F - The format input type.\n */\nexport interface ContextCallArgs<\n T = NoVars,\n F extends AnyFormatInput = undefined,\n> extends Params {\n /** The model to use, either a Model instance or model ID string. */\n model: Model | ModelId;\n /** Optional tools to make available to the model. */\n tools?: ExtractDeps<T> extends never ? Tools : ContextTools<ExtractDeps<T>>;\n /**\n * Optional format specification for structured output.\n * Can be a Zod schema, Format, FormatSpec, or OutputParser.\n */\n format?: F;\n /** A function that generates message content from context (and optionally variables). */\n template: TemplateFunc<T>;\n}\n\n// ============================================================================\n// Call Interface (Non-Context)\n// ============================================================================\n\n/**\n * A call that can be invoked directly to generate a response.\n *\n * Created by `defineCall()`. Unlike a `Prompt`, a `Call` has a model bundled in,\n * so it can be invoked without passing a model argument.\n *\n * @template T - The type of variables the call accepts. Defaults to empty object.\n * @template F - The format input type. The output type F is derived via ExtractFormatType<F>.\n *\n * @example With variables\n * ```typescript\n * const recommendBook = defineCall<{ genre: string }>({\n * model: 'anthropic/claude-sonnet-4-20250514',\n * template: ({ genre }) => `Recommend a ${genre} book`,\n * });\n *\n * const response = await recommendBook({ genre: 'fantasy' });\n * ```\n *\n * @example Without variables\n * ```typescript\n * const sayHello = defineCall({\n * model: 'anthropic/claude-sonnet-4-20250514',\n * template: () => 'Hello!',\n * });\n * const response = await sayHello();\n * ```\n */\nexport interface Call<T = NoVars, F extends AnyFormatInput = undefined> {\n /**\n * Call directly to generate a response (model is bundled).\n *\n * @param vars - The variables to pass to the template.\n * @returns A promise that resolves to the LLM response.\n */\n (\n ...args: keyof T extends never ? [] : [vars: T]\n ): Promise<Response<ExtractFormatType<F>>>;\n\n /**\n * Call directly to generate a response (model is bundled).\n * This is the method form of the callable interface.\n *\n * @param vars - The variables to pass to the template.\n * @returns A promise that resolves to the LLM response.\n */\n call(\n ...args: keyof T extends never ? [] : [vars: T]\n ): Promise<Response<ExtractFormatType<F>>>;\n\n /**\n * Stream directly to generate a streaming response (model is bundled).\n *\n * @param vars - The variables to pass to the template.\n * @returns A promise that resolves to the streaming LLM response.\n *\n * @example\n * ```typescript\n * const response = await call.stream({ genre: 'fantasy' });\n * for await (const text of response.textStream()) {\n * process.stdout.write(text);\n * }\n * ```\n */\n stream(\n ...args: keyof T extends never ? [] : [vars: T]\n ): Promise<StreamResponse<ExtractFormatType<F>>>;\n\n /**\n * The model used for generating responses.\n * Returns the context model if one is set via `withModel`, otherwise returns `defaultModel`.\n */\n readonly model: Model;\n\n /**\n * The default model configured when defining this call.\n * Use `model` to get the effective model (which respects context).\n */\n readonly defaultModel: Model;\n\n /**\n * The tools available to this call.\n */\n readonly tools: Tools | undefined;\n\n /**\n * The format specification for structured output, if any.\n */\n readonly format: FormatInput<ExtractFormatType<F>>;\n\n /**\n * The underlying prompt.\n */\n readonly prompt: Prompt<T, F>;\n\n /**\n * The underlying template function.\n */\n readonly template: TemplateFunc<T>;\n}\n\n// ============================================================================\n// Context Call Interface\n// ============================================================================\n\n/**\n * A context-aware call that can be invoked directly with a context to generate a response.\n *\n * Created by `defineCall()` when the template type includes `ctx: Context<DepsT>`.\n * Unlike a `ContextPrompt`, a `ContextCall` has a model bundled in, so it can be\n * invoked without passing a model argument.\n *\n * @template T - The type of variables the call accepts. Defaults to empty object.\n * @template DepsT - The type of dependencies in the context.\n * @template F - The format input type. The output type is derived via ExtractFormatType<F>.\n *\n * @example With variables\n * ```typescript\n * interface MyDeps { userId: string; }\n *\n * const greetUser = defineCall<{ ctx: Context<MyDeps>; greeting: string }>({\n * model: 'anthropic/claude-sonnet-4-20250514',\n * template: ({ ctx, greeting }) => `${greeting}, user ${ctx.deps.userId}!`,\n * });\n *\n * const ctx = createContext<MyDeps>({ userId: '123' });\n * const response = await greetUser(ctx, { greeting: 'Hello' });\n * ```\n *\n * @example Without variables\n * ```typescript\n * interface MyDeps { userId: string; }\n *\n * const sayHello = defineCall<{ ctx: Context<MyDeps> }>({\n * model: 'anthropic/claude-sonnet-4-20250514',\n * template: ({ ctx }) => `Hello, user ${ctx.deps.userId}!`,\n * });\n *\n * const ctx = createContext<MyDeps>({ userId: '123' });\n * const response = await sayHello(ctx);\n * ```\n */\nexport interface ContextCall<\n T = NoVars,\n DepsT = unknown,\n F extends AnyFormatInput = undefined,\n> {\n /**\n * Call directly with context to generate a response (model is bundled).\n *\n * @param ctx - The context containing dependencies.\n * @param vars - The variables to pass to the template.\n * @returns A promise that resolves to the LLM response.\n */\n (\n ctx: Context<DepsT>,\n ...args: keyof T extends never ? [] : [vars: T]\n ): Promise<ContextResponse<DepsT, ExtractFormatType<F>>>;\n\n /**\n * Call directly with context to generate a response (model is bundled).\n * This is the method form of the callable interface.\n *\n * @param ctx - The context containing dependencies.\n * @param vars - The variables to pass to the template.\n * @returns A promise that resolves to the LLM response.\n */\n call(\n ctx: Context<DepsT>,\n ...args: keyof T extends never ? [] : [vars: T]\n ): Promise<ContextResponse<DepsT, ExtractFormatType<F>>>;\n\n /**\n * Stream directly with context to generate a streaming response (model is bundled).\n *\n * @param ctx - The context containing dependencies.\n * @param vars - The variables to pass to the template.\n * @returns A promise that resolves to the streaming LLM response.\n *\n * @example\n * ```typescript\n * const response = await call.stream(ctx, { greeting: 'Hello' });\n * for await (const text of response.textStream()) {\n * process.stdout.write(text);\n * }\n * ```\n */\n stream(\n ctx: Context<DepsT>,\n ...args: keyof T extends never ? [] : [vars: T]\n ): Promise<ContextStreamResponse<DepsT, ExtractFormatType<F>>>;\n\n /**\n * The model used for generating responses.\n * Returns the context model if one is set via `withModel`, otherwise returns `defaultModel`.\n */\n readonly model: Model;\n\n /**\n * The default model configured when defining this call.\n * Use `model` to get the effective model (which respects context).\n */\n readonly defaultModel: Model;\n\n /**\n * The tools available to this call.\n */\n readonly tools: ContextTools<DepsT> | undefined;\n\n /**\n * The format specification for structured output, if any.\n */\n readonly format:\n | Format<ExtractFormatType<F>>\n | FormatSpec<ExtractFormatType<F>>\n | ZodLike\n | OutputParser<ExtractFormatType<F>>\n | null\n | undefined;\n\n /**\n * The underlying context prompt.\n */\n readonly prompt: ContextPrompt<T, DepsT, F>;\n\n /**\n * The underlying template function.\n */\n readonly template: ContextTemplateFunc<T, DepsT>;\n}\n\n// ============================================================================\n// Unified Call Type\n// ============================================================================\n\n/**\n * Unified call type that returns either Call or ContextCall\n * based on whether T includes `ctx: Context<DepsT>`.\n */\nexport type UnifiedCall<T, F extends AnyFormatInput = undefined> =\n ExtractDeps<T> extends never\n ? Call<T, F>\n : ContextCall<ExtractVars<T>, ExtractDeps<T>, F>;\n\n/**\n * A builder function returned when defineCall is called with only a type parameter.\n * Allows specifying the variables type explicitly while inferring the format type.\n *\n * @template T - The type of variables the call accepts (may include ctx for context calls).\n */\nexport interface CallBuilder<T extends Record<string, unknown>> {\n <F extends AnyFormatInput = undefined>(\n args: CallArgs<T, F> | ContextCallArgs<T, F>,\n ): UnifiedCall<T, F>;\n}\n\n// ============================================================================\n// Core Implementation\n// ============================================================================\n\n// Core implementation - separated to avoid overload matching issues with curried calls\nfunction createCall<T, F extends AnyFormatInput>({\n model,\n tools,\n format,\n template,\n ...params\n}: CallArgs<T, F> | ContextCallArgs<T, F>): UnifiedCall<T, F> {\n if (typeof model !== \"string\" && Object.keys(params).length > 0) {\n throw new Error(\n \"Cannot pass params when model is a Model instance. Use new Model(id, params) instead.\",\n );\n }\n\n // Resolve the default model at definition time (bakes in params)\n const defaultModel: Model =\n typeof model === \"string\" ? new Model(model, params) : model;\n\n // Create the unified prompt (it handles both context and non-context cases)\n const prompt = definePrompt({ tools, format, template } as PromptArgs<\n T & Record<string, unknown>,\n F\n >);\n\n // Create call function that handles both context and non-context cases\n // We use type assertions here because the unified prompt handles runtime detection\n const callImpl = async (\n ...args: unknown[]\n ): Promise<\n | Response<ExtractFormatType<F>>\n | ContextResponse<unknown, ExtractFormatType<F>>\n > => {\n const firstArg = args[0];\n\n if (isContext(firstArg)) {\n // Context case: call(ctx, vars?)\n const ctx = firstArg;\n const vars = args[1] as ExtractVars<T> | undefined;\n // Use the prompt's internal implementation which handles both cases\n const contextPrompt = prompt as unknown as {\n call(\n model: Model,\n ctx: Context<unknown>,\n vars?: ExtractVars<T>,\n ): Promise<ContextResponse<unknown, ExtractFormatType<F>>>;\n };\n return contextPrompt.call(useModel(defaultModel), ctx, vars);\n } else {\n // Non-context case: call(vars?)\n const vars = firstArg as T | undefined;\n const regularPrompt = prompt as unknown as {\n call(model: Model, vars?: T): Promise<Response<ExtractFormatType<F>>>;\n };\n return regularPrompt.call(useModel(defaultModel), vars);\n }\n };\n\n // Create callable wrapper\n const callable = async (\n ...args: unknown[]\n ): Promise<\n | Response<ExtractFormatType<F>>\n | ContextResponse<unknown, ExtractFormatType<F>>\n > => {\n return callImpl(...args);\n };\n\n // Create stream function\n const streamImpl = async (\n ...args: unknown[]\n ): Promise<\n | StreamResponse<ExtractFormatType<F>>\n | ContextStreamResponse<unknown, ExtractFormatType<F>>\n > => {\n const firstArg = args[0];\n\n if (isContext(firstArg)) {\n // Context case: stream(ctx, vars?)\n const ctx = firstArg;\n const vars = args[1] as ExtractVars<T> | undefined;\n const contextPrompt = prompt as unknown as {\n stream(\n model: Model,\n ctx: Context<unknown>,\n vars?: ExtractVars<T>,\n ): Promise<ContextStreamResponse<unknown, ExtractFormatType<F>>>;\n };\n return contextPrompt.stream(useModel(defaultModel), ctx, vars);\n } else {\n // Non-context case: stream(vars?)\n const vars = firstArg as T | undefined;\n const regularPrompt = prompt as unknown as {\n stream(\n model: Model,\n vars?: T,\n ): Promise<StreamResponse<ExtractFormatType<F>>>;\n };\n return regularPrompt.stream(useModel(defaultModel), vars);\n }\n };\n\n const definedCall = Object.assign(callable, {\n defaultModel,\n call: callImpl,\n stream: streamImpl,\n tools,\n format,\n prompt,\n template,\n });\n\n Object.defineProperty(definedCall, \"model\", {\n get: () => useModel(defaultModel),\n enumerable: true,\n });\n\n return definedCall as unknown as UnifiedCall<T, F>;\n}\n\n// ============================================================================\n// defineCall Function Overloads\n// ============================================================================\n\n/**\n * Define a call with explicit variables type, returning a builder that infers format.\n *\n * This overload enables specifying the variables type upfront while still allowing\n * the format type to be inferred from the `format` property.\n *\n * @template T - The type of variables the template accepts (may include ctx for context calls).\n * @returns A builder function that accepts call arguments and infers the format type.\n *\n * @example With explicit variables and inferred format\n * ```typescript\n * const recommendBook = defineCall<{ genre: string }>()({\n * model: 'anthropic/claude-sonnet-4-20250514',\n * format: defineFormat<Book>({ mode: 'tool' }),\n * template: ({ genre }) => `Recommend a ${genre} book`,\n * });\n *\n * const response = await recommendBook({ genre: 'fantasy' });\n * const book = response.parse(); // Typed as Book\n * ```\n *\n * @example Context-aware call with explicit type\n * ```typescript\n * interface MyDeps { userId: string; }\n *\n * const greetUser = defineCall<{ ctx: Context<MyDeps>; greeting: string }>()({\n * model: 'anthropic/claude-sonnet-4-20250514',\n * template: ({ ctx, greeting }) => `${greeting}, user ${ctx.deps.userId}!`,\n * });\n *\n * const ctx = createContext<MyDeps>({ userId: '123' });\n * const response = await greetUser(ctx, { greeting: 'Hello' });\n * ```\n */\nexport function defineCall<T extends Record<string, unknown>>(): CallBuilder<T>;\n\n/**\n * Define a call that automatically detects context from the template type.\n *\n * When T includes `ctx: Context<DepsT>`, returns a ContextCall.\n * Otherwise returns a regular Call.\n *\n * Both the variables type and format type are inferred from the arguments.\n * Type the template parameter to enable variables inference.\n *\n * @template T - The type of variables the template accepts (may include ctx for context calls).\n * @template F - The format input type (inferred from format property).\n * @param args - The call arguments including model, template, and optional parameters.\n * @returns A callable that can be invoked directly with variables (and context if T includes ctx).\n *\n * @example Call without variables\n * ```typescript\n * const sayHello = defineCall({\n * model: 'anthropic/claude-sonnet-4-20250514',\n * template: () => 'Hello!',\n * });\n * const response = await sayHello();\n * ```\n *\n * @example Regular call with variables\n * ```typescript\n * const recommendBook = defineCall({\n * model: 'anthropic/claude-sonnet-4-20250514',\n * format: defineFormat<Book>({ mode: 'tool' }),\n * template: ({ genre }: { genre: string }) => `Recommend a ${genre} book`,\n * });\n * const response = await recommendBook({ genre: 'fantasy' });\n * ```\n *\n * @example Context-aware call\n * ```typescript\n * interface MyDeps { userId: string; }\n *\n * const greetUser = defineCall({\n * model: 'anthropic/claude-sonnet-4-20250514',\n * template: ({ ctx, greeting }: { ctx: Context<MyDeps>; greeting: string }) =>\n * `${greeting}, user ${ctx.deps.userId}!`,\n * });\n *\n * const ctx = createContext<MyDeps>({ userId: '123' });\n * const response = await greetUser(ctx, { greeting: 'Hello' });\n * ```\n */\nexport function defineCall<\n T extends Record<string, unknown> = NoVars,\n F extends AnyFormatInput = undefined,\n>(args: CallArgs<T, F> | ContextCallArgs<T, F>): UnifiedCall<T, F>;\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n// Implementation\nexport function defineCall<T, F extends AnyFormatInput>(\n args?: CallArgs<T, F> | ContextCallArgs<T, F>,\n): UnifiedCall<T, F> | CallBuilder<T & Record<string, unknown>> {\n // If no args provided, return a builder function for curried usage\n if (args === undefined) {\n return (<F2 extends AnyFormatInput = undefined>(\n builderArgs: CallArgs<T, F2> | ContextCallArgs<T, F2>,\n ): UnifiedCall<T, F2> => {\n return createCall(builderArgs);\n }) as CallBuilder<T & Record<string, unknown>>;\n }\n\n return createCall(args);\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"model-T6IQ7UUA.js"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JSON Schema property definition for a single tool parameter.
|
|
3
|
+
*/
|
|
4
|
+
interface JsonSchemaProperty {
|
|
5
|
+
type?: string;
|
|
6
|
+
description?: string;
|
|
7
|
+
enum?: readonly (string | number | boolean)[];
|
|
8
|
+
items?: JsonSchemaProperty;
|
|
9
|
+
properties?: Record<string, JsonSchemaProperty>;
|
|
10
|
+
required?: readonly string[];
|
|
11
|
+
additionalProperties?: boolean;
|
|
12
|
+
default?: unknown;
|
|
13
|
+
$ref?: string;
|
|
14
|
+
oneOf?: readonly JsonSchemaProperty[];
|
|
15
|
+
allOf?: readonly JsonSchemaProperty[];
|
|
16
|
+
anyOf?: readonly JsonSchemaProperty[];
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Tool parameter schema following JSON Schema format.
|
|
20
|
+
*
|
|
21
|
+
* This represents the complete parameter schema for a tool,
|
|
22
|
+
* including all properties, required fields, and definitions.
|
|
23
|
+
*/
|
|
24
|
+
interface ToolParameterSchema {
|
|
25
|
+
readonly type: "object";
|
|
26
|
+
readonly title?: string;
|
|
27
|
+
readonly properties: Record<string, JsonSchemaProperty>;
|
|
28
|
+
readonly required: readonly string[];
|
|
29
|
+
readonly additionalProperties: false;
|
|
30
|
+
readonly $defs?: Record<string, JsonSchemaProperty>;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Complete tool schema including name, description, and parameters.
|
|
34
|
+
*
|
|
35
|
+
* This is the provider-agnostic representation of a tool that
|
|
36
|
+
* gets converted to provider-specific formats (OpenAI, Anthropic, etc.).
|
|
37
|
+
*/
|
|
38
|
+
interface ToolSchema {
|
|
39
|
+
readonly name: string;
|
|
40
|
+
readonly description: string;
|
|
41
|
+
readonly parameters: ToolParameterSchema;
|
|
42
|
+
readonly strict?: boolean;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export type { JsonSchemaProperty as J, ToolSchema as T, ToolParameterSchema as a };
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JSON Schema property definition for a single tool parameter.
|
|
3
|
+
*/
|
|
4
|
+
interface JsonSchemaProperty {
|
|
5
|
+
type?: string;
|
|
6
|
+
description?: string;
|
|
7
|
+
enum?: readonly (string | number | boolean)[];
|
|
8
|
+
items?: JsonSchemaProperty;
|
|
9
|
+
properties?: Record<string, JsonSchemaProperty>;
|
|
10
|
+
required?: readonly string[];
|
|
11
|
+
additionalProperties?: boolean;
|
|
12
|
+
default?: unknown;
|
|
13
|
+
$ref?: string;
|
|
14
|
+
oneOf?: readonly JsonSchemaProperty[];
|
|
15
|
+
allOf?: readonly JsonSchemaProperty[];
|
|
16
|
+
anyOf?: readonly JsonSchemaProperty[];
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Tool parameter schema following JSON Schema format.
|
|
20
|
+
*
|
|
21
|
+
* This represents the complete parameter schema for a tool,
|
|
22
|
+
* including all properties, required fields, and definitions.
|
|
23
|
+
*/
|
|
24
|
+
interface ToolParameterSchema {
|
|
25
|
+
readonly type: "object";
|
|
26
|
+
readonly title?: string;
|
|
27
|
+
readonly properties: Record<string, JsonSchemaProperty>;
|
|
28
|
+
readonly required: readonly string[];
|
|
29
|
+
readonly additionalProperties: false;
|
|
30
|
+
readonly $defs?: Record<string, JsonSchemaProperty>;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Complete tool schema including name, description, and parameters.
|
|
34
|
+
*
|
|
35
|
+
* This is the provider-agnostic representation of a tool that
|
|
36
|
+
* gets converted to provider-specific formats (OpenAI, Anthropic, etc.).
|
|
37
|
+
*/
|
|
38
|
+
interface ToolSchema {
|
|
39
|
+
readonly name: string;
|
|
40
|
+
readonly description: string;
|
|
41
|
+
readonly parameters: ToolParameterSchema;
|
|
42
|
+
readonly strict?: boolean;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export type { JsonSchemaProperty as J, ToolSchema as T, ToolParameterSchema as a };
|