@orpc/ai-sdk 2.0.0-beta.47 → 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)
@@ -191,15 +192,14 @@ Like what we build over at [middleapi](https://github.com/middleapi)? You can he
191
192
  <td align="center"><a href="https://kellychan.im/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Kelly Peilin Chan"><img src="https://avatars.githubusercontent.com/u/520852?u=6b0f7105f694e7b5cacf410a3f04c7044b469dc8&amp;v=4" width="139" alt="Kelly Peilin Chan"/><br />Kelly Peilin Chan</a></td>
192
193
  <td align="center"><a href="https://guyariely.com/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Guy Ariely"><img src="https://avatars.githubusercontent.com/u/42813496?u=edb6b7f563bf28e160a290832e7da57c0506f8ca&amp;v=4" width="139" alt="Guy Ariely"/><br />Guy Ariely</a></td>
193
194
  <td align="center"><a href="https://paulsenon.com/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="PaulSenon"><img src="https://avatars.githubusercontent.com/u/19531087?u=6385741eb91d200b8c513ec6045482e301767ca6&amp;v=4" width="139" alt="PaulSenon"/><br />PaulSenon</a></td>
194
- <td align="center"><a href="https://nakasyou.how/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Shotaro Nakamura"><img src="https://avatars.githubusercontent.com/u/79000684?u=f644df3f29f0e8677a90967115774564f1d9d6ab&amp;v=4" width="139" alt="Shotaro Nakamura"/><br />Shotaro Nakamura</a></td>
195
+ <td align="center"><a href="https://piscis.dev/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Alex"><img src="https://avatars.githubusercontent.com/u/326163?u=b245f368bd940cf51d08c0b6bf55f8257f359437&amp;v=4" width="139" alt="Alex"/><br />Alex</a></td>
195
196
  </tr>
196
197
  <tr>
197
- <td align="center"><a href="https://piscis.dev/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Alex"><img src="https://avatars.githubusercontent.com/u/326163?u=b245f368bd940cf51d08c0b6bf55f8257f359437&amp;v=4" width="139" alt="Alex"/><br />Alex</a></td>
198
198
  <td align="center"><a href="https://opensource.gubanov.eu/?ref=middleapi&amp;utm_source=middleapi&amp;utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Andrey Gubanov"><img src="https://avatars.githubusercontent.com/u/1082083?u=c5f2daf7ebece498e85c83367bb37b4e10e2649d&amp;v=4" width="139" alt="Andrey Gubanov"/><br />Andrey Gubanov</a></td>
199
199
  </tr>
200
200
  </table>
201
201
 
202
- With thanks to [39 past sponsors](https://orpc.dev/sponsors#past-sponsors) who helped get oRPC here.
202
+ With thanks to [40 past sponsors](https://orpc.dev/sponsors#past-sponsors) who helped get oRPC here.
203
203
 
204
204
  ## Open Source Programs
205
205
 
@@ -209,7 +209,6 @@ With thanks to [39 past sponsors](https://orpc.dev/sponsors#past-sponsors) who h
209
209
  <tr>
210
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>
211
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>
212
- <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>
213
212
  </tr>
214
213
  </table>
215
214
 
package/dist/index.d.ts CHANGED
@@ -1,172 +1,2 @@
1
- import { ClientOptions } from '@orpc/client';
2
- import { AnySchema, ErrorMap, InferSchemaOutput, InferSchemaInput, MetaPlugin, AnyProcedureContract, Schema, ProcedureContract } from '@orpc/contract';
3
- import { Lazy, Context, ProcedureClientOptions, Procedure } from '@orpc/server';
4
- import { Public, MaybeOptionalOptions } from '@orpc/shared';
5
- import { JSONValue, Tool } from 'ai';
6
- import { OpenAPIJsonSerializer } from '@orpc/openapi';
7
-
8
- /**
9
- * The [function tool](https://ai-sdk.dev/docs/foundations/tools) member of the AI SDK `Tool` union,
10
- * which is the kind of tool this package produces.
11
- */
12
- type FunctionTool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any> = 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
- type AiSdkToolMeta<TInputSchema extends AnySchema = AnySchema, TOutputSchema extends AnySchema = AnySchema> = Partial<Omit<FunctionTool<InferSchemaOutput<TInputSchema>, ToolOutput<InferSchemaInput<TOutputSchema>>>, 'inputSchema' | 'outputSchema' | 'execute'>>;
25
- interface AiSdkToolMetaPlugin<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> extends MetaPlugin<TInputSchema, TOutputSchema, TErrorMap> {
26
- name: '~ai-sdk/tool';
27
- }
28
- interface AiSdkToolFunction {
29
- <TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap>(meta: AiSdkToolMeta<TInputSchema, TOutputSchema>): AiSdkToolMetaPlugin<TInputSchema, TOutputSchema, TErrorMap>;
30
- }
31
- /**
32
- * Attaches base [AI SDK Tool](https://ai-sdk.dev/docs/foundations/tools) options to a procedure/contract,
33
- * used as defaults when creating tools from it.
34
- *
35
- * @remarks
36
- * **Note**: When defined multiple times, options are overridden by the most recent call.
37
- *
38
- * @example
39
- * ```ts
40
- * const getWeatherContract = oc
41
- * .meta(aiSdkTool({
42
- * description: 'Get the weather in a location',
43
- * metadata: { source: 'weather-service' },
44
- * }))
45
- * .input(z.object({ location: z.string() }))
46
- * ```
47
- *
48
- * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-implementer | AI SDK Integration - Tool Implementer}
49
- */
50
- declare const aiSdkTool: AiSdkToolFunction;
51
- /**
52
- * Reads the base [AI SDK Tool](https://ai-sdk.dev/docs/foundations/tools) options
53
- * attached to a procedure/contract by {@link aiSdkTool}.
54
- *
55
- * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-implementer | AI SDK Integration - Tool Implementer}
56
- */
57
- declare function getAiSdkToolMeta(procedureOrLazy: AnyProcedureContract | Lazy<any>): AiSdkToolMeta | undefined;
58
-
59
- /**
60
- * Infers the value an AI SDK tool outputs for a given oRPC output type.
61
- *
62
- * For [AsyncIteratorObject](https://orpc.dev/docs/async-iterator-object) outputs, the tool streams
63
- * each yielded event as a [preliminary result](https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling#preliminary-tool-results)
64
- * and the last event becomes the final result, so the tool output is the yield type.
65
- *
66
- * @see {@link https://orpc.dev/docs/integrations/ai-sdk#streaming-tool-outputs | AI SDK Integration - Streaming Tool Outputs}
67
- */
68
- type ToolOutput<T> = T extends AsyncIteratorObject<infer TYield, any, any> ? TYield : T;
69
- interface ImplementToolFactoryOptions {
70
- /**
71
- * Serializes outputs for the default `toModelOutput`, converting types such as `Date`, `BigInt`, and `Set`
72
- * the same way OpenAPI responses do.
73
- *
74
- * @default new OpenAPIJsonSerializer()
75
- * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-outputs | AI SDK Integration - Tool Outputs}
76
- */
77
- serializer?: Public<OpenAPIJsonSerializer> | undefined;
78
- }
79
- interface ToolImplementer {
80
- <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>>>;
81
- }
82
- /**
83
- * Creates a builder that implements [procedure contracts](https://orpc.dev/docs/contract/procedure)
84
- * as [AI SDK Tools](https://ai-sdk.dev/docs/foundations/tools) by leveraging existing contract definitions.
85
- *
86
- * The factory accepts oRPC related options, and the resulting builder
87
- * accepts a contract alongside AI SDK tool options.
88
- *
89
- * @remarks
90
- * **Note**: [Procedures](https://orpc.dev/docs/procedure) are also compatible with [procedure contracts](https://orpc.dev/docs/contract/procedure).
91
- *
92
- * @example
93
- * ```ts
94
- * import { aiSdkTool, implementToolFactory } from '@orpc/ai-sdk'
95
- * import { oc } from '@orpc/contract'
96
- *
97
- * const getWeatherContract = oc
98
- * .meta(
99
- * aiSdkTool({ description: 'Get the weather in a location' }), // default AI SDK tool options
100
- * )
101
- * .input(
102
- * z.object({
103
- * location: z.string().describe('The location to get the weather for'),
104
- * }),
105
- * )
106
- * .output(
107
- * z.object({
108
- * location: z.string().describe('The location the weather is for'),
109
- * temperature: z.number().describe('The temperature in Celsius'),
110
- * }),
111
- * )
112
- *
113
- * const implementTool = implementToolFactory()
114
- *
115
- * const getWeatherTool = implementTool(getWeatherContract, {
116
- * execute: async ({ location }) => ({
117
- * location,
118
- * temperature: 72 + Math.floor(Math.random() * 21) - 10,
119
- * }),
120
- * })
121
- * ```
122
- *
123
- * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-implementer | AI SDK Integration - Tool Implementer}
124
- */
125
- declare function implementToolFactory(options?: ImplementToolFactoryOptions): ToolImplementer;
126
- type CreateToolFactoryOptions<TInitialContext extends Context> = ImplementToolFactoryOptions & ProcedureClientOptions<TInitialContext, Schema<unknown>, object, object> & Omit<ClientOptions<object>, 'context' | 'signal'>;
127
- interface ToolFactory<TInitialContext extends Context> {
128
- <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>>>;
129
- }
130
- /**
131
- * Creates a builder that converts [procedures](https://orpc.dev/docs/procedure)
132
- * into [AI SDK Tools](https://ai-sdk.dev/docs/foundations/tools) by leveraging existing procedure definitions.
133
- *
134
- * The factory accepts oRPC related options, and the resulting builder
135
- * accepts a procedure alongside AI SDK tool options.
136
- *
137
- * @example
138
- * ```ts
139
- * import { aiSdkTool, createToolFactory } from '@orpc/ai-sdk'
140
- * import { os } from '@orpc/server'
141
- *
142
- * const getWeatherProcedure = os
143
- * .meta(
144
- * aiSdkTool({ description: 'Get the weather in a location' }), // default AI SDK tool options
145
- * )
146
- * .input(z.object({
147
- * location: z.string().describe('The location to get the weather for'),
148
- * }))
149
- * .output(z.object({
150
- * location: z.string().describe('The location the weather is for'),
151
- * temperature: z.number().describe('The temperature in Celsius'),
152
- * }))
153
- * .handler(async ({ input }) => ({
154
- * location: input.location,
155
- * temperature: 72 + Math.floor(Math.random() * 21) - 10,
156
- * }))
157
- *
158
- * const createTool = createToolFactory({
159
- * context: {}, // provide initial context if needed
160
- * })
161
- *
162
- * const getWeatherTool = createTool(getWeatherProcedure, {
163
- * // ...AI SDK tool options/overrides here if needed
164
- * })
165
- * ```
166
- *
167
- * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-factory | AI SDK Integration - Tool Factory}
168
- */
169
- declare function createToolFactory<TInitialContext extends Context = object>(...rest: MaybeOptionalOptions<CreateToolFactoryOptions<TInitialContext>>): ToolFactory<TInitialContext>;
170
-
171
- export { aiSdkTool, createToolFactory, getAiSdkToolMeta, implementToolFactory };
172
- export type { AiSdkToolFunction, AiSdkToolMeta, AiSdkToolMetaPlugin, CreateToolFactoryOptions, FunctionTool, ImplementToolFactoryOptions, ToolFactory, ToolImplementer, ToolOutput };
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
+ }
@@ -1,61 +1,11 @@
1
- import { ClientOptions } from '@orpc/client';
2
- import { AnySchema, ErrorMap, InferSchemaOutput, InferSchemaInput, MetaPlugin, AnyProcedureContract, Schema, ProcedureContract } from '@orpc/contract';
3
- import { Lazy, Context, ProcedureClientOptions, Procedure } from '@orpc/server';
4
- import { Public, MaybeOptionalOptions } from '@orpc/shared';
5
- import { JSONValue, Tool } from 'ai';
1
+ import type { ClientOptions } from '@orpc/client';
2
+ import type { AnySchema, InferSchemaInput, InferSchemaOutput, ProcedureContract, Schema } from '@orpc/contract';
6
3
  import { OpenAPIJsonSerializer } from '@orpc/openapi';
7
-
8
- /**
9
- * The [function tool](https://ai-sdk.dev/docs/foundations/tools) member of the AI SDK `Tool` union,
10
- * which is the kind of tool this package produces.
11
- */
12
- type FunctionTool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any> = 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
- type AiSdkToolMeta<TInputSchema extends AnySchema = AnySchema, TOutputSchema extends AnySchema = AnySchema> = Partial<Omit<FunctionTool<InferSchemaOutput<TInputSchema>, ToolOutput<InferSchemaInput<TOutputSchema>>>, 'inputSchema' | 'outputSchema' | 'execute'>>;
25
- interface AiSdkToolMetaPlugin<TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap> extends MetaPlugin<TInputSchema, TOutputSchema, TErrorMap> {
26
- name: '~ai-sdk/tool';
27
- }
28
- interface AiSdkToolFunction {
29
- <TInputSchema extends AnySchema, TOutputSchema extends AnySchema, TErrorMap extends ErrorMap>(meta: AiSdkToolMeta<TInputSchema, TOutputSchema>): AiSdkToolMetaPlugin<TInputSchema, TOutputSchema, TErrorMap>;
30
- }
31
- /**
32
- * Attaches base [AI SDK Tool](https://ai-sdk.dev/docs/foundations/tools) options to a procedure/contract,
33
- * used as defaults when creating tools from it.
34
- *
35
- * @remarks
36
- * **Note**: When defined multiple times, options are overridden by the most recent call.
37
- *
38
- * @example
39
- * ```ts
40
- * const getWeatherContract = oc
41
- * .meta(aiSdkTool({
42
- * description: 'Get the weather in a location',
43
- * metadata: { source: 'weather-service' },
44
- * }))
45
- * .input(z.object({ location: z.string() }))
46
- * ```
47
- *
48
- * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-implementer | AI SDK Integration - Tool Implementer}
49
- */
50
- declare const aiSdkTool: AiSdkToolFunction;
51
- /**
52
- * Reads the base [AI SDK Tool](https://ai-sdk.dev/docs/foundations/tools) options
53
- * attached to a procedure/contract by {@link aiSdkTool}.
54
- *
55
- * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-implementer | AI SDK Integration - Tool Implementer}
56
- */
57
- declare function getAiSdkToolMeta(procedureOrLazy: AnyProcedureContract | Lazy<any>): AiSdkToolMeta | undefined;
58
-
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';
59
9
  /**
60
10
  * Infers the value an AI SDK tool outputs for a given oRPC output type.
61
11
  *
@@ -65,8 +15,8 @@ declare function getAiSdkToolMeta(procedureOrLazy: AnyProcedureContract | Lazy<a
65
15
  *
66
16
  * @see {@link https://orpc.dev/docs/integrations/ai-sdk#streaming-tool-outputs | AI SDK Integration - Streaming Tool Outputs}
67
17
  */
68
- type ToolOutput<T> = T extends AsyncIteratorObject<infer TYield, any, any> ? TYield : T;
69
- interface ImplementToolFactoryOptions {
18
+ export type ToolOutput<T> = T extends AsyncIteratorObject<infer TYield, any, any> ? TYield : T;
19
+ export interface ImplementToolFactoryOptions {
70
20
  /**
71
21
  * Serializes outputs for the default `toModelOutput`, converting types such as `Date`, `BigInt`, and `Set`
72
22
  * the same way OpenAPI responses do.
@@ -76,7 +26,7 @@ interface ImplementToolFactoryOptions {
76
26
  */
77
27
  serializer?: Public<OpenAPIJsonSerializer> | undefined;
78
28
  }
79
- interface ToolImplementer {
29
+ export interface ToolImplementer {
80
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>>>;
81
31
  }
82
32
  /**
@@ -122,9 +72,9 @@ interface ToolImplementer {
122
72
  *
123
73
  * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-implementer | AI SDK Integration - Tool Implementer}
124
74
  */
125
- declare function implementToolFactory(options?: ImplementToolFactoryOptions): ToolImplementer;
126
- type CreateToolFactoryOptions<TInitialContext extends Context> = ImplementToolFactoryOptions & ProcedureClientOptions<TInitialContext, Schema<unknown>, object, object> & Omit<ClientOptions<object>, 'context' | 'signal'>;
127
- interface ToolFactory<TInitialContext extends Context> {
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> {
128
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>>>;
129
79
  }
130
80
  /**
@@ -166,7 +116,4 @@ interface ToolFactory<TInitialContext extends Context> {
166
116
  *
167
117
  * @see {@link https://orpc.dev/docs/integrations/ai-sdk#tool-factory | AI SDK Integration - Tool Factory}
168
118
  */
169
- declare function createToolFactory<TInitialContext extends Context = object>(...rest: MaybeOptionalOptions<CreateToolFactoryOptions<TInitialContext>>): ToolFactory<TInitialContext>;
170
-
171
- export { aiSdkTool, createToolFactory, getAiSdkToolMeta, implementToolFactory };
172
- export type { AiSdkToolFunction, AiSdkToolMeta, AiSdkToolMetaPlugin, CreateToolFactoryOptions, FunctionTool, ImplementToolFactoryOptions, ToolFactory, ToolImplementer, ToolOutput };
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.47",
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.47",
44
- "@orpc/contract": "2.0.0-beta.47",
45
- "@orpc/json-schema": "2.0.0-beta.47",
46
- "@orpc/openapi": "2.0.0-beta.47",
47
- "@orpc/server": "2.0.0-beta.47",
48
- "@orpc/shared": "2.0.0-beta.47"
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.141",
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.mjs DELETED
@@ -1,148 +0,0 @@
1
- import { getAsyncIteratorObjectSchemasDetails } from '@orpc/contract';
2
- import { combineJsonSchemasWithComposition } from '@orpc/json-schema';
3
- import { OpenAPIJsonSerializer } from '@orpc/openapi';
4
- import { Procedure, call } from '@orpc/server';
5
- import { resolveMaybeOptionalOptions, isAsyncGeneratorFunction, toArray, ORPC_NAME, mergeTwoLevels, encodeBase64, loadBytes, stringifyJSON } from '@orpc/shared';
6
- import { tool } from 'ai';
7
-
8
- const aiSdkTool = (incoming) => ({
9
- name: "~ai-sdk/tool",
10
- init(meta) {
11
- const existing = meta["~ai-sdk/tool"];
12
- return {
13
- ...meta,
14
- "~ai-sdk/tool": { ...existing, ...incoming }
15
- };
16
- }
17
- });
18
- function getAiSdkToolMeta(procedureOrLazy) {
19
- return procedureOrLazy["~orpc"].meta["~ai-sdk/tool"];
20
- }
21
-
22
- const ANY_SCHEMA = {
23
- "~standard": {
24
- vendor: ORPC_NAME,
25
- version: 1,
26
- validate: (value) => ({ value }),
27
- jsonSchema: {
28
- input: () => ({}),
29
- output: () => ({})
30
- }
31
- }
32
- };
33
- function combineJsonSchemas(jsonSchemas) {
34
- let $schema;
35
- const branches = jsonSchemas.map((jsonSchema) => {
36
- if ("$schema" in jsonSchema) {
37
- const { $schema: branch$schema, ...rest } = jsonSchema;
38
- $schema ??= branch$schema;
39
- return rest;
40
- }
41
- return jsonSchema;
42
- });
43
- const combined = combineJsonSchemasWithComposition("allOf", branches);
44
- return { $schema, ...combined };
45
- }
46
- function combineSchemas(schemas, merge) {
47
- if (schemas.length === 0) {
48
- return void 0;
49
- }
50
- if (schemas.length === 1) {
51
- return schemas[0];
52
- }
53
- const standardJsonSchemas = schemas.filter((schema) => schema["~standard"].jsonSchema);
54
- const jsonSchema = standardJsonSchemas.length ? {
55
- input: (options) => combineJsonSchemas(standardJsonSchemas.map((schema) => schema["~standard"].jsonSchema.input(options))),
56
- output: (options) => combineJsonSchemas(standardJsonSchemas.map((schema) => schema["~standard"].jsonSchema.output(options)))
57
- } : void 0;
58
- return {
59
- "~standard": {
60
- vendor: ORPC_NAME,
61
- version: 1,
62
- async validate(value) {
63
- let current = value;
64
- for (const [index, schema] of schemas.entries()) {
65
- const merging = merge && index !== 0;
66
- const result = await schema["~standard"].validate(merging ? mergeTwoLevels(value, current) : current);
67
- if (result.issues) {
68
- return result;
69
- }
70
- current = merging ? mergeTwoLevels(current, result.value) : result.value;
71
- }
72
- return { value: current };
73
- },
74
- jsonSchema
75
- }
76
- };
77
- }
78
- function combineOutputSchemas(outputSchemas) {
79
- const yieldSchemas = getAsyncIteratorObjectSchemasDetails(outputSchemas)?.yieldSchemas;
80
- return combineSchemas([...yieldSchemas ?? outputSchemas].reverse(), false);
81
- }
82
- async function toModelOutput(serializer, output) {
83
- const { json, maps, blobs } = serializer.serializeJson(output);
84
- if (typeof json === "string") {
85
- return { type: "text", value: json };
86
- }
87
- if (!blobs?.length) {
88
- return { type: "json", value: json ?? null };
89
- }
90
- const files = await Promise.all(blobs.map(async (blob, i) => {
91
- const path = maps[i];
92
- const names = blob instanceof File && blob.name !== "" ? [...path, blob.name] : path;
93
- return {
94
- type: "file",
95
- mediaType: blob.type || "application/octet-stream",
96
- // base64 is encoded once, providers would otherwise re-encode the bytes on every step
97
- data: { type: "data", data: encodeBase64(await loadBytes(blob)) },
98
- ...names.length === 0 ? {} : { filename: names.join("/") }
99
- };
100
- }));
101
- return { type: "content", value: json instanceof Blob ? files : [{ type: "text", text: stringifyJSON(json) }, ...files] };
102
- }
103
- function implementToolFactory(options = {}) {
104
- const serializer = options.serializer ?? new OpenAPIJsonSerializer();
105
- const defaultToModelOutput = ({ output }) => toModelOutput(serializer, output);
106
- const factory = (contract, ...rest) => {
107
- const toolOptions = resolveMaybeOptionalOptions(rest);
108
- const inputSchemas = toArray(contract["~orpc"].inputSchemas);
109
- const outputSchemas = toArray(contract["~orpc"].outputSchemas);
110
- const defaults = getAiSdkToolMeta(contract);
111
- return tool({
112
- ...defaults,
113
- ...toolOptions,
114
- toModelOutput: toolOptions.toModelOutput ?? defaults?.toModelOutput ?? defaultToModelOutput,
115
- inputSchema: combineSchemas(inputSchemas, true) ?? ANY_SCHEMA,
116
- outputSchema: combineOutputSchemas(outputSchemas)
117
- });
118
- };
119
- return factory;
120
- }
121
- function createToolFactory(...rest) {
122
- const options = resolveMaybeOptionalOptions(rest);
123
- const implementTool = implementToolFactory(options);
124
- const factory = (procedure, ...rest2) => {
125
- const toolOptions = resolveMaybeOptionalOptions(rest2);
126
- const disabledValidation = new Procedure({
127
- ...procedure["~orpc"],
128
- disableInputValidation: true
129
- });
130
- const isIteratorOutput = getAsyncIteratorObjectSchemasDetails(procedure["~orpc"].outputSchemas) !== void 0 || isAsyncGeneratorFunction(procedure["~orpc"].handler);
131
- return implementTool(procedure, {
132
- ...toolOptions,
133
- /**
134
- * For async iterator outputs, the tool streams each event as a
135
- * [preliminary result](https://ai-sdk.dev/docs/ai-sdk-core/tools-and-tool-calling#preliminary-tool-results),
136
- * and the last event becomes the final result.
137
- */
138
- execute: isIteratorOutput ? async function* (input, callingOptions) {
139
- yield* await call(disabledValidation, input, { ...options, signal: callingOptions.abortSignal });
140
- } : (input, callingOptions) => {
141
- return call(disabledValidation, input, { ...options, signal: callingOptions.abortSignal });
142
- }
143
- });
144
- };
145
- return factory;
146
- }
147
-
148
- export { aiSdkTool, createToolFactory, getAiSdkToolMeta, implementToolFactory };