@tinyweb_dev/agent-framework-llm 0.1.0 → 0.2.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/package.json +2 -2
- package/src/protocols/openai-chat.ts +45 -3
- package/src/schema/events.ts +2 -0
- package/src/schema/messages.ts +12 -2
- package/src/tool-runtime.ts +62 -24
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package.json",
|
|
3
3
|
"name": "@tinyweb_dev/agent-framework-llm",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"scripts": {
|
|
@@ -43,6 +43,6 @@
|
|
|
43
43
|
},
|
|
44
44
|
"dependencies": {
|
|
45
45
|
"effect": "4.0.0-beta.59",
|
|
46
|
-
"@tinyweb_dev/agent-framework-core": "0.
|
|
46
|
+
"@tinyweb_dev/agent-framework-core": "0.2.0"
|
|
47
47
|
}
|
|
48
48
|
}
|
|
@@ -157,6 +157,8 @@ interface ParserState {
|
|
|
157
157
|
readonly toolCallEvents: ReadonlyArray<LLMEvent>
|
|
158
158
|
readonly usage?: Usage
|
|
159
159
|
readonly finishReason?: FinishReason
|
|
160
|
+
/** Running assistant text used to normalise cumulative `delta.content` providers. */
|
|
161
|
+
readonly textAcc: string
|
|
160
162
|
}
|
|
161
163
|
|
|
162
164
|
const invalid = ProviderShared.invalidRequest
|
|
@@ -331,6 +333,34 @@ const mapUsage = (usage: OpenAIChatEvent["usage"]): Usage | undefined => {
|
|
|
331
333
|
})
|
|
332
334
|
}
|
|
333
335
|
|
|
336
|
+
/**
|
|
337
|
+
* OpenAI Chat streams are *incremental* (`delta.content` is the next fragment).
|
|
338
|
+
* Some OpenAI-compatible proxies instead re-send the full text so far on every
|
|
339
|
+
* chunk (cumulative snapshots). Blindly forwarding those as text-delta makes
|
|
340
|
+
* UIs that concatenate deltas render duplicated prose.
|
|
341
|
+
*
|
|
342
|
+
* Returns the incremental fragment to emit (empty = skip) and the new
|
|
343
|
+
* accumulated text for parser state.
|
|
344
|
+
*/
|
|
345
|
+
const normaliseTextDelta = (
|
|
346
|
+
prev: string,
|
|
347
|
+
incoming: string,
|
|
348
|
+
): { readonly emit: string; readonly textAcc: string } => {
|
|
349
|
+
if (!incoming) return { emit: "", textAcc: prev }
|
|
350
|
+
// Exact replay of what we already have — drop.
|
|
351
|
+
if (incoming === prev) return { emit: "", textAcc: prev }
|
|
352
|
+
// Cumulative snapshot: full text so far (or a longer prefix continuation).
|
|
353
|
+
if (prev.length > 0 && incoming.startsWith(prev)) {
|
|
354
|
+
return { emit: incoming.slice(prev.length), textAcc: incoming }
|
|
355
|
+
}
|
|
356
|
+
// Stale / shorter snapshot after we already advanced — drop.
|
|
357
|
+
if (prev.length > 0 && prev.startsWith(incoming)) {
|
|
358
|
+
return { emit: "", textAcc: prev }
|
|
359
|
+
}
|
|
360
|
+
// True incremental fragment.
|
|
361
|
+
return { emit: incoming, textAcc: prev + incoming }
|
|
362
|
+
}
|
|
363
|
+
|
|
334
364
|
const step = (state: ParserState, event: OpenAIChatEvent) =>
|
|
335
365
|
Effect.gen(function* () {
|
|
336
366
|
const events: LLMEvent[] = []
|
|
@@ -340,8 +370,15 @@ const step = (state: ParserState, event: OpenAIChatEvent) =>
|
|
|
340
370
|
const delta = choice?.delta
|
|
341
371
|
const toolDeltas = delta?.tool_calls ?? []
|
|
342
372
|
let tools = state.tools
|
|
343
|
-
|
|
344
|
-
|
|
373
|
+
let textAcc = state.textAcc
|
|
374
|
+
|
|
375
|
+
if (delta?.content) {
|
|
376
|
+
const normalised = normaliseTextDelta(textAcc, delta.content)
|
|
377
|
+
textAcc = normalised.textAcc
|
|
378
|
+
if (normalised.emit) {
|
|
379
|
+
events.push(LLMEvent.textDelta({ id: "text-0", text: normalised.emit }))
|
|
380
|
+
}
|
|
381
|
+
}
|
|
345
382
|
|
|
346
383
|
for (const tool of toolDeltas) {
|
|
347
384
|
const result = ToolStream.appendOrStart(
|
|
@@ -367,6 +404,7 @@ const step = (state: ParserState, event: OpenAIChatEvent) =>
|
|
|
367
404
|
toolCallEvents: finished?.events ?? state.toolCallEvents,
|
|
368
405
|
usage,
|
|
369
406
|
finishReason,
|
|
407
|
+
textAcc,
|
|
370
408
|
},
|
|
371
409
|
events,
|
|
372
410
|
] as const
|
|
@@ -389,7 +427,11 @@ export const protocol = Protocol.make({
|
|
|
389
427
|
},
|
|
390
428
|
stream: {
|
|
391
429
|
event: Protocol.jsonEvent(OpenAIChatEvent),
|
|
392
|
-
initial: () => ({
|
|
430
|
+
initial: (): ParserState => ({
|
|
431
|
+
tools: ToolStream.empty<number>(),
|
|
432
|
+
toolCallEvents: [],
|
|
433
|
+
textAcc: "",
|
|
434
|
+
}),
|
|
393
435
|
step,
|
|
394
436
|
onHalt: finishEvents,
|
|
395
437
|
},
|
package/src/schema/events.ts
CHANGED
|
@@ -150,6 +150,8 @@ export const ToolError = Schema.Struct({
|
|
|
150
150
|
id: ToolCallID,
|
|
151
151
|
name: Schema.String,
|
|
152
152
|
message: Schema.String,
|
|
153
|
+
/** Optional structured payload (e.g. tool-interrupt metadata for approval). */
|
|
154
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
|
153
155
|
providerMetadata: Schema.optional(ProviderMetadata),
|
|
154
156
|
}).annotate({ identifier: "LLM.Event.ToolError" })
|
|
155
157
|
export type ToolError = Schema.Schema.Type<typeof ToolError>
|
package/src/schema/messages.ts
CHANGED
|
@@ -49,10 +49,20 @@ export const ToolResultValue = Object.assign(
|
|
|
49
49
|
Schema.Struct({
|
|
50
50
|
type: Schema.Literals(["json", "text", "error"]),
|
|
51
51
|
value: Schema.Unknown,
|
|
52
|
+
/** Optional structured payload (e.g. tool-interrupt metadata). */
|
|
53
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
|
52
54
|
}).annotate({ identifier: "LLM.ToolResult" }),
|
|
53
55
|
{
|
|
54
|
-
make: (
|
|
55
|
-
|
|
56
|
+
make: (
|
|
57
|
+
value: unknown,
|
|
58
|
+
type: ToolResultValue["type"] = "json",
|
|
59
|
+
metadata?: Record<string, unknown>,
|
|
60
|
+
): ToolResultValue => {
|
|
61
|
+
if (isToolResultValue(value)) {
|
|
62
|
+
return metadata ? { ...value, metadata: { ...(value.metadata ?? {}), ...metadata } } : value
|
|
63
|
+
}
|
|
64
|
+
return metadata ? { type, value, metadata } : { type, value }
|
|
65
|
+
},
|
|
56
66
|
},
|
|
57
67
|
)
|
|
58
68
|
export type ToolResultValue = Schema.Schema.Type<typeof ToolResultValue>
|
package/src/tool-runtime.ts
CHANGED
|
@@ -97,23 +97,32 @@ export const stream = <T extends Tools>(options: StreamOptions<T>): Stream.Strea
|
|
|
97
97
|
.pipe(Stream.tap((event) => Effect.sync(() => accumulate(state, event))))
|
|
98
98
|
|
|
99
99
|
const continuation = Stream.unwrap(
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
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
|
+
// Tool-interrupt (permission ask/interrupt mode): stop the agentic
|
|
112
|
+
// loop so the host can collect user approval and later resume.
|
|
113
|
+
// Do NOT feed interrupt errors back to the model as a follow-up turn.
|
|
114
|
+
if (dispatched.some(([, result]) => isInterruptResult(result))) return resultStream
|
|
115
|
+
|
|
116
|
+
if (!options.stopWhen) return resultStream
|
|
117
|
+
if (options.stopWhen({ step, request, toolCalls: state.toolCalls })) return resultStream
|
|
118
|
+
|
|
119
|
+
// Only completed (non-interrupt) results participate in the follow-up.
|
|
120
|
+
const followUp = dispatched.filter(([, result]) => !isInterruptResult(result))
|
|
121
|
+
if (followUp.length === 0) return resultStream
|
|
122
|
+
|
|
123
|
+
return resultStream.pipe(Stream.concat(loop(followUpRequest(request, state, followUp), step + 1)))
|
|
124
|
+
}),
|
|
125
|
+
)
|
|
117
126
|
|
|
118
127
|
return modelStream.pipe(Stream.concat(continuation))
|
|
119
128
|
}),
|
|
@@ -209,6 +218,12 @@ const appendStreamingText = (
|
|
|
209
218
|
state.assistantContent.push({ type, text, providerMetadata })
|
|
210
219
|
}
|
|
211
220
|
|
|
221
|
+
const isInterruptResult = (result: ToolResultValue): boolean =>
|
|
222
|
+
result.type === "error" &&
|
|
223
|
+
typeof result.metadata === "object" &&
|
|
224
|
+
result.metadata !== null &&
|
|
225
|
+
(result.metadata as { kind?: unknown }).kind === "tool-interrupt"
|
|
226
|
+
|
|
212
227
|
const dispatch = (tools: Tools, call: ToolCallPart): Effect.Effect<ToolResultValue> => {
|
|
213
228
|
const tool = tools[call.name]
|
|
214
229
|
if (!tool) return Effect.succeed({ type: "error" as const, value: `Unknown tool: ${call.name}` })
|
|
@@ -217,7 +232,11 @@ const dispatch = (tools: Tools, call: ToolCallPart): Effect.Effect<ToolResultVal
|
|
|
217
232
|
|
|
218
233
|
return decodeAndExecute(tool, call.input).pipe(
|
|
219
234
|
Effect.catchTag("LLM.ToolFailure", (failure) =>
|
|
220
|
-
Effect.succeed({
|
|
235
|
+
Effect.succeed({
|
|
236
|
+
type: "error" as const,
|
|
237
|
+
value: failure.message,
|
|
238
|
+
...(failure.metadata ? { metadata: failure.metadata as Record<string, unknown> } : {}),
|
|
239
|
+
} satisfies ToolResultValue),
|
|
221
240
|
),
|
|
222
241
|
)
|
|
223
242
|
}
|
|
@@ -239,13 +258,32 @@ const decodeAndExecute = (tool: AnyTool, input: unknown): Effect.Effect<ToolResu
|
|
|
239
258
|
Effect.map((encoded): ToolResultValue => ({ type: "json", value: encoded })),
|
|
240
259
|
)
|
|
241
260
|
|
|
242
|
-
const emitEvents = (call: ToolCallPart, result: ToolResultValue): ReadonlyArray<LLMEvent> =>
|
|
243
|
-
result.type === "error"
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
261
|
+
const emitEvents = (call: ToolCallPart, result: ToolResultValue): ReadonlyArray<LLMEvent> => {
|
|
262
|
+
if (result.type === "error") {
|
|
263
|
+
// Interrupt: emit tool-error only (no tool-result) so agent processors can
|
|
264
|
+
// map it to pending-approval without a follow-up result overwriting state.
|
|
265
|
+
if (isInterruptResult(result)) {
|
|
266
|
+
return [
|
|
267
|
+
LLMEvent.toolError({
|
|
268
|
+
id: call.id,
|
|
269
|
+
name: call.name,
|
|
270
|
+
message: String(result.value),
|
|
271
|
+
metadata: result.metadata,
|
|
272
|
+
}),
|
|
247
273
|
]
|
|
248
|
-
|
|
274
|
+
}
|
|
275
|
+
return [
|
|
276
|
+
LLMEvent.toolError({
|
|
277
|
+
id: call.id,
|
|
278
|
+
name: call.name,
|
|
279
|
+
message: String(result.value),
|
|
280
|
+
metadata: result.metadata,
|
|
281
|
+
}),
|
|
282
|
+
LLMEvent.toolResult({ id: call.id, name: call.name, result }),
|
|
283
|
+
]
|
|
284
|
+
}
|
|
285
|
+
return [LLMEvent.toolResult({ id: call.id, name: call.name, result })]
|
|
286
|
+
}
|
|
249
287
|
|
|
250
288
|
const followUpRequest = (
|
|
251
289
|
request: LLMRequest,
|