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