@orpc/ai-sdk 2.0.0-beta.48 → 2.0.0-beta.49

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 CHANGED
@@ -5,7 +5,7 @@
5
5
  <img alt="codecov" src="https://codecov.io/gh/middleapi/orpc/branch/main/graph/badge.svg">
6
6
  </a>
7
7
  <a href="https://www.npmjs.com/package/@orpc/ai-sdk">
8
- <img alt="weekly downloads" src="https://img.shields.io/npm/dw/%40orpc%2Fai-sdk?logo=npm" />
8
+ <img alt="monthly downloads" src="https://img.shields.io/npm/dm/%40orpc%2Fai-sdk?logo=npm" />
9
9
  </a>
10
10
  <a href="https://app.codspeed.io/middleapi/orpc?utm_source=badge">
11
11
  <img alt="CodSpeed" src="https://img.shields.io/endpoint?url=https://codspeed.io/badge.json" />
@@ -41,10 +41,11 @@ export const router = {
41
41
  Then call them from a client that knows every input and output, without generating anything:
42
42
 
43
43
  ```ts
44
- import type { RouterClient } from '@orpc/server'
45
- import type { router } from './router'
46
44
  import { createORPCClient } from '@orpc/client'
47
45
  import { RPCLink } from '@orpc/client/fetch'
46
+ import type { RouterClient } from '@orpc/server'
47
+
48
+ import type { router } from './router'
48
49
 
49
50
  const link = new RPCLink({ origin: 'http://localhost:3000', url: '/rpc' })
50
51
  const client: RouterClient<typeof router> = createORPCClient(link)
@@ -208,7 +209,6 @@ With thanks to [40 past sponsors](https://orpc.dev/sponsors#past-sponsors) who h
208
209
  <tr>
209
210
  <td align="center"><a href="https://claude.com/contact-sales/claude-for-oss" target="_blank" rel="noopener" title="Claude for Open Source"><img src="https://cdn.simpleicons.org/claude" width="64" alt="Claude"/><br />Claude</a></td>
210
211
  <td align="center"><a href="https://pullfrog.com/for-oss" target="_blank" rel="noopener" title="Pullfrog for OSS"><img src="https://avatars.githubusercontent.com/in/1768019?s=128&amp;v=4" width="64" alt="Pullfrog"/><br />Pullfrog</a></td>
211
- <td align="center"><a href="https://macroscope.com/open-source" target="_blank" rel="noopener" title="Macroscope for Open Source"><img src="https://avatars.githubusercontent.com/in/900172?s=128&amp;v=4" width="64" alt="Macroscope"/><br />Macroscope</a></td>
212
212
  </tr>
213
213
  </table>
214
214
 
@@ -0,0 +1,2 @@
1
+ export * from './tool.ts';
2
+ export * from './tool-meta.ts';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from './tool.js';
2
+ export * from './tool-meta.js';
@@ -0,0 +1,54 @@
1
+ import type { AnyProcedureContract, AnySchema, ErrorMap, InferSchemaInput, InferSchemaOutput, MetaPlugin } from '@orpc/contract';
2
+ import type { Lazy } from '@orpc/server';
3
+ import type { JSONValue, Tool } from 'ai';
4
+ import type { ToolOutput } from './tool.ts';
5
+ /**
6
+ * The [function tool](https://ai-sdk.dev/docs/foundations/tools) member of the AI SDK `Tool` union,
7
+ * which is the kind of tool this package produces.
8
+ */
9
+ export type FunctionTool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any> = Extract<Tool<INPUT, OUTPUT>, {
10
+ type?: 'function' | undefined;
11
+ }>;
12
+ /**
13
+ * Base [AI SDK Tool](https://ai-sdk.dev/docs/foundations/tools) options attached to a procedure/contract,
14
+ * used as defaults when creating tools from it.
15
+ *
16
+ * @remarks
17
+ * **Note**: When defined multiple times, options are overridden by the most recent call.
18
+ *
19
+ * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-implementer | AI SDK Integration - Tool Implementer}
20
+ */
21
+ export type AiSdkToolMeta<TInputSchema extends AnySchema = AnySchema, TOutputSchema extends AnySchema = AnySchema> = Partial<Omit<FunctionTool<InferSchemaOutput<TInputSchema>, ToolOutput<InferSchemaInput<TOutputSchema>>>, 'inputSchema' | 'outputSchema' | 'execute'>>;
22
+ export interface AiSdkToolMetaPlugin<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> extends MetaPlugin<TInputSchema, TOutputSchema, TErrorMap> {
23
+ name: '~ai-sdk/tool';
24
+ }
25
+ export interface AiSdkToolFunction {
26
+ <TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap>(meta: AiSdkToolMeta<TInputSchema, TOutputSchema>): AiSdkToolMetaPlugin<TInputSchema, TOutputSchema, TErrorMap>;
27
+ }
28
+ /**
29
+ * Attaches base [AI SDK Tool](https://ai-sdk.dev/docs/foundations/tools) options to a procedure/contract,
30
+ * used as defaults when creating tools from it.
31
+ *
32
+ * @remarks
33
+ * **Note**: When defined multiple times, options are overridden by the most recent call.
34
+ *
35
+ * @example
36
+ * ```ts
37
+ * const getWeatherContract = oc
38
+ * .meta(aiSdkTool({
39
+ * description: 'Get the weather in a location',
40
+ * metadata: { source: 'weather-service' },
41
+ * }))
42
+ * .input(z.object({ location: z.string() }))
43
+ * ```
44
+ *
45
+ * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-implementer | AI SDK Integration - Tool Implementer}
46
+ */
47
+ export declare const aiSdkTool: AiSdkToolFunction;
48
+ /**
49
+ * Reads the base [AI SDK Tool](https://ai-sdk.dev/docs/foundations/tools) options
50
+ * attached to a procedure/contract by {@link aiSdkTool}.
51
+ *
52
+ * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-implementer | AI SDK Integration - Tool Implementer}
53
+ */
54
+ export declare function getAiSdkToolMeta(procedureOrLazy: AnyProcedureContract | Lazy<any>): AiSdkToolMeta | undefined;
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Attaches base [AI SDK Tool](https://ai-sdk.dev/docs/foundations/tools) options to a procedure/contract,
3
+ * used as defaults when creating tools from it.
4
+ *
5
+ * @remarks
6
+ * **Note**: When defined multiple times, options are overridden by the most recent call.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * const getWeatherContract = oc
11
+ * .meta(aiSdkTool({
12
+ * description: 'Get the weather in a location',
13
+ * metadata: { source: 'weather-service' },
14
+ * }))
15
+ * .input(z.object({ location: z.string() }))
16
+ * ```
17
+ *
18
+ * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-implementer | AI SDK Integration - Tool Implementer}
19
+ */
20
+ export const aiSdkTool = (incoming) => ({
21
+ name: '~ai-sdk/tool',
22
+ init(meta) {
23
+ const existing = meta['~ai-sdk/tool'];
24
+ return {
25
+ ...meta,
26
+ '~ai-sdk/tool': { ...existing, ...incoming },
27
+ };
28
+ },
29
+ });
30
+ /**
31
+ * Reads the base [AI SDK Tool](https://ai-sdk.dev/docs/foundations/tools) options
32
+ * attached to a procedure/contract by {@link aiSdkTool}.
33
+ *
34
+ * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-implementer | AI SDK Integration - Tool Implementer}
35
+ */
36
+ export function getAiSdkToolMeta(procedureOrLazy) {
37
+ return procedureOrLazy['~orpc'].meta['~ai-sdk/tool'];
38
+ }
package/dist/tool.d.ts ADDED
@@ -0,0 +1,119 @@
1
+ import type { ClientOptions } from '@orpc/client';
2
+ import type { AnySchema, InferSchemaInput, InferSchemaOutput, ProcedureContract, Schema } from '@orpc/contract';
3
+ import { OpenAPIJsonSerializer } from '@orpc/openapi';
4
+ import type { Context, ProcedureClientOptions } from '@orpc/server';
5
+ import { Procedure } from '@orpc/server';
6
+ import type { MaybeOptionalOptions, Public } from '@orpc/shared';
7
+ import type { Tool } from 'ai';
8
+ import type { FunctionTool } from './tool-meta.ts';
9
+ /**
10
+ * Infers the value an AI SDK tool outputs for a given oRPC output type.
11
+ *
12
+ * For [AsyncIteratorObject](https://orpc.dev/docs/async-iterator-object) outputs, the tool streams
13
+ * each yielded event as a [preliminary result](https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling#preliminary-tool-results)
14
+ * and the last event becomes the final result, so the tool output is the yield type.
15
+ *
16
+ * @see {@link https://orpc.dev/docs/integrations/ai-sdk#streaming-tool-outputs | AI SDK Integration - Streaming Tool Outputs}
17
+ */
18
+ export type ToolOutput<T> = T extends AsyncIteratorObject<infer TYield, any, any> ? TYield : T;
19
+ export interface ImplementToolFactoryOptions {
20
+ /**
21
+ * Serializes outputs for the default `toModelOutput`, converting types such as `Date`, `BigInt`, and `Set`
22
+ * the same way OpenAPI responses do.
23
+ *
24
+ * @default new OpenAPIJsonSerializer()
25
+ * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-outputs | AI SDK Integration - Tool Outputs}
26
+ */
27
+ serializer?: Public<OpenAPIJsonSerializer> | undefined;
28
+ }
29
+ export interface ToolImplementer {
30
+ <TInputSchema extends AnySchema, TOutputSchema extends AnySchema>(contract: ProcedureContract<TInputSchema, TOutputSchema, any>, ...rest: MaybeOptionalOptions<Omit<FunctionTool<InferSchemaOutput<TInputSchema>, ToolOutput<InferSchemaInput<TOutputSchema>>>, 'inputSchema' | 'outputSchema'>>): Tool<InferSchemaOutput<TInputSchema>, ToolOutput<InferSchemaInput<TOutputSchema>>>;
31
+ }
32
+ /**
33
+ * Creates a builder that implements [procedure contracts](https://orpc.dev/docs/contract/procedure)
34
+ * as [AI SDK Tools](https://ai-sdk.dev/docs/foundations/tools) by leveraging existing contract definitions.
35
+ *
36
+ * The factory accepts oRPC related options, and the resulting builder
37
+ * accepts a contract alongside AI SDK tool options.
38
+ *
39
+ * @remarks
40
+ * **Note**: [Procedures](https://orpc.dev/docs/procedure) are also compatible with [procedure contracts](https://orpc.dev/docs/contract/procedure).
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * import { aiSdkTool, implementToolFactory } from '@orpc/ai-sdk'
45
+ * import { oc } from '@orpc/contract'
46
+ *
47
+ * const getWeatherContract = oc
48
+ * .meta(
49
+ * aiSdkTool({ description: 'Get the weather in a location' }), // default AI SDK tool options
50
+ * )
51
+ * .input(
52
+ * z.object({
53
+ * location: z.string().describe('The location to get the weather for'),
54
+ * }),
55
+ * )
56
+ * .output(
57
+ * z.object({
58
+ * location: z.string().describe('The location the weather is for'),
59
+ * temperature: z.number().describe('The temperature in Celsius'),
60
+ * }),
61
+ * )
62
+ *
63
+ * const implementTool = implementToolFactory()
64
+ *
65
+ * const getWeatherTool = implementTool(getWeatherContract, {
66
+ * execute: async ({ location }) => ({
67
+ * location,
68
+ * temperature: 72 + Math.floor(Math.random() * 21) - 10,
69
+ * }),
70
+ * })
71
+ * ```
72
+ *
73
+ * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-implementer | AI SDK Integration - Tool Implementer}
74
+ */
75
+ export declare function implementToolFactory(options?: ImplementToolFactoryOptions): ToolImplementer;
76
+ export type CreateToolFactoryOptions<TInitialContext extends Context> = ImplementToolFactoryOptions & ProcedureClientOptions<TInitialContext, Schema<unknown>, object, object> & Omit<ClientOptions<object>, 'context' | 'signal'>;
77
+ export interface ToolFactory<TInitialContext extends Context> {
78
+ <TInputSchema extends AnySchema, TOutputSchema extends AnySchema>(procedure: Procedure<TInitialContext, any, TInputSchema, TOutputSchema, any>, ...rest: MaybeOptionalOptions<Omit<FunctionTool<InferSchemaOutput<TInputSchema>, ToolOutput<InferSchemaInput<TOutputSchema>>>, 'inputSchema' | 'outputSchema' | 'execute'>>): Tool<InferSchemaOutput<TInputSchema>, ToolOutput<InferSchemaInput<TOutputSchema>>>;
79
+ }
80
+ /**
81
+ * Creates a builder that converts [procedures](https://orpc.dev/docs/procedure)
82
+ * into [AI SDK Tools](https://ai-sdk.dev/docs/foundations/tools) by leveraging existing procedure definitions.
83
+ *
84
+ * The factory accepts oRPC related options, and the resulting builder
85
+ * accepts a procedure alongside AI SDK tool options.
86
+ *
87
+ * @example
88
+ * ```ts
89
+ * import { aiSdkTool, createToolFactory } from '@orpc/ai-sdk'
90
+ * import { os } from '@orpc/server'
91
+ *
92
+ * const getWeatherProcedure = os
93
+ * .meta(
94
+ * aiSdkTool({ description: 'Get the weather in a location' }), // default AI SDK tool options
95
+ * )
96
+ * .input(z.object({
97
+ * location: z.string().describe('The location to get the weather for'),
98
+ * }))
99
+ * .output(z.object({
100
+ * location: z.string().describe('The location the weather is for'),
101
+ * temperature: z.number().describe('The temperature in Celsius'),
102
+ * }))
103
+ * .handler(async ({ input }) => ({
104
+ * location: input.location,
105
+ * temperature: 72 + Math.floor(Math.random() * 21) - 10,
106
+ * }))
107
+ *
108
+ * const createTool = createToolFactory({
109
+ * context: {}, // provide initial context if needed
110
+ * })
111
+ *
112
+ * const getWeatherTool = createTool(getWeatherProcedure, {
113
+ * // ...AI SDK tool options/overrides here if needed
114
+ * })
115
+ * ```
116
+ *
117
+ * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-factory | AI SDK Integration - Tool Factory}
118
+ */
119
+ export declare function createToolFactory<TInitialContext extends Context = object>(...rest: MaybeOptionalOptions<CreateToolFactoryOptions<TInitialContext>>): ToolFactory<TInitialContext>;
package/dist/tool.js ADDED
@@ -0,0 +1,244 @@
1
+ import { getAsyncIteratorObjectSchemasDetails } from '@orpc/contract';
2
+ import { combineJsonSchemasWithComposition } from '@orpc/json-schema';
3
+ import { OpenAPIJsonSerializer } from '@orpc/openapi';
4
+ import { call, Procedure } from '@orpc/server';
5
+ import { encodeBase64, isAsyncGeneratorFunction, loadBytes, mergeTwoLevels, ORPC_NAME, resolveMaybeOptionalOptions, stringifyJSON, toArray, } from '@orpc/shared';
6
+ import { tool } from 'ai';
7
+ import { getAiSdkToolMeta } from './tool-meta.js';
8
+ const ANY_SCHEMA = {
9
+ '~standard': {
10
+ vendor: ORPC_NAME,
11
+ version: 1,
12
+ validate: (value) => ({ value }),
13
+ jsonSchema: {
14
+ input: () => ({}),
15
+ output: () => ({}),
16
+ },
17
+ },
18
+ };
19
+ function combineJsonSchemas(jsonSchemas) {
20
+ let $schema;
21
+ const branches = jsonSchemas.map((jsonSchema) => {
22
+ if ('$schema' in jsonSchema) {
23
+ const { $schema: branch$schema, ...rest } = jsonSchema;
24
+ $schema ??= branch$schema;
25
+ return rest;
26
+ }
27
+ return jsonSchema;
28
+ });
29
+ const combined = combineJsonSchemasWithComposition('allOf', branches);
30
+ return { $schema, ...combined };
31
+ }
32
+ function combineSchemas(schemas, merge) {
33
+ if (schemas.length === 0) {
34
+ return undefined;
35
+ }
36
+ if (schemas.length === 1) {
37
+ return schemas[0];
38
+ }
39
+ const standardJsonSchemas = schemas.filter((schema) => schema['~standard'].jsonSchema);
40
+ const jsonSchema = standardJsonSchemas.length
41
+ ? {
42
+ input: (options) => combineJsonSchemas(standardJsonSchemas.map((schema) => schema['~standard'].jsonSchema.input(options))),
43
+ output: (options) => combineJsonSchemas(standardJsonSchemas.map((schema) => schema['~standard'].jsonSchema.output(options))),
44
+ }
45
+ : undefined;
46
+ return {
47
+ '~standard': {
48
+ vendor: ORPC_NAME,
49
+ version: 1,
50
+ async validate(value) {
51
+ let current = value;
52
+ // Mirrors the server's stacked input validation, output schemas stay piped.
53
+ for (const [index, schema] of schemas.entries()) {
54
+ const merging = merge && index !== 0;
55
+ const result = await schema['~standard'].validate(merging ? mergeTwoLevels(value, current) : current);
56
+ if (result.issues) {
57
+ return result;
58
+ }
59
+ current = merging ? mergeTwoLevels(current, result.value) : result.value;
60
+ }
61
+ return { value: current };
62
+ },
63
+ jsonSchema,
64
+ },
65
+ };
66
+ }
67
+ function combineOutputSchemas(outputSchemas) {
68
+ const yieldSchemas = getAsyncIteratorObjectSchemasDetails(outputSchemas)?.yieldSchemas;
69
+ // oxlint-disable-next-line unicorn/no-array-reverse
70
+ return combineSchemas([...(yieldSchemas ?? outputSchemas)].reverse(), false);
71
+ }
72
+ /**
73
+ * Serializes an output like an OpenAPI response body. JSON shows a `Blob` as an empty object,
74
+ * so blobs, nested or not, are sent as file parts named by their path, such as `report/q3.pdf`.
75
+ */
76
+ async function toModelOutput(serializer, output) {
77
+ const { json, maps, blobs } = serializer.serializeJson(output);
78
+ if (typeof json === 'string') {
79
+ return { type: 'text', value: json };
80
+ }
81
+ if (!blobs?.length) {
82
+ return { type: 'json', value: (json ?? null) };
83
+ }
84
+ const files = await Promise.all(blobs.map(async (blob, i) => {
85
+ const path = maps[i];
86
+ const names = blob instanceof File && blob.name !== '' ? [...path, blob.name] : path;
87
+ return {
88
+ type: 'file',
89
+ mediaType: blob.type || 'application/octet-stream',
90
+ // base64 is encoded once, providers would otherwise re-encode the bytes on every step
91
+ data: { type: 'data', data: encodeBase64(await loadBytes(blob)) },
92
+ ...(names.length === 0 ? {} : { filename: names.join('/') }),
93
+ };
94
+ }));
95
+ return {
96
+ type: 'content',
97
+ value: json instanceof Blob ? files : [{ type: 'text', text: stringifyJSON(json) }, ...files],
98
+ };
99
+ }
100
+ /**
101
+ * Creates a builder that implements [procedure contracts](https://orpc.dev/docs/contract/procedure)
102
+ * as [AI SDK Tools](https://ai-sdk.dev/docs/foundations/tools) by leveraging existing contract definitions.
103
+ *
104
+ * The factory accepts oRPC related options, and the resulting builder
105
+ * accepts a contract alongside AI SDK tool options.
106
+ *
107
+ * @remarks
108
+ * **Note**: [Procedures](https://orpc.dev/docs/procedure) are also compatible with [procedure contracts](https://orpc.dev/docs/contract/procedure).
109
+ *
110
+ * @example
111
+ * ```ts
112
+ * import { aiSdkTool, implementToolFactory } from '@orpc/ai-sdk'
113
+ * import { oc } from '@orpc/contract'
114
+ *
115
+ * const getWeatherContract = oc
116
+ * .meta(
117
+ * aiSdkTool({ description: 'Get the weather in a location' }), // default AI SDK tool options
118
+ * )
119
+ * .input(
120
+ * z.object({
121
+ * location: z.string().describe('The location to get the weather for'),
122
+ * }),
123
+ * )
124
+ * .output(
125
+ * z.object({
126
+ * location: z.string().describe('The location the weather is for'),
127
+ * temperature: z.number().describe('The temperature in Celsius'),
128
+ * }),
129
+ * )
130
+ *
131
+ * const implementTool = implementToolFactory()
132
+ *
133
+ * const getWeatherTool = implementTool(getWeatherContract, {
134
+ * execute: async ({ location }) => ({
135
+ * location,
136
+ * temperature: 72 + Math.floor(Math.random() * 21) - 10,
137
+ * }),
138
+ * })
139
+ * ```
140
+ *
141
+ * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-implementer | AI SDK Integration - Tool Implementer}
142
+ */
143
+ export function implementToolFactory(options = {}) {
144
+ const serializer = options.serializer ?? new OpenAPIJsonSerializer();
145
+ const defaultToModelOutput = ({ output }) => toModelOutput(serializer, output);
146
+ const factory = (contract, ...rest) => {
147
+ const toolOptions = resolveMaybeOptionalOptions(rest);
148
+ const inputSchemas = toArray(contract['~orpc'].inputSchemas);
149
+ const outputSchemas = toArray(contract['~orpc'].outputSchemas);
150
+ const defaults = getAiSdkToolMeta(contract);
151
+ return tool({
152
+ ...defaults,
153
+ ...toolOptions,
154
+ toModelOutput: toolOptions.toModelOutput ?? defaults?.toModelOutput ?? defaultToModelOutput,
155
+ inputSchema: combineSchemas(inputSchemas, true) ?? ANY_SCHEMA,
156
+ outputSchema: combineOutputSchemas(outputSchemas),
157
+ });
158
+ };
159
+ return factory;
160
+ }
161
+ /**
162
+ * Creates a builder that converts [procedures](https://orpc.dev/docs/procedure)
163
+ * into [AI SDK Tools](https://ai-sdk.dev/docs/foundations/tools) by leveraging existing procedure definitions.
164
+ *
165
+ * The factory accepts oRPC related options, and the resulting builder
166
+ * accepts a procedure alongside AI SDK tool options.
167
+ *
168
+ * @example
169
+ * ```ts
170
+ * import { aiSdkTool, createToolFactory } from '@orpc/ai-sdk'
171
+ * import { os } from '@orpc/server'
172
+ *
173
+ * const getWeatherProcedure = os
174
+ * .meta(
175
+ * aiSdkTool({ description: 'Get the weather in a location' }), // default AI SDK tool options
176
+ * )
177
+ * .input(z.object({
178
+ * location: z.string().describe('The location to get the weather for'),
179
+ * }))
180
+ * .output(z.object({
181
+ * location: z.string().describe('The location the weather is for'),
182
+ * temperature: z.number().describe('The temperature in Celsius'),
183
+ * }))
184
+ * .handler(async ({ input }) => ({
185
+ * location: input.location,
186
+ * temperature: 72 + Math.floor(Math.random() * 21) - 10,
187
+ * }))
188
+ *
189
+ * const createTool = createToolFactory({
190
+ * context: {}, // provide initial context if needed
191
+ * })
192
+ *
193
+ * const getWeatherTool = createTool(getWeatherProcedure, {
194
+ * // ...AI SDK tool options/overrides here if needed
195
+ * })
196
+ * ```
197
+ *
198
+ * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-factory | AI SDK Integration - Tool Factory}
199
+ */
200
+ export function createToolFactory(...rest) {
201
+ const options = resolveMaybeOptionalOptions(rest);
202
+ const implementTool = implementToolFactory(options);
203
+ const factory = (procedure, ...rest) => {
204
+ const toolOptions = resolveMaybeOptionalOptions(rest);
205
+ /**
206
+ * The AI SDK already validates input against the tool's `inputSchema`,
207
+ * so input validation is disabled at the oRPC level to avoid validating twice.
208
+ * Output validation stays enabled because the AI SDK does not validate
209
+ * the value returned from `execute` against the tool's `outputSchema`.
210
+ */
211
+ const disabledValidation = new Procedure({
212
+ ...procedure['~orpc'],
213
+ disableInputValidation: true,
214
+ });
215
+ /**
216
+ * Output schemas are the source of truth, but an `async function*` handler always
217
+ * returns an async iterator, so it streams even without an `asyncIteratorObject` schema.
218
+ */
219
+ const isIteratorOutput = getAsyncIteratorObjectSchemasDetails(procedure['~orpc'].outputSchemas) !== undefined ||
220
+ isAsyncGeneratorFunction(procedure['~orpc'].handler);
221
+ return implementTool(procedure, {
222
+ ...toolOptions,
223
+ /**
224
+ * For async iterator outputs, the tool streams each event as a
225
+ * [preliminary result](https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling#preliminary-tool-results),
226
+ * and the last event becomes the final result.
227
+ */
228
+ execute: isIteratorOutput
229
+ ? async function* (input, callingOptions) {
230
+ yield* (await call(disabledValidation, input, {
231
+ ...options,
232
+ signal: callingOptions.abortSignal,
233
+ }));
234
+ }
235
+ : (input, callingOptions) => {
236
+ return call(disabledValidation, input, {
237
+ ...options,
238
+ signal: callingOptions.abortSignal,
239
+ });
240
+ },
241
+ });
242
+ };
243
+ return factory;
244
+ }
package/package.json CHANGED
@@ -1,57 +1,55 @@
1
1
  {
2
2
  "name": "@orpc/ai-sdk",
3
- "type": "module",
4
- "version": "2.0.0-beta.48",
3
+ "version": "2.0.0-beta.49",
5
4
  "description": "AI SDK integration for oRPC: turn contracts and procedures into typesafe AI SDK tools",
6
- "license": "MIT",
7
- "funding": [
8
- "https://github.com/sponsors/dinwwwh",
9
- "https://opencollective.com/middleapi"
5
+ "keywords": [
6
+ "agents",
7
+ "ai",
8
+ "ai-sdk",
9
+ "llm",
10
+ "orpc",
11
+ "tools",
12
+ "typesafe",
13
+ "typescript"
10
14
  ],
11
15
  "homepage": "https://orpc.dev",
16
+ "license": "MIT",
12
17
  "repository": {
13
18
  "type": "git",
14
19
  "url": "git+https://github.com/middleapi/orpc.git",
15
20
  "directory": "packages/ai-sdk"
16
21
  },
17
- "keywords": [
18
- "orpc",
19
- "ai",
20
- "ai-sdk",
21
- "tools",
22
- "llm",
23
- "agents",
24
- "typescript",
25
- "typesafe"
22
+ "funding": [
23
+ "https://github.com/sponsors/dinwwwh",
24
+ "https://opencollective.com/middleapi"
26
25
  ],
26
+ "files": [
27
+ "dist"
28
+ ],
29
+ "type": "module",
27
30
  "sideEffects": false,
28
31
  "exports": {
29
32
  "./package.json": "./package.json",
30
33
  ".": {
31
- "types": "./dist/index.d.mts",
32
- "import": "./dist/index.mjs",
33
- "default": "./dist/index.mjs"
34
+ "types": "./dist/index.d.ts",
35
+ "import": "./dist/index.js",
36
+ "default": "./dist/index.js"
34
37
  }
35
38
  },
36
- "files": [
37
- "dist"
38
- ],
39
- "peerDependencies": {
40
- "ai": ">=7.0.31"
41
- },
42
39
  "dependencies": {
43
- "@orpc/client": "2.0.0-beta.48",
44
- "@orpc/contract": "2.0.0-beta.48",
45
- "@orpc/json-schema": "2.0.0-beta.48",
46
- "@orpc/openapi": "2.0.0-beta.48",
47
- "@orpc/server": "2.0.0-beta.48",
48
- "@orpc/shared": "2.0.0-beta.48"
40
+ "@orpc/client": "2.0.0-beta.49",
41
+ "@orpc/contract": "2.0.0-beta.49",
42
+ "@orpc/json-schema": "2.0.0-beta.49",
43
+ "@orpc/openapi": "2.0.0-beta.49",
44
+ "@orpc/server": "2.0.0-beta.49",
45
+ "@orpc/shared": "2.0.0-beta.49"
49
46
  },
50
47
  "devDependencies": {
51
- "ai": "^7.0.157",
48
+ "ai": "^7.0.162",
52
49
  "zod": "^4.6.7"
53
50
  },
54
- "scripts": {
55
- "type:check": "tsc -b"
56
- }
51
+ "peerDependencies": {
52
+ "ai": ">=7.0.31"
53
+ },
54
+ "scripts": {}
57
55
  }
package/dist/index.d.mts DELETED
@@ -1,2 +0,0 @@
1
- export * from "./tool.mjs";
2
- export * from "./tool-meta.mjs";
package/dist/index.mjs DELETED
@@ -1,2 +0,0 @@
1
- export * from "./tool.mjs";
2
- export * from "./tool-meta.mjs";
@@ -1,68 +0,0 @@
1
- import type { AnyProcedureContract, AnySchema, ErrorMap, InferSchemaInput, InferSchemaOutput, MetaPlugin } from "@orpc/contract";
2
- import type { Lazy } from "@orpc/server";
3
- import type { JSONValue, Tool } from "ai";
4
- import type { ToolOutput } from "./tool.mjs";
5
- /**
6
- * The [function tool](https://ai-sdk.dev/docs/foundations/tools) member of the AI SDK `Tool` union,
7
- * which is the kind of tool this package produces.
8
- */
9
- export type FunctionTool<
10
- INPUT extends JSONValue | unknown | never = any,
11
- OUTPUT extends JSONValue | unknown | never = any
12
- > = Extract<Tool<INPUT, OUTPUT>, {
13
- type?: "function" | undefined;
14
- }>;
15
- /**
16
- * Base [AI SDK Tool](https://ai-sdk.dev/docs/foundations/tools) options attached to a procedure/contract,
17
- * used as defaults when creating tools from it.
18
- *
19
- * @remarks
20
- * **Note**: When defined multiple times, options are overridden by the most recent call.
21
- *
22
- * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-implementer | AI SDK Integration - Tool Implementer}
23
- */
24
- export type AiSdkToolMeta<
25
- TInputSchema extends AnySchema = AnySchema,
26
- TOutputSchema extends AnySchema = AnySchema
27
- > = Partial<Omit<FunctionTool<InferSchemaOutput<TInputSchema>, ToolOutput<InferSchemaInput<TOutputSchema>>>, "inputSchema" | "outputSchema" | "execute">>;
28
- export interface AiSdkToolMetaPlugin<
29
- TInputSchema extends AnySchema,
30
- TOutputSchema extends AnySchema,
31
- TErrorMap extends ErrorMap
32
- > extends MetaPlugin<TInputSchema, TOutputSchema, TErrorMap> {
33
- name: "~ai-sdk/tool";
34
- }
35
- export interface AiSdkToolFunction {
36
- <
37
- TInputSchema extends AnySchema,
38
- TOutputSchema extends AnySchema,
39
- TErrorMap extends ErrorMap
40
- >(meta: AiSdkToolMeta<TInputSchema, TOutputSchema>): AiSdkToolMetaPlugin<TInputSchema, TOutputSchema, TErrorMap>;
41
- }
42
- /**
43
- * Attaches base [AI SDK Tool](https://ai-sdk.dev/docs/foundations/tools) options to a procedure/contract,
44
- * used as defaults when creating tools from it.
45
- *
46
- * @remarks
47
- * **Note**: When defined multiple times, options are overridden by the most recent call.
48
- *
49
- * @example
50
- * ```ts
51
- * const getWeatherContract = oc
52
- * .meta(aiSdkTool({
53
- * description: 'Get the weather in a location',
54
- * metadata: { source: 'weather-service' },
55
- * }))
56
- * .input(z.object({ location: z.string() }))
57
- * ```
58
- *
59
- * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-implementer | AI SDK Integration - Tool Implementer}
60
- */
61
- export declare const aiSdkTool: AiSdkToolFunction;
62
- /**
63
- * Reads the base [AI SDK Tool](https://ai-sdk.dev/docs/foundations/tools) options
64
- * attached to a procedure/contract by {@link aiSdkTool}.
65
- *
66
- * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-implementer | AI SDK Integration - Tool Implementer}
67
- */
68
- export declare function getAiSdkToolMeta(procedureOrLazy: AnyProcedureContract | Lazy<any>): AiSdkToolMeta | undefined;
@@ -1,18 +0,0 @@
1
-
2
- export const aiSdkTool = (incoming) => ({
3
- name: "~ai-sdk/tool",
4
- init(meta) {
5
- const existing = meta["~ai-sdk/tool"];
6
- return {
7
- ...meta,
8
- "~ai-sdk/tool": {
9
- ...existing,
10
- ...incoming
11
- }
12
- };
13
- }
14
- });
15
-
16
- export function getAiSdkToolMeta(procedureOrLazy) {
17
- return procedureOrLazy["~orpc"].meta["~ai-sdk/tool"];
18
- }
package/dist/tool.d.mts DELETED
@@ -1,125 +0,0 @@
1
- import type { ClientOptions } from "@orpc/client";
2
- import type { AnySchema, InferSchemaInput, InferSchemaOutput, ProcedureContract, Schema } from "@orpc/contract";
3
- import type { Context, ProcedureClientOptions } from "@orpc/server";
4
- import type { MaybeOptionalOptions, Public } from "@orpc/shared";
5
- import type { Tool } from "ai";
6
- import type { FunctionTool } from "./tool-meta.mjs";
7
- import { OpenAPIJsonSerializer } from "@orpc/openapi";
8
- import { Procedure } from "@orpc/server";
9
- /**
10
- * Infers the value an AI SDK tool outputs for a given oRPC output type.
11
- *
12
- * For [AsyncIteratorObject](https://orpc.dev/docs/async-iterator-object) outputs, the tool streams
13
- * each yielded event as a [preliminary result](https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling#preliminary-tool-results)
14
- * and the last event becomes the final result, so the tool output is the yield type.
15
- *
16
- * @see {@link https://orpc.dev/docs/integrations/ai-sdk#streaming-tool-outputs | AI SDK Integration - Streaming Tool Outputs}
17
- */
18
- export type ToolOutput<T> = T extends AsyncIteratorObject<infer TYield, any, any> ? TYield : T;
19
- export interface ImplementToolFactoryOptions {
20
- /**
21
- * Serializes outputs for the default `toModelOutput`, converting types such as `Date`, `BigInt`, and `Set`
22
- * the same way OpenAPI responses do.
23
- *
24
- * @default new OpenAPIJsonSerializer()
25
- * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-outputs | AI SDK Integration - Tool Outputs}
26
- */
27
- serializer?: Public<OpenAPIJsonSerializer> | undefined;
28
- }
29
- export interface ToolImplementer {
30
- <
31
- TInputSchema extends AnySchema,
32
- TOutputSchema extends AnySchema
33
- >(contract: ProcedureContract<TInputSchema, TOutputSchema, any>, ...rest: MaybeOptionalOptions<Omit<FunctionTool<InferSchemaOutput<TInputSchema>, ToolOutput<InferSchemaInput<TOutputSchema>>>, "inputSchema" | "outputSchema">>): Tool<InferSchemaOutput<TInputSchema>, ToolOutput<InferSchemaInput<TOutputSchema>>>;
34
- }
35
- /**
36
- * Creates a builder that implements [procedure contracts](https://orpc.dev/docs/contract/procedure)
37
- * as [AI SDK Tools](https://ai-sdk.dev/docs/foundations/tools) by leveraging existing contract definitions.
38
- *
39
- * The factory accepts oRPC related options, and the resulting builder
40
- * accepts a contract alongside AI SDK tool options.
41
- *
42
- * @remarks
43
- * **Note**: [Procedures](https://orpc.dev/docs/procedure) are also compatible with [procedure contracts](https://orpc.dev/docs/contract/procedure).
44
- *
45
- * @example
46
- * ```ts
47
- * import { aiSdkTool, implementToolFactory } from '@orpc/ai-sdk'
48
- * import { oc } from '@orpc/contract'
49
- *
50
- * const getWeatherContract = oc
51
- * .meta(
52
- * aiSdkTool({ description: 'Get the weather in a location' }), // default AI SDK tool options
53
- * )
54
- * .input(
55
- * z.object({
56
- * location: z.string().describe('The location to get the weather for'),
57
- * }),
58
- * )
59
- * .output(
60
- * z.object({
61
- * location: z.string().describe('The location the weather is for'),
62
- * temperature: z.number().describe('The temperature in Celsius'),
63
- * }),
64
- * )
65
- *
66
- * const implementTool = implementToolFactory()
67
- *
68
- * const getWeatherTool = implementTool(getWeatherContract, {
69
- * execute: async ({ location }) => ({
70
- * location,
71
- * temperature: 72 + Math.floor(Math.random() * 21) - 10,
72
- * }),
73
- * })
74
- * ```
75
- *
76
- * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-implementer | AI SDK Integration - Tool Implementer}
77
- */
78
- export declare function implementToolFactory(options?: ImplementToolFactoryOptions): ToolImplementer;
79
- export type CreateToolFactoryOptions<TInitialContext extends Context> = ImplementToolFactoryOptions & ProcedureClientOptions<TInitialContext, Schema<unknown>, object, object> & Omit<ClientOptions<object>, "context" | "signal">;
80
- export interface ToolFactory<TInitialContext extends Context> {
81
- <
82
- TInputSchema extends AnySchema,
83
- TOutputSchema extends AnySchema
84
- >(procedure: Procedure<TInitialContext, any, TInputSchema, TOutputSchema, any>, ...rest: MaybeOptionalOptions<Omit<FunctionTool<InferSchemaOutput<TInputSchema>, ToolOutput<InferSchemaInput<TOutputSchema>>>, "inputSchema" | "outputSchema" | "execute">>): Tool<InferSchemaOutput<TInputSchema>, ToolOutput<InferSchemaInput<TOutputSchema>>>;
85
- }
86
- /**
87
- * Creates a builder that converts [procedures](https://orpc.dev/docs/procedure)
88
- * into [AI SDK Tools](https://ai-sdk.dev/docs/foundations/tools) by leveraging existing procedure definitions.
89
- *
90
- * The factory accepts oRPC related options, and the resulting builder
91
- * accepts a procedure alongside AI SDK tool options.
92
- *
93
- * @example
94
- * ```ts
95
- * import { aiSdkTool, createToolFactory } from '@orpc/ai-sdk'
96
- * import { os } from '@orpc/server'
97
- *
98
- * const getWeatherProcedure = os
99
- * .meta(
100
- * aiSdkTool({ description: 'Get the weather in a location' }), // default AI SDK tool options
101
- * )
102
- * .input(z.object({
103
- * location: z.string().describe('The location to get the weather for'),
104
- * }))
105
- * .output(z.object({
106
- * location: z.string().describe('The location the weather is for'),
107
- * temperature: z.number().describe('The temperature in Celsius'),
108
- * }))
109
- * .handler(async ({ input }) => ({
110
- * location: input.location,
111
- * temperature: 72 + Math.floor(Math.random() * 21) - 10,
112
- * }))
113
- *
114
- * const createTool = createToolFactory({
115
- * context: {}, // provide initial context if needed
116
- * })
117
- *
118
- * const getWeatherTool = createTool(getWeatherProcedure, {
119
- * // ...AI SDK tool options/overrides here if needed
120
- * })
121
- * ```
122
- *
123
- * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-factory | AI SDK Integration - Tool Factory}
124
- */
125
- export declare function createToolFactory<TInitialContext extends Context = object>(...rest: MaybeOptionalOptions<CreateToolFactoryOptions<TInitialContext>>): ToolFactory<TInitialContext>;
package/dist/tool.mjs DELETED
@@ -1,154 +0,0 @@
1
- import { getAsyncIteratorObjectSchemasDetails } from "@orpc/contract";
2
- import { combineJsonSchemasWithComposition } from "@orpc/json-schema";
3
- import { OpenAPIJsonSerializer } from "@orpc/openapi";
4
- import { call, Procedure } from "@orpc/server";
5
- import { encodeBase64, isAsyncGeneratorFunction, loadBytes, mergeTwoLevels, ORPC_NAME, resolveMaybeOptionalOptions, stringifyJSON, toArray } from "@orpc/shared";
6
- import { tool } from "ai";
7
- import { getAiSdkToolMeta } from "./tool-meta.mjs";
8
- const ANY_SCHEMA = { "~standard": {
9
- vendor: ORPC_NAME,
10
- version: 1,
11
- validate: (value) => ({ value }),
12
- jsonSchema: {
13
- input: () => ({}),
14
- output: () => ({})
15
- }
16
- } };
17
- function combineJsonSchemas(jsonSchemas) {
18
- let $schema;
19
- const branches = jsonSchemas.map((jsonSchema) => {
20
- if ("$schema" in jsonSchema) {
21
- const { $schema: branch$schema, ...rest } = jsonSchema;
22
- $schema ??= branch$schema;
23
- return rest;
24
- }
25
- return jsonSchema;
26
- });
27
- const combined = combineJsonSchemasWithComposition("allOf", branches);
28
- return {
29
- $schema,
30
- ...combined
31
- };
32
- }
33
- function combineSchemas(schemas, merge) {
34
- if (schemas.length === 0) {
35
- return undefined;
36
- }
37
- if (schemas.length === 1) {
38
- return schemas[0];
39
- }
40
- const standardJsonSchemas = schemas.filter((schema) => schema["~standard"].jsonSchema);
41
- const jsonSchema = standardJsonSchemas.length ? {
42
- input: (options) => combineJsonSchemas(standardJsonSchemas.map((schema) => schema["~standard"].jsonSchema.input(options))),
43
- output: (options) => combineJsonSchemas(standardJsonSchemas.map((schema) => schema["~standard"].jsonSchema.output(options)))
44
- } : undefined;
45
- return { "~standard": {
46
- vendor: ORPC_NAME,
47
- version: 1,
48
- async validate(value) {
49
- let current = value;
50
-
51
- for (const [index, schema] of schemas.entries()) {
52
- const merging = merge && index !== 0;
53
- const result = await schema["~standard"].validate(merging ? mergeTwoLevels(value, current) : current);
54
- if (result.issues) {
55
- return result;
56
- }
57
- current = merging ? mergeTwoLevels(current, result.value) : result.value;
58
- }
59
- return { value: current };
60
- },
61
- jsonSchema
62
- } };
63
- }
64
- function combineOutputSchemas(outputSchemas) {
65
- const yieldSchemas = getAsyncIteratorObjectSchemasDetails(outputSchemas)?.yieldSchemas;
66
- return combineSchemas([...yieldSchemas ?? outputSchemas].reverse(), false);
67
- }
68
-
69
- async function toModelOutput(serializer, output) {
70
- const { json, maps, blobs } = serializer.serializeJson(output);
71
- if (typeof json === "string") {
72
- return {
73
- type: "text",
74
- value: json
75
- };
76
- }
77
- if (!blobs?.length) {
78
- return {
79
- type: "json",
80
- value: json ?? null
81
- };
82
- }
83
- const files = await Promise.all(blobs.map(async (blob, i) => {
84
- const path = maps[i];
85
- const names = blob instanceof File && blob.name !== "" ? [...path, blob.name] : path;
86
- return {
87
- type: "file",
88
- mediaType: blob.type || "application/octet-stream",
89
-
90
- data: {
91
- type: "data",
92
- data: encodeBase64(await loadBytes(blob))
93
- },
94
- ...names.length === 0 ? {} : { filename: names.join("/") }
95
- };
96
- }));
97
- return {
98
- type: "content",
99
- value: json instanceof Blob ? files : [{
100
- type: "text",
101
- text: stringifyJSON(json)
102
- }, ...files]
103
- };
104
- }
105
-
106
- export function implementToolFactory(options = {}) {
107
- const serializer = options.serializer ?? new OpenAPIJsonSerializer();
108
- const defaultToModelOutput = ({ output }) => toModelOutput(serializer, output);
109
- const factory = (contract, ...rest) => {
110
- const toolOptions = resolveMaybeOptionalOptions(rest);
111
- const inputSchemas = toArray(contract["~orpc"].inputSchemas);
112
- const outputSchemas = toArray(contract["~orpc"].outputSchemas);
113
- const defaults = getAiSdkToolMeta(contract);
114
- return tool({
115
- ...defaults,
116
- ...toolOptions,
117
- toModelOutput: toolOptions.toModelOutput ?? defaults?.toModelOutput ?? defaultToModelOutput,
118
- inputSchema: combineSchemas(inputSchemas, true) ?? ANY_SCHEMA,
119
- outputSchema: combineOutputSchemas(outputSchemas)
120
- });
121
- };
122
- return factory;
123
- }
124
-
125
- export function createToolFactory(...rest) {
126
- const options = resolveMaybeOptionalOptions(rest);
127
- const implementTool = implementToolFactory(options);
128
- const factory = (procedure, ...rest) => {
129
- const toolOptions = resolveMaybeOptionalOptions(rest);
130
-
131
- const disabledValidation = new Procedure({
132
- ...procedure["~orpc"],
133
- disableInputValidation: true
134
- });
135
-
136
- const isIteratorOutput = getAsyncIteratorObjectSchemasDetails(procedure["~orpc"].outputSchemas) !== undefined || isAsyncGeneratorFunction(procedure["~orpc"].handler);
137
- return implementTool(procedure, {
138
- ...toolOptions,
139
-
140
- execute: isIteratorOutput ? async function* (input, callingOptions) {
141
- yield* await call(disabledValidation, input, {
142
- ...options,
143
- signal: callingOptions.abortSignal
144
- });
145
- } : (input, callingOptions) => {
146
- return call(disabledValidation, input, {
147
- ...options,
148
- signal: callingOptions.abortSignal
149
- });
150
- }
151
- });
152
- };
153
- return factory;
154
- }