@tinyweb_dev/agent-framework-llm 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +59 -0
- package/package.json +48 -0
- package/src/cache-policy.ts +92 -0
- package/src/index.ts +62 -0
- package/src/llm.ts +210 -0
- package/src/protocols/openai-chat.ts +422 -0
- package/src/protocols/openai-compatible-chat.ts +29 -0
- package/src/protocols/shared.ts +204 -0
- package/src/protocols/utils/openai-options.ts +56 -0
- package/src/protocols/utils/tool-stream.ts +135 -0
- package/src/provider.ts +32 -0
- package/src/providers/openai-compatible-profile.ts +24 -0
- package/src/providers/openai-compatible.ts +69 -0
- package/src/providers/openai-options.ts +71 -0
- package/src/providers/openai.ts +39 -0
- package/src/route/auth-options.ts +48 -0
- package/src/route/auth.ts +198 -0
- package/src/route/client.ts +459 -0
- package/src/route/endpoint.ts +28 -0
- package/src/route/executor.ts +396 -0
- package/src/route/framing.ts +13 -0
- package/src/route/overflow-detect.ts +74 -0
- package/src/route/protocol.ts +48 -0
- package/src/route/transport/http.ts +123 -0
- package/src/route/transport/index.ts +21 -0
- package/src/schema/errors.ts +225 -0
- package/src/schema/events.ts +333 -0
- package/src/schema/ids.ts +44 -0
- package/src/schema/index.ts +6 -0
- package/src/schema/messages.ts +240 -0
- package/src/schema/options.ts +231 -0
- package/src/tool-runtime.ts +263 -0
- package/src/tool.ts +212 -0
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
// Adapted from opencode@v1.14.48 packages/llm/src/tool-runtime.ts
|
|
2
|
+
import { Effect, Stream } from "effect"
|
|
3
|
+
import type { Concurrency } from "effect/Types"
|
|
4
|
+
import {
|
|
5
|
+
type ContentPart,
|
|
6
|
+
type FinishReason,
|
|
7
|
+
type LLMError,
|
|
8
|
+
LLMEvent,
|
|
9
|
+
LLMRequest,
|
|
10
|
+
Message,
|
|
11
|
+
type ProviderMetadata,
|
|
12
|
+
ToolCallPart,
|
|
13
|
+
ToolFailure,
|
|
14
|
+
ToolResultPart,
|
|
15
|
+
type ToolResultValue,
|
|
16
|
+
} from "./schema"
|
|
17
|
+
import { type AnyTool, type ExecutableTools, type Tools, toDefinitions } from "./tool"
|
|
18
|
+
|
|
19
|
+
export interface RuntimeState {
|
|
20
|
+
readonly step: number
|
|
21
|
+
readonly request: LLMRequest
|
|
22
|
+
/** Tool calls emitted by the model in the step that just finished (before dispatch follow-up). */
|
|
23
|
+
readonly toolCalls: ReadonlyArray<ToolCallPart>
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export type StopCondition = (state: RuntimeState) => boolean
|
|
27
|
+
|
|
28
|
+
/** Stop the loop once the model emits a tool call with the given name. */
|
|
29
|
+
export const hasToolCall =
|
|
30
|
+
(name: string): StopCondition =>
|
|
31
|
+
(state) =>
|
|
32
|
+
state.toolCalls.some((call) => call.name === name)
|
|
33
|
+
|
|
34
|
+
/** Combine multiple stop conditions with OR semantics. */
|
|
35
|
+
export const stopWhenAny =
|
|
36
|
+
(...conditions: ReadonlyArray<StopCondition>): StopCondition =>
|
|
37
|
+
(state) =>
|
|
38
|
+
conditions.some((condition) => condition(state))
|
|
39
|
+
|
|
40
|
+
export type ToolExecution = "auto" | "none"
|
|
41
|
+
|
|
42
|
+
interface RunOptionsBase {
|
|
43
|
+
readonly request: LLMRequest
|
|
44
|
+
readonly concurrency?: Concurrency
|
|
45
|
+
readonly stopWhen?: StopCondition
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export type RunOptions<T extends Tools> = RunOptionsAuto<T & ExecutableTools> | RunOptionsNone<T>
|
|
49
|
+
|
|
50
|
+
export interface RunOptionsAuto<T extends ExecutableTools> extends RunOptionsBase {
|
|
51
|
+
readonly request: LLMRequest
|
|
52
|
+
readonly tools: T
|
|
53
|
+
readonly toolExecution?: "auto"
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface RunOptionsNone<T extends Tools> extends RunOptionsBase {
|
|
57
|
+
readonly request: LLMRequest
|
|
58
|
+
readonly tools: T
|
|
59
|
+
/** Advertise tool schemas but leave model-emitted tool calls for the caller. */
|
|
60
|
+
readonly toolExecution: "none"
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export type StreamOptions<T extends Tools> = RunOptions<T> & {
|
|
64
|
+
readonly stream: (request: LLMRequest) => Stream.Stream<LLMEvent, LLMError>
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export const stepCountIs =
|
|
68
|
+
(count: number): StopCondition =>
|
|
69
|
+
(state) =>
|
|
70
|
+
state.step + 1 >= count
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Run a model with typed tools. This helper owns tool orchestration, while the
|
|
74
|
+
* caller supplies the actual model stream function. It can advertise schemas
|
|
75
|
+
* only (`toolExecution: "none"`), execute one step, or continue model rounds
|
|
76
|
+
* when `stopWhen` is provided.
|
|
77
|
+
*/
|
|
78
|
+
export const stream = <T extends Tools>(options: StreamOptions<T>): Stream.Stream<LLMEvent, LLMError> => {
|
|
79
|
+
const concurrency = options.concurrency ?? 10
|
|
80
|
+
const tools = options.tools as Tools
|
|
81
|
+
const runtimeTools = toDefinitions(tools)
|
|
82
|
+
const runtimeToolNames = new Set(runtimeTools.map((tool) => tool.name))
|
|
83
|
+
const initialRequest =
|
|
84
|
+
runtimeTools.length === 0
|
|
85
|
+
? options.request
|
|
86
|
+
: LLMRequest.update(options.request, {
|
|
87
|
+
tools: [...options.request.tools.filter((tool) => !runtimeToolNames.has(tool.name)), ...runtimeTools],
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
const loop = (request: LLMRequest, step: number): Stream.Stream<LLMEvent, LLMError> =>
|
|
91
|
+
Stream.unwrap(
|
|
92
|
+
Effect.gen(function* () {
|
|
93
|
+
const state: StepState = { assistantContent: [], toolCalls: [], finishReason: undefined }
|
|
94
|
+
|
|
95
|
+
const modelStream = options
|
|
96
|
+
.stream(request)
|
|
97
|
+
.pipe(Stream.tap((event) => Effect.sync(() => accumulate(state, event))))
|
|
98
|
+
|
|
99
|
+
const continuation = Stream.unwrap(
|
|
100
|
+
Effect.gen(function* () {
|
|
101
|
+
if (state.finishReason !== "tool-calls" || state.toolCalls.length === 0) return Stream.empty
|
|
102
|
+
if (options.toolExecution === "none") return Stream.empty
|
|
103
|
+
|
|
104
|
+
const dispatched = yield* Effect.forEach(
|
|
105
|
+
state.toolCalls,
|
|
106
|
+
(call) => dispatch(tools, call).pipe(Effect.map((result) => [call, result] as const)),
|
|
107
|
+
{ concurrency },
|
|
108
|
+
)
|
|
109
|
+
const resultStream = Stream.fromIterable(dispatched.flatMap(([call, result]) => emitEvents(call, result)))
|
|
110
|
+
|
|
111
|
+
if (!options.stopWhen) return resultStream
|
|
112
|
+
if (options.stopWhen({ step, request, toolCalls: state.toolCalls })) return resultStream
|
|
113
|
+
|
|
114
|
+
return resultStream.pipe(Stream.concat(loop(followUpRequest(request, state, dispatched), step + 1)))
|
|
115
|
+
}),
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
return modelStream.pipe(Stream.concat(continuation))
|
|
119
|
+
}),
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
return loop(initialRequest, 0)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
interface StepState {
|
|
126
|
+
assistantContent: ContentPart[]
|
|
127
|
+
toolCalls: ToolCallPart[]
|
|
128
|
+
finishReason: FinishReason | undefined
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const accumulate = (state: StepState, event: LLMEvent) => {
|
|
132
|
+
if (event.type === "text-delta") {
|
|
133
|
+
appendStreamingText(state, "text", event.text, undefined)
|
|
134
|
+
return
|
|
135
|
+
}
|
|
136
|
+
if (event.type === "reasoning-delta") {
|
|
137
|
+
appendStreamingText(state, "reasoning", event.text, undefined)
|
|
138
|
+
return
|
|
139
|
+
}
|
|
140
|
+
if (event.type === "reasoning-end") {
|
|
141
|
+
appendStreamingText(state, "reasoning", "", event.providerMetadata)
|
|
142
|
+
return
|
|
143
|
+
}
|
|
144
|
+
if (event.type === "text-end") {
|
|
145
|
+
appendStreamingText(state, "text", "", event.providerMetadata)
|
|
146
|
+
return
|
|
147
|
+
}
|
|
148
|
+
if (event.type === "tool-call") {
|
|
149
|
+
const part = ToolCallPart.make({
|
|
150
|
+
id: event.id,
|
|
151
|
+
name: event.name,
|
|
152
|
+
input: event.input,
|
|
153
|
+
providerExecuted: event.providerExecuted,
|
|
154
|
+
providerMetadata: event.providerMetadata,
|
|
155
|
+
})
|
|
156
|
+
state.assistantContent.push(part)
|
|
157
|
+
if (!event.providerExecuted) state.toolCalls.push(part)
|
|
158
|
+
return
|
|
159
|
+
}
|
|
160
|
+
if (event.type === "tool-result" && event.providerExecuted) {
|
|
161
|
+
state.assistantContent.push(
|
|
162
|
+
ToolResultPart.make({
|
|
163
|
+
id: event.id,
|
|
164
|
+
name: event.name,
|
|
165
|
+
result: event.result,
|
|
166
|
+
providerExecuted: true,
|
|
167
|
+
providerMetadata: event.providerMetadata,
|
|
168
|
+
}),
|
|
169
|
+
)
|
|
170
|
+
return
|
|
171
|
+
}
|
|
172
|
+
if (event.type === "request-finish") {
|
|
173
|
+
state.finishReason = event.reason
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const sameProviderMetadata = (left: ProviderMetadata | undefined, right: ProviderMetadata | undefined) =>
|
|
178
|
+
left === right || JSON.stringify(left) === JSON.stringify(right)
|
|
179
|
+
|
|
180
|
+
const mergeProviderMetadata = (left: ProviderMetadata | undefined, right: ProviderMetadata | undefined) => {
|
|
181
|
+
if (!left) return right
|
|
182
|
+
if (!right) return left
|
|
183
|
+
return Object.fromEntries(
|
|
184
|
+
Array.from(new Set([...Object.keys(left), ...Object.keys(right)])).map((provider) => [
|
|
185
|
+
provider,
|
|
186
|
+
{ ...left[provider], ...right[provider] },
|
|
187
|
+
]),
|
|
188
|
+
)
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const appendStreamingText = (
|
|
192
|
+
state: StepState,
|
|
193
|
+
type: "text" | "reasoning",
|
|
194
|
+
text: string,
|
|
195
|
+
providerMetadata: ProviderMetadata | undefined,
|
|
196
|
+
) => {
|
|
197
|
+
const last = state.assistantContent.at(-1)
|
|
198
|
+
if (last?.type === type && text.length === 0) {
|
|
199
|
+
state.assistantContent[state.assistantContent.length - 1] = {
|
|
200
|
+
...last,
|
|
201
|
+
providerMetadata: mergeProviderMetadata(last.providerMetadata, providerMetadata),
|
|
202
|
+
}
|
|
203
|
+
return
|
|
204
|
+
}
|
|
205
|
+
if (last?.type === type && sameProviderMetadata(last.providerMetadata, providerMetadata)) {
|
|
206
|
+
state.assistantContent[state.assistantContent.length - 1] = { ...last, text: `${last.text}${text}` }
|
|
207
|
+
return
|
|
208
|
+
}
|
|
209
|
+
state.assistantContent.push({ type, text, providerMetadata })
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const dispatch = (tools: Tools, call: ToolCallPart): Effect.Effect<ToolResultValue> => {
|
|
213
|
+
const tool = tools[call.name]
|
|
214
|
+
if (!tool) return Effect.succeed({ type: "error" as const, value: `Unknown tool: ${call.name}` })
|
|
215
|
+
if (!tool.execute)
|
|
216
|
+
return Effect.succeed({ type: "error" as const, value: `Tool has no execute handler: ${call.name}` })
|
|
217
|
+
|
|
218
|
+
return decodeAndExecute(tool, call.input).pipe(
|
|
219
|
+
Effect.catchTag("LLM.ToolFailure", (failure) =>
|
|
220
|
+
Effect.succeed({ type: "error" as const, value: failure.message } satisfies ToolResultValue),
|
|
221
|
+
),
|
|
222
|
+
)
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const decodeAndExecute = (tool: AnyTool, input: unknown): Effect.Effect<ToolResultValue, ToolFailure> =>
|
|
226
|
+
tool._decode(input).pipe(
|
|
227
|
+
Effect.mapError((error) => new ToolFailure({ message: `Invalid tool input: ${error.message}` })),
|
|
228
|
+
Effect.flatMap((decoded) => tool.execute!(decoded)),
|
|
229
|
+
Effect.flatMap((value) =>
|
|
230
|
+
tool._encode(value).pipe(
|
|
231
|
+
Effect.mapError(
|
|
232
|
+
(error) =>
|
|
233
|
+
new ToolFailure({
|
|
234
|
+
message: `Tool returned an invalid value for its success schema: ${error.message}`,
|
|
235
|
+
}),
|
|
236
|
+
),
|
|
237
|
+
),
|
|
238
|
+
),
|
|
239
|
+
Effect.map((encoded): ToolResultValue => ({ type: "json", value: encoded })),
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
const emitEvents = (call: ToolCallPart, result: ToolResultValue): ReadonlyArray<LLMEvent> =>
|
|
243
|
+
result.type === "error"
|
|
244
|
+
? [
|
|
245
|
+
LLMEvent.toolError({ id: call.id, name: call.name, message: String(result.value) }),
|
|
246
|
+
LLMEvent.toolResult({ id: call.id, name: call.name, result }),
|
|
247
|
+
]
|
|
248
|
+
: [LLMEvent.toolResult({ id: call.id, name: call.name, result })]
|
|
249
|
+
|
|
250
|
+
const followUpRequest = (
|
|
251
|
+
request: LLMRequest,
|
|
252
|
+
state: StepState,
|
|
253
|
+
dispatched: ReadonlyArray<readonly [ToolCallPart, ToolResultValue]>,
|
|
254
|
+
) =>
|
|
255
|
+
LLMRequest.update(request, {
|
|
256
|
+
messages: [
|
|
257
|
+
...request.messages,
|
|
258
|
+
Message.assistant(state.assistantContent),
|
|
259
|
+
...dispatched.map(([call, result]) => Message.tool({ id: call.id, name: call.name, result })),
|
|
260
|
+
],
|
|
261
|
+
})
|
|
262
|
+
|
|
263
|
+
export const ToolRuntime = { stream, stepCountIs } as const
|
package/src/tool.ts
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
// Adapted from opencode@v1.14.48 packages/llm/src/tool.ts
|
|
2
|
+
import { Effect, JsonSchema, Schema } from "effect"
|
|
3
|
+
import type { ToolDefinition as ToolDefinitionClass } from "./schema"
|
|
4
|
+
import { ToolDefinition, ToolFailure } from "./schema"
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Schema constraint for tool parameters / success values: no decoding or
|
|
8
|
+
* encoding services are allowed. Tools should be self-contained — anything
|
|
9
|
+
* beyond pure data conversion belongs in the handler closure.
|
|
10
|
+
*/
|
|
11
|
+
export type ToolSchema<T> = Schema.Codec<T, any, never, never>
|
|
12
|
+
|
|
13
|
+
export type ToolExecute<Parameters extends ToolSchema<any>, Success extends ToolSchema<any>> = (
|
|
14
|
+
params: Schema.Schema.Type<Parameters>,
|
|
15
|
+
) => Effect.Effect<Schema.Schema.Type<Success>, ToolFailure>
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* A type-safe LLM tool. Each tool bundles its own description, parameter
|
|
19
|
+
* Schema and success Schema. The execute handler is optional: omit it when you
|
|
20
|
+
* only want to expose a tool schema to the model and handle tool calls outside
|
|
21
|
+
* this package.
|
|
22
|
+
*
|
|
23
|
+
* Errors must be expressed as `ToolFailure`. Unmapped errors and defects fail
|
|
24
|
+
* the stream.
|
|
25
|
+
*
|
|
26
|
+
* Internally each tool also carries memoized codecs and a precomputed
|
|
27
|
+
* `ToolDefinition` so the runtime doesn't rebuild them per invocation.
|
|
28
|
+
*/
|
|
29
|
+
export interface Tool<Parameters extends ToolSchema<any>, Success extends ToolSchema<any>> {
|
|
30
|
+
readonly description: string
|
|
31
|
+
readonly parameters: Parameters
|
|
32
|
+
readonly success: Success
|
|
33
|
+
readonly execute?: ToolExecute<Parameters, Success>
|
|
34
|
+
/** @internal */
|
|
35
|
+
readonly _decode: (input: unknown) => Effect.Effect<Schema.Schema.Type<Parameters>, Schema.SchemaError>
|
|
36
|
+
/** @internal */
|
|
37
|
+
readonly _encode: (value: Schema.Schema.Type<Success>) => Effect.Effect<unknown, Schema.SchemaError>
|
|
38
|
+
/** @internal */
|
|
39
|
+
readonly _definition: ToolDefinitionClass
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export type AnyTool = Tool<ToolSchema<any>, ToolSchema<any>>
|
|
43
|
+
|
|
44
|
+
export type ExecutableTool<Parameters extends ToolSchema<any>, Success extends ToolSchema<any>> = Tool<
|
|
45
|
+
Parameters,
|
|
46
|
+
Success
|
|
47
|
+
> & {
|
|
48
|
+
readonly execute: ToolExecute<Parameters, Success>
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export type AnyExecutableTool = ExecutableTool<ToolSchema<any>, ToolSchema<any>>
|
|
52
|
+
|
|
53
|
+
export type ExecutableTools = Record<string, AnyExecutableTool>
|
|
54
|
+
|
|
55
|
+
type TypedToolConfig = {
|
|
56
|
+
readonly description: string
|
|
57
|
+
readonly parameters: ToolSchema<any>
|
|
58
|
+
readonly success: ToolSchema<any>
|
|
59
|
+
readonly execute?: ToolExecute<ToolSchema<any>, ToolSchema<any>>
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
type DynamicToolConfig = {
|
|
63
|
+
readonly description: string
|
|
64
|
+
readonly jsonSchema: JsonSchema.JsonSchema
|
|
65
|
+
readonly execute?: (params: unknown) => Effect.Effect<unknown, ToolFailure>
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Constructs a tool. Two input modes:
|
|
70
|
+
*
|
|
71
|
+
* 1. **Typed** — pass Effect `parameters` and `success` Schemas; inputs and
|
|
72
|
+
* outputs are statically typed and decoded/encoded automatically.
|
|
73
|
+
*
|
|
74
|
+
* ```ts
|
|
75
|
+
* Tool.make({
|
|
76
|
+
* description: "Get current weather",
|
|
77
|
+
* parameters: Schema.Struct({ city: Schema.String }),
|
|
78
|
+
* success: Schema.Struct({ temperature: Schema.Number }),
|
|
79
|
+
* execute: ({ city }) => Effect.succeed({ temperature: 22 }),
|
|
80
|
+
* })
|
|
81
|
+
* ```
|
|
82
|
+
*
|
|
83
|
+
* 2. **Dynamic** — pass raw JSON Schema as `jsonSchema`. Use this when the
|
|
84
|
+
* schema comes from an external source (MCP server, plugin manifest,
|
|
85
|
+
* dynamic config) and is not known at compile time. Inputs are typed as
|
|
86
|
+
* `unknown`; the handler is responsible for any validation it needs.
|
|
87
|
+
*
|
|
88
|
+
* ```ts
|
|
89
|
+
* Tool.make({
|
|
90
|
+
* description: "Look something up",
|
|
91
|
+
* jsonSchema: { type: "object", properties: { ... } },
|
|
92
|
+
* execute: (params) => Effect.succeed(...),
|
|
93
|
+
* })
|
|
94
|
+
* ```
|
|
95
|
+
*
|
|
96
|
+
* In both modes the produced tool flows through `toDefinitions(...)` and the
|
|
97
|
+
* runtime identically.
|
|
98
|
+
*/
|
|
99
|
+
export function make<Parameters extends ToolSchema<any>, Success extends ToolSchema<any>>(config: {
|
|
100
|
+
readonly description: string
|
|
101
|
+
readonly parameters: Parameters
|
|
102
|
+
readonly success: Success
|
|
103
|
+
readonly execute: ToolExecute<Parameters, Success>
|
|
104
|
+
}): ExecutableTool<Parameters, Success>
|
|
105
|
+
export function make<Parameters extends ToolSchema<any>, Success extends ToolSchema<any>>(config: {
|
|
106
|
+
readonly description: string
|
|
107
|
+
readonly parameters: Parameters
|
|
108
|
+
readonly success: Success
|
|
109
|
+
readonly execute?: undefined
|
|
110
|
+
}): Tool<Parameters, Success>
|
|
111
|
+
export function make(config: {
|
|
112
|
+
readonly description: string
|
|
113
|
+
readonly jsonSchema: JsonSchema.JsonSchema
|
|
114
|
+
readonly execute: (params: unknown) => Effect.Effect<unknown, ToolFailure>
|
|
115
|
+
}): AnyExecutableTool
|
|
116
|
+
export function make(config: {
|
|
117
|
+
readonly description: string
|
|
118
|
+
readonly jsonSchema: JsonSchema.JsonSchema
|
|
119
|
+
readonly execute?: undefined
|
|
120
|
+
}): AnyTool
|
|
121
|
+
export function make(config: TypedToolConfig | DynamicToolConfig): AnyTool {
|
|
122
|
+
if ("jsonSchema" in config) {
|
|
123
|
+
return {
|
|
124
|
+
description: config.description,
|
|
125
|
+
parameters: Schema.Unknown as ToolSchema<unknown>,
|
|
126
|
+
success: Schema.Unknown as ToolSchema<unknown>,
|
|
127
|
+
execute: config.execute,
|
|
128
|
+
_decode: Effect.succeed,
|
|
129
|
+
_encode: Effect.succeed,
|
|
130
|
+
_definition: new ToolDefinition({
|
|
131
|
+
name: "",
|
|
132
|
+
description: config.description,
|
|
133
|
+
inputSchema: config.jsonSchema,
|
|
134
|
+
}),
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return {
|
|
138
|
+
description: config.description,
|
|
139
|
+
parameters: config.parameters,
|
|
140
|
+
success: config.success,
|
|
141
|
+
execute: config.execute,
|
|
142
|
+
_decode: Schema.decodeUnknownEffect(config.parameters),
|
|
143
|
+
_encode: Schema.encodeEffect(config.success),
|
|
144
|
+
_definition: new ToolDefinition({
|
|
145
|
+
name: "",
|
|
146
|
+
description: config.description,
|
|
147
|
+
inputSchema: toJsonSchema(config.parameters),
|
|
148
|
+
}),
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export const tool = make
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* A record of named tools. The record key becomes the tool name on the wire.
|
|
156
|
+
*/
|
|
157
|
+
export type Tools = Record<string, AnyTool>
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Convert a tools record into the `ToolDefinition[]` shape that
|
|
161
|
+
* `LLMRequest.tools` expects. The runtime calls this internally; consumers
|
|
162
|
+
* that build `LLMRequest` themselves can use it too.
|
|
163
|
+
*
|
|
164
|
+
* Tool names come from the record keys, so the per-tool cached
|
|
165
|
+
* `_definition` is rebuilt with the correct name here. The JSON Schema body
|
|
166
|
+
* is reused.
|
|
167
|
+
*/
|
|
168
|
+
export const toDefinitions = (tools: Tools): ReadonlyArray<ToolDefinitionClass> =>
|
|
169
|
+
Object.entries(tools).map(
|
|
170
|
+
([name, item]) =>
|
|
171
|
+
new ToolDefinition({
|
|
172
|
+
name,
|
|
173
|
+
description: item._definition.description,
|
|
174
|
+
inputSchema: item._definition.inputSchema,
|
|
175
|
+
}),
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
const toJsonSchema = (schema: Schema.Top): JsonSchema.JsonSchema => {
|
|
179
|
+
const document = Schema.toJsonSchemaDocument(schema)
|
|
180
|
+
const base =
|
|
181
|
+
Object.keys(document.definitions).length === 0
|
|
182
|
+
? document.schema
|
|
183
|
+
: { ...document.schema, $defs: document.definitions }
|
|
184
|
+
// OpenAI/Anthropic both require the top-level tool parameters schema to be
|
|
185
|
+
// `type: "object"`. Effect Schema emits `anyOf: [{object},{array}]` for
|
|
186
|
+
// empty structs, which OpenAI rejects. Normalize here.
|
|
187
|
+
return normalizeTopLevel(base)
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const normalizeTopLevel = (s: JsonSchema.JsonSchema): JsonSchema.JsonSchema => {
|
|
191
|
+
if (!s || typeof s !== "object") {
|
|
192
|
+
return { type: "object", properties: {}, additionalProperties: false } as JsonSchema.JsonSchema
|
|
193
|
+
}
|
|
194
|
+
const obj = s as { type?: unknown; anyOf?: ReadonlyArray<JsonSchema.JsonSchema> }
|
|
195
|
+
if (obj.type === "object") return s
|
|
196
|
+
if (Array.isArray(obj.anyOf)) {
|
|
197
|
+
const objectVariant = obj.anyOf.find(
|
|
198
|
+
(v): v is JsonSchema.JsonSchema =>
|
|
199
|
+
v != null && typeof v === "object" && (v as { type?: unknown }).type === "object",
|
|
200
|
+
)
|
|
201
|
+
if (objectVariant) {
|
|
202
|
+
const { anyOf: _omit, ...rest } = obj
|
|
203
|
+
void _omit
|
|
204
|
+
return { ...rest, ...(objectVariant as object) } as JsonSchema.JsonSchema
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return { type: "object", properties: {}, additionalProperties: false } as JsonSchema.JsonSchema
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export { ToolFailure }
|
|
211
|
+
|
|
212
|
+
export * as Tool from "./tool"
|