@mariozechner/pi-ai 0.5.34 → 0.5.36
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 +31 -31
- package/dist/agent/agent.d.ts +2 -1
- package/dist/agent/agent.d.ts.map +1 -1
- package/dist/agent/agent.js +6 -4
- package/dist/agent/agent.js.map +1 -1
- package/dist/agent/tools/calculate.d.ts +2 -7
- package/dist/agent/tools/calculate.d.ts.map +1 -1
- package/dist/agent/tools/calculate.js +3 -3
- package/dist/agent/tools/calculate.js.map +1 -1
- package/dist/agent/tools/get-current-time.d.ts +2 -7
- package/dist/agent/tools/get-current-time.d.ts.map +1 -1
- package/dist/agent/tools/get-current-time.js +3 -3
- package/dist/agent/tools/get-current-time.js.map +1 -1
- package/dist/agent/types.d.ts +3 -3
- package/dist/agent/types.d.ts.map +1 -1
- package/dist/agent/types.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/models.generated.d.ts +7 -7
- package/dist/models.generated.js +41 -41
- package/dist/models.generated.js.map +1 -1
- package/dist/providers/anthropic.d.ts.map +1 -1
- package/dist/providers/anthropic.js +1 -2
- package/dist/providers/anthropic.js.map +1 -1
- package/dist/providers/google.d.ts.map +1 -1
- package/dist/providers/google.js +1 -2
- package/dist/providers/google.js.map +1 -1
- package/dist/providers/openai-completions.d.ts.map +1 -1
- package/dist/providers/openai-completions.js +1 -2
- package/dist/providers/openai-completions.js.map +1 -1
- package/dist/providers/openai-responses.d.ts.map +1 -1
- package/dist/providers/openai-responses.js +1 -2
- package/dist/providers/openai-responses.js.map +1 -1
- package/dist/typebox-helpers.d.ts +17 -0
- package/dist/typebox-helpers.d.ts.map +1 -0
- package/dist/typebox-helpers.js +21 -0
- package/dist/typebox-helpers.js.map +1 -0
- package/dist/types.d.ts +2 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/validation.d.ts +3 -3
- package/dist/validation.d.ts.map +1 -1
- package/dist/validation.js +22 -22
- package/dist/validation.js.map +1 -1
- package/package.json +4 -1
package/README.md
CHANGED
|
@@ -24,17 +24,17 @@ npm install @mariozechner/pi-ai
|
|
|
24
24
|
## Quick Start
|
|
25
25
|
|
|
26
26
|
```typescript
|
|
27
|
-
import { getModel, stream, complete, Context, Tool,
|
|
27
|
+
import { Type, getModel, stream, complete, Context, Tool, StringEnum } from '@mariozechner/pi-ai';
|
|
28
28
|
|
|
29
29
|
// Fully typed with auto-complete support for both providers and models
|
|
30
30
|
const model = getModel('openai', 'gpt-4o-mini');
|
|
31
31
|
|
|
32
|
-
// Define tools with
|
|
32
|
+
// Define tools with TypeBox schemas for type safety and validation
|
|
33
33
|
const tools: Tool[] = [{
|
|
34
34
|
name: 'get_time',
|
|
35
35
|
description: 'Get the current time',
|
|
36
|
-
parameters:
|
|
37
|
-
timezone:
|
|
36
|
+
parameters: Type.Object({
|
|
37
|
+
timezone: Type.Optional(Type.String({ description: 'Optional timezone (e.g., America/New_York)' }))
|
|
38
38
|
})
|
|
39
39
|
}];
|
|
40
40
|
|
|
@@ -133,36 +133,35 @@ for (const block of response.content) {
|
|
|
133
133
|
|
|
134
134
|
## Tools
|
|
135
135
|
|
|
136
|
-
Tools enable LLMs to interact with external systems. This library uses
|
|
136
|
+
Tools enable LLMs to interact with external systems. This library uses TypeBox schemas for type-safe tool definitions with automatic validation using AJV. TypeBox schemas can be serialized and deserialized as plain JSON, making them ideal for distributed systems.
|
|
137
137
|
|
|
138
138
|
### Defining Tools
|
|
139
139
|
|
|
140
140
|
```typescript
|
|
141
|
-
import {
|
|
141
|
+
import { Type, Tool, StringEnum } from '@mariozechner/pi-ai';
|
|
142
142
|
|
|
143
|
-
// Define tool parameters with
|
|
143
|
+
// Define tool parameters with TypeBox
|
|
144
144
|
const weatherTool: Tool = {
|
|
145
145
|
name: 'get_weather',
|
|
146
146
|
description: 'Get current weather for a location',
|
|
147
|
-
parameters:
|
|
148
|
-
location:
|
|
149
|
-
units:
|
|
147
|
+
parameters: Type.Object({
|
|
148
|
+
location: Type.String({ description: 'City name or coordinates' }),
|
|
149
|
+
units: StringEnum(['celsius', 'fahrenheit'], { default: 'celsius' })
|
|
150
150
|
})
|
|
151
151
|
};
|
|
152
152
|
|
|
153
|
-
//
|
|
153
|
+
// Note: For Google API compatibility, use StringEnum helper instead of Type.Enum
|
|
154
|
+
// Type.Enum generates anyOf/const patterns that Google doesn't support
|
|
155
|
+
|
|
154
156
|
const bookMeetingTool: Tool = {
|
|
155
157
|
name: 'book_meeting',
|
|
156
158
|
description: 'Schedule a meeting',
|
|
157
|
-
parameters:
|
|
158
|
-
title:
|
|
159
|
-
startTime:
|
|
160
|
-
endTime:
|
|
161
|
-
attendees:
|
|
162
|
-
})
|
|
163
|
-
data => new Date(data.endTime) > new Date(data.startTime),
|
|
164
|
-
{ message: 'End time must be after start time' }
|
|
165
|
-
)
|
|
159
|
+
parameters: Type.Object({
|
|
160
|
+
title: Type.String({ minLength: 1 }),
|
|
161
|
+
startTime: Type.String({ format: 'date-time' }),
|
|
162
|
+
endTime: Type.String({ format: 'date-time' }),
|
|
163
|
+
attendees: Type.Array(Type.String({ format: 'email' }), { minItems: 1 })
|
|
164
|
+
})
|
|
166
165
|
};
|
|
167
166
|
```
|
|
168
167
|
|
|
@@ -179,7 +178,7 @@ const response = await complete(model, context);
|
|
|
179
178
|
// Check for tool calls in the response
|
|
180
179
|
for (const block of response.content) {
|
|
181
180
|
if (block.type === 'toolCall') {
|
|
182
|
-
// Arguments are automatically validated against the
|
|
181
|
+
// Arguments are automatically validated against the TypeBox schema using AJV
|
|
183
182
|
// If validation fails, an error event is emitted
|
|
184
183
|
const result = await executeWeatherApi(block.arguments);
|
|
185
184
|
|
|
@@ -687,19 +686,20 @@ const messages = await stream.result();
|
|
|
687
686
|
context.messages.push(...messages);
|
|
688
687
|
```
|
|
689
688
|
|
|
690
|
-
### Defining Tools with
|
|
689
|
+
### Defining Tools with TypeBox
|
|
691
690
|
|
|
692
|
-
Tools use
|
|
691
|
+
Tools use TypeBox schemas for runtime validation and type inference:
|
|
693
692
|
|
|
694
693
|
```typescript
|
|
695
|
-
import {
|
|
696
|
-
import { AgentTool, AgentToolResult } from '@mariozechner/pi-ai';
|
|
694
|
+
import { Type, Static, AgentTool, AgentToolResult, StringEnum } from '@mariozechner/pi-ai';
|
|
697
695
|
|
|
698
|
-
const weatherSchema =
|
|
699
|
-
city:
|
|
700
|
-
units:
|
|
696
|
+
const weatherSchema = Type.Object({
|
|
697
|
+
city: Type.String({ minLength: 1 }),
|
|
698
|
+
units: StringEnum(['celsius', 'fahrenheit'], { default: 'celsius' })
|
|
701
699
|
});
|
|
702
700
|
|
|
701
|
+
type WeatherParams = Static<typeof weatherSchema>;
|
|
702
|
+
|
|
703
703
|
const weatherTool: AgentTool<typeof weatherSchema, { temp: number }> = {
|
|
704
704
|
label: 'Get Weather',
|
|
705
705
|
name: 'get_weather',
|
|
@@ -718,7 +718,7 @@ const weatherTool: AgentTool<typeof weatherSchema, { temp: number }> = {
|
|
|
718
718
|
|
|
719
719
|
### Validation and Error Handling
|
|
720
720
|
|
|
721
|
-
Tool arguments are automatically validated using the
|
|
721
|
+
Tool arguments are automatically validated using AJV with the TypeBox schema. Invalid arguments result in detailed error messages:
|
|
722
722
|
|
|
723
723
|
```typescript
|
|
724
724
|
// If the LLM calls with invalid arguments:
|
|
@@ -727,8 +727,8 @@ Tool arguments are automatically validated using the Zod schema. Invalid argumen
|
|
|
727
727
|
// The tool execution will fail with:
|
|
728
728
|
/*
|
|
729
729
|
Validation failed for tool "get_weather":
|
|
730
|
-
- city:
|
|
731
|
-
- units:
|
|
730
|
+
- city: must NOT have fewer than 1 characters
|
|
731
|
+
- units: must be equal to one of the allowed values
|
|
732
732
|
|
|
733
733
|
Received arguments:
|
|
734
734
|
{
|
package/dist/agent/agent.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { EventStream } from "../event-stream";
|
|
2
|
+
import { streamSimple } from "../stream.js";
|
|
2
3
|
import type { UserMessage } from "../types.js";
|
|
3
4
|
import type { AgentContext, AgentEvent, PromptConfig } from "./types";
|
|
4
|
-
export declare function prompt(prompt: UserMessage, context: AgentContext, config: PromptConfig, signal?: AbortSignal): EventStream<AgentEvent, AgentContext["messages"]>;
|
|
5
|
+
export declare function prompt(prompt: UserMessage, context: AgentContext, config: PromptConfig, signal?: AbortSignal, streamFn?: typeof streamSimple): EventStream<AgentEvent, AgentContext["messages"]>;
|
|
5
6
|
//# sourceMappingURL=agent.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../../src/agent/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;
|
|
1
|
+
{"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../../src/agent/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,KAAK,EAAyD,WAAW,EAAE,MAAM,aAAa,CAAC;AAEtG,OAAO,KAAK,EAAE,YAAY,EAAE,UAAU,EAA8B,YAAY,EAAE,MAAM,SAAS,CAAC;AAGlG,wBAAgB,MAAM,CACrB,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,YAAY,EACrB,MAAM,EAAE,YAAY,EACpB,MAAM,CAAC,EAAE,WAAW,EACpB,QAAQ,CAAC,EAAE,OAAO,YAAY,GAC5B,WAAW,CAAC,UAAU,EAAE,YAAY,CAAC,UAAU,CAAC,CAAC,CAwDnD"}
|
package/dist/agent/agent.js
CHANGED
|
@@ -2,7 +2,7 @@ import { EventStream } from "../event-stream";
|
|
|
2
2
|
import { streamSimple } from "../stream.js";
|
|
3
3
|
import { validateToolArguments } from "../validation.js";
|
|
4
4
|
// Main prompt function - returns a stream of events
|
|
5
|
-
export function prompt(prompt, context, config, signal) {
|
|
5
|
+
export function prompt(prompt, context, config, signal, streamFn) {
|
|
6
6
|
const stream = new EventStream((event) => event.type === "agent_end", (event) => (event.type === "agent_end" ? event.messages : []));
|
|
7
7
|
// Run the prompt async
|
|
8
8
|
(async () => {
|
|
@@ -31,7 +31,7 @@ export function prompt(prompt, context, config, signal) {
|
|
|
31
31
|
firstTurn = false;
|
|
32
32
|
}
|
|
33
33
|
// Stream assistant response
|
|
34
|
-
const assistantMessage = await streamAssistantResponse(currentContext, config, signal, stream);
|
|
34
|
+
const assistantMessage = await streamAssistantResponse(currentContext, config, signal, stream, streamFn);
|
|
35
35
|
newMessages.push(assistantMessage);
|
|
36
36
|
// Check for tool calls
|
|
37
37
|
const toolCalls = assistantMessage.content.filter((c) => c.type === "toolCall");
|
|
@@ -51,7 +51,7 @@ export function prompt(prompt, context, config, signal) {
|
|
|
51
51
|
return stream;
|
|
52
52
|
}
|
|
53
53
|
// Helper functions
|
|
54
|
-
async function streamAssistantResponse(context, config, signal, stream) {
|
|
54
|
+
async function streamAssistantResponse(context, config, signal, stream, streamFn) {
|
|
55
55
|
// Convert AgentContext to Context for streamSimple
|
|
56
56
|
// Use a copy of messages to avoid mutating the original context
|
|
57
57
|
const processedMessages = config.preprocessor
|
|
@@ -70,7 +70,9 @@ async function streamAssistantResponse(context, config, signal, stream) {
|
|
|
70
70
|
}),
|
|
71
71
|
tools: context.tools, // AgentTool extends Tool, so this works
|
|
72
72
|
};
|
|
73
|
-
|
|
73
|
+
// Use custom stream function if provided, otherwise use default streamSimple
|
|
74
|
+
const streamFunction = streamFn || streamSimple;
|
|
75
|
+
const response = await streamFunction(config.model, processedContext, { ...config, signal });
|
|
74
76
|
let partialMessage = null;
|
|
75
77
|
let addedPartial = false;
|
|
76
78
|
for await (const event of response) {
|
package/dist/agent/agent.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.js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Y,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;YAC3D,OAAO,GAAG,IAAI,CAAC;QAChB,CAAC;QAED,MAAM,CAAC,IAAI,CAAC;YACX,IAAI,EAAE,oBAAoB;YAC1B,UAAU,EAAE,QAAQ,CAAC,EAAE;YACvB,QAAQ,EAAE,QAAQ,CAAC,IAAI;YACvB,MAAM,EAAE,aAAa;YACrB,OAAO;SACP,CAAC,CAAC;QAEH,MAAM,iBAAiB,GAAyB;YAC/C,IAAI,EAAE,YAAY;YAClB,UAAU,EAAE,QAAQ,CAAC,EAAE;YACvB,QAAQ,EAAE,QAAQ,CAAC,IAAI;YACvB,MAAM,EAAE,OAAO,aAAa,KAAK,QAAQ,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,aAAa,CAAC,MAAM;YAChF,OAAO,EAAE,OAAO,aAAa,KAAK,QAAQ,CAAC,CAAC,CAAE,EAAQ,CAAC,CAAC,CAAC,aAAa,CAAC,OAAO;YAC9E,OAAO;SACP,CAAC;QAEF,OAAO,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC;QAChC,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC,CAAC;QACnE,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC,CAAC;IAClE,CAAC;IAED,OAAO,OAAO,CAAC;AAChB,CAAC","sourcesContent":["import { EventStream } from \"../event-stream\";\nimport { streamSimple } from \"../stream.js\";\nimport type { AssistantMessage, Context, Message, ToolResultMessage, UserMessage } from \"../types.js\";\nimport { validateToolArguments } from \"../validation.js\";\nimport type { AgentContext, AgentEvent, AgentTool, AgentToolResult, PromptConfig } from \"./types\";\n\n// Main prompt function - returns a stream of events\nexport function prompt(\n\tprompt: UserMessage,\n\tcontext: AgentContext,\n\tconfig: PromptConfig,\n\tsignal?: AbortSignal,\n): EventStream<AgentEvent, AgentContext[\"messages\"]> {\n\tconst stream = new EventStream<AgentEvent, AgentContext[\"messages\"]>(\n\t\t(event) => event.type === \"agent_end\",\n\t\t(event) => (event.type === \"agent_end\" ? event.messages : []),\n\t);\n\n\t// Run the prompt async\n\t(async () => {\n\t\t// Track new messages generated during this prompt\n\t\tconst newMessages: AgentContext[\"messages\"] = [];\n\t\t// Create user message for the prompt\n\t\tconst messages = [...context.messages, prompt];\n\t\tnewMessages.push(prompt);\n\n\t\tstream.push({ type: \"agent_start\" });\n\t\tstream.push({ type: \"turn_start\" });\n\t\tstream.push({ type: \"message_start\", message: prompt });\n\t\tstream.push({ type: \"message_end\", message: prompt });\n\n\t\t// Update context with new messages\n\t\tconst currentContext: AgentContext = {\n\t\t\t...context,\n\t\t\tmessages,\n\t\t};\n\n\t\t// Keep looping while we have tool calls\n\t\tlet hasMoreToolCalls = true;\n\t\tlet firstTurn = true;\n\t\twhile (hasMoreToolCalls) {\n\t\t\tif (!firstTurn) {\n\t\t\t\tstream.push({ type: \"turn_start\" });\n\t\t\t} else {\n\t\t\t\tfirstTurn = false;\n\t\t\t}\n\t\t\t// Stream assistant response\n\t\t\tconst assistantMessage = await streamAssistantResponse(currentContext, config, signal, stream);\n\t\t\tnewMessages.push(assistantMessage);\n\n\t\t\t// Check for tool calls\n\t\t\tconst toolCalls = assistantMessage.content.filter((c) => c.type === \"toolCall\");\n\t\t\thasMoreToolCalls = toolCalls.length > 0;\n\n\t\t\tconst toolResults: ToolResultMessage[] = [];\n\t\t\tif (hasMoreToolCalls) {\n\t\t\t\t// Execute tool calls\n\t\t\t\ttoolResults.push(...(await executeToolCalls(currentContext.tools, assistantMessage, signal, stream)));\n\t\t\t\tcurrentContext.messages.push(...toolResults);\n\t\t\t\tnewMessages.push(...toolResults);\n\t\t\t}\n\t\t\tstream.push({ type: \"turn_end\", assistantMessage, toolResults: toolResults });\n\t\t}\n\t\tstream.push({ type: \"agent_end\", messages: newMessages });\n\t\tstream.end(newMessages);\n\t})();\n\n\treturn stream;\n}\n\n// Helper functions\nasync function streamAssistantResponse(\n\tcontext: AgentContext,\n\tconfig: PromptConfig,\n\tsignal: AbortSignal | undefined,\n\tstream: EventStream<AgentEvent, AgentContext[\"messages\"]>,\n): Promise<AssistantMessage> {\n\t// Convert AgentContext to Context for streamSimple\n\t// Use a copy of messages to avoid mutating the original context\n\tconst processedMessages = config.preprocessor\n\t\t? await config.preprocessor(context.messages, signal)\n\t\t: [...context.messages];\n\tconst processedContext: Context = {\n\t\tsystemPrompt: context.systemPrompt,\n\t\tmessages: [...processedMessages].map((m) => {\n\t\t\tif (m.role === \"toolResult\") {\n\t\t\t\tconst { details, ...rest } = m;\n\t\t\t\treturn rest;\n\t\t\t} else {\n\t\t\t\treturn m;\n\t\t\t}\n\t\t}),\n\t\ttools: context.tools, // AgentTool extends Tool, so this works\n\t};\n\n\tconst response = await streamSimple(config.model, processedContext, { ...config, signal });\n\n\tlet partialMessage: AssistantMessage | null = null;\n\tlet addedPartial = false;\n\n\tfor await (const event of response) {\n\t\tswitch (event.type) {\n\t\t\tcase \"start\":\n\t\t\t\tpartialMessage = event.partial;\n\t\t\t\tcontext.messages.push(partialMessage);\n\t\t\t\taddedPartial = true;\n\t\t\t\tstream.push({ type: \"message_start\", message: { ...partialMessage } });\n\t\t\t\tbreak;\n\n\t\t\tcase \"text_start\":\n\t\t\tcase \"text_delta\":\n\t\t\tcase \"text_end\":\n\t\t\tcase \"thinking_start\":\n\t\t\tcase \"thinking_delta\":\n\t\t\tcase \"thinking_end\":\n\t\t\tcase \"toolcall_start\":\n\t\t\tcase \"toolcall_delta\":\n\t\t\tcase \"toolcall_end\":\n\t\t\t\tif (partialMessage) {\n\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\tcontext.messages[context.messages.length - 1] = partialMessage;\n\t\t\t\t\tstream.push({ type: \"message_update\", assistantMessageEvent: event, message: { ...partialMessage } });\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"done\":\n\t\t\tcase \"error\": {\n\t\t\t\tconst finalMessage = await response.result();\n\t\t\t\tif (addedPartial) {\n\t\t\t\t\tcontext.messages[context.messages.length - 1] = finalMessage;\n\t\t\t\t} else {\n\t\t\t\t\tcontext.messages.push(finalMessage);\n\t\t\t\t}\n\t\t\t\tstream.push({ type: \"message_end\", message: finalMessage });\n\t\t\t\treturn finalMessage;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn await response.result();\n}\n\nasync function executeToolCalls<T>(\n\ttools: AgentTool<any, T>[] | undefined,\n\tassistantMessage: AssistantMessage,\n\tsignal: AbortSignal | undefined,\n\tstream: EventStream<AgentEvent, Message[]>,\n): Promise<ToolResultMessage<T>[]> {\n\tconst toolCalls = assistantMessage.content.filter((c) => c.type === \"toolCall\");\n\tconst results: ToolResultMessage<any>[] = [];\n\n\tfor (const toolCall of toolCalls) {\n\t\tconst tool = tools?.find((t) => t.name === toolCall.name);\n\n\t\tstream.push({\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\targs: toolCall.arguments,\n\t\t});\n\n\t\tlet resultOrError: AgentToolResult<T> | string;\n\t\tlet isError = false;\n\n\t\ttry {\n\t\t\tif (!tool) throw new Error(`Tool ${toolCall.name} not found`);\n\n\t\t\t// Validate arguments using shared validation function\n\t\t\tconst validatedArgs = validateToolArguments(tool, toolCall);\n\n\t\t\t// Execute with validated, typed arguments\n\t\t\tresultOrError = await tool.execute(toolCall.id, validatedArgs, signal);\n\t\t} catch (e) {\n\t\t\tresultOrError = e instanceof Error ? e.message : String(e);\n\t\t\tisError = true;\n\t\t}\n\n\t\tstream.push({\n\t\t\ttype: \"tool_execution_end\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\tresult: resultOrError,\n\t\t\tisError,\n\t\t});\n\n\t\tconst toolResultMessage: ToolResultMessage<T> = {\n\t\t\trole: \"toolResult\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\toutput: typeof resultOrError === \"string\" ? resultOrError : resultOrError.output,\n\t\t\tdetails: typeof resultOrError === \"string\" ? ({} as T) : resultOrError.details,\n\t\t\tisError,\n\t\t};\n\n\t\tresults.push(toolResultMessage);\n\t\tstream.push({ type: \"message_start\", message: toolResultMessage });\n\t\tstream.push({ type: \"message_end\", message: toolResultMessage });\n\t}\n\n\treturn results;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"agent.js","sourceRoot":"","sources":["../../src/agent/agent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9C,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAE5C,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAGzD,oDAAoD;AACpD,MAAM,UAAU,MAAM,CACrB,MAAmB,EACnB,OAAqB,EACrB,MAAoB,EACpB,MAAoB,EACpB,QAA8B;IAE9B,MAAM,MAAM,GAAG,IAAI,WAAW,CAC7B,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,WAAW,EACrC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC,CAC7D,CAAC;IAEF,uBAAuB;IACvB,CAAC,KAAK,IAAI,EAAE;QACX,kDAAkD;QAClD,MAAM,WAAW,GAA6B,EAAE,CAAC;QACjD,qCAAqC;QACrC,MAAM,QAAQ,GAAG,CAAC,GAAG,OAAO,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;QAC/C,WAAW,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAEzB,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,aAAa,EAAE,CA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AE,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC,CAAC;QACnE,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,aAAa,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC,CAAC;IAClE,CAAC;IAED,OAAO,OAAO,CAAC;AAChB,CAAC","sourcesContent":["import { EventStream } from \"../event-stream\";\nimport { streamSimple } from \"../stream.js\";\nimport type { AssistantMessage, Context, Message, ToolResultMessage, UserMessage } from \"../types.js\";\nimport { validateToolArguments } from \"../validation.js\";\nimport type { AgentContext, AgentEvent, AgentTool, AgentToolResult, PromptConfig } from \"./types\";\n\n// Main prompt function - returns a stream of events\nexport function prompt(\n\tprompt: UserMessage,\n\tcontext: AgentContext,\n\tconfig: PromptConfig,\n\tsignal?: AbortSignal,\n\tstreamFn?: typeof streamSimple,\n): EventStream<AgentEvent, AgentContext[\"messages\"]> {\n\tconst stream = new EventStream<AgentEvent, AgentContext[\"messages\"]>(\n\t\t(event) => event.type === \"agent_end\",\n\t\t(event) => (event.type === \"agent_end\" ? event.messages : []),\n\t);\n\n\t// Run the prompt async\n\t(async () => {\n\t\t// Track new messages generated during this prompt\n\t\tconst newMessages: AgentContext[\"messages\"] = [];\n\t\t// Create user message for the prompt\n\t\tconst messages = [...context.messages, prompt];\n\t\tnewMessages.push(prompt);\n\n\t\tstream.push({ type: \"agent_start\" });\n\t\tstream.push({ type: \"turn_start\" });\n\t\tstream.push({ type: \"message_start\", message: prompt });\n\t\tstream.push({ type: \"message_end\", message: prompt });\n\n\t\t// Update context with new messages\n\t\tconst currentContext: AgentContext = {\n\t\t\t...context,\n\t\t\tmessages,\n\t\t};\n\n\t\t// Keep looping while we have tool calls\n\t\tlet hasMoreToolCalls = true;\n\t\tlet firstTurn = true;\n\t\twhile (hasMoreToolCalls) {\n\t\t\tif (!firstTurn) {\n\t\t\t\tstream.push({ type: \"turn_start\" });\n\t\t\t} else {\n\t\t\t\tfirstTurn = false;\n\t\t\t}\n\t\t\t// Stream assistant response\n\t\t\tconst assistantMessage = await streamAssistantResponse(currentContext, config, signal, stream, streamFn);\n\t\t\tnewMessages.push(assistantMessage);\n\n\t\t\t// Check for tool calls\n\t\t\tconst toolCalls = assistantMessage.content.filter((c) => c.type === \"toolCall\");\n\t\t\thasMoreToolCalls = toolCalls.length > 0;\n\n\t\t\tconst toolResults: ToolResultMessage[] = [];\n\t\t\tif (hasMoreToolCalls) {\n\t\t\t\t// Execute tool calls\n\t\t\t\ttoolResults.push(...(await executeToolCalls(currentContext.tools, assistantMessage, signal, stream)));\n\t\t\t\tcurrentContext.messages.push(...toolResults);\n\t\t\t\tnewMessages.push(...toolResults);\n\t\t\t}\n\t\t\tstream.push({ type: \"turn_end\", assistantMessage, toolResults: toolResults });\n\t\t}\n\t\tstream.push({ type: \"agent_end\", messages: newMessages });\n\t\tstream.end(newMessages);\n\t})();\n\n\treturn stream;\n}\n\n// Helper functions\nasync function streamAssistantResponse(\n\tcontext: AgentContext,\n\tconfig: PromptConfig,\n\tsignal: AbortSignal | undefined,\n\tstream: EventStream<AgentEvent, AgentContext[\"messages\"]>,\n\tstreamFn?: typeof streamSimple,\n): Promise<AssistantMessage> {\n\t// Convert AgentContext to Context for streamSimple\n\t// Use a copy of messages to avoid mutating the original context\n\tconst processedMessages = config.preprocessor\n\t\t? await config.preprocessor(context.messages, signal)\n\t\t: [...context.messages];\n\tconst processedContext: Context = {\n\t\tsystemPrompt: context.systemPrompt,\n\t\tmessages: [...processedMessages].map((m) => {\n\t\t\tif (m.role === \"toolResult\") {\n\t\t\t\tconst { details, ...rest } = m;\n\t\t\t\treturn rest;\n\t\t\t} else {\n\t\t\t\treturn m;\n\t\t\t}\n\t\t}),\n\t\ttools: context.tools, // AgentTool extends Tool, so this works\n\t};\n\n\t// Use custom stream function if provided, otherwise use default streamSimple\n\tconst streamFunction = streamFn || streamSimple;\n\tconst response = await streamFunction(config.model, processedContext, { ...config, signal });\n\n\tlet partialMessage: AssistantMessage | null = null;\n\tlet addedPartial = false;\n\n\tfor await (const event of response) {\n\t\tswitch (event.type) {\n\t\t\tcase \"start\":\n\t\t\t\tpartialMessage = event.partial;\n\t\t\t\tcontext.messages.push(partialMessage);\n\t\t\t\taddedPartial = true;\n\t\t\t\tstream.push({ type: \"message_start\", message: { ...partialMessage } });\n\t\t\t\tbreak;\n\n\t\t\tcase \"text_start\":\n\t\t\tcase \"text_delta\":\n\t\t\tcase \"text_end\":\n\t\t\tcase \"thinking_start\":\n\t\t\tcase \"thinking_delta\":\n\t\t\tcase \"thinking_end\":\n\t\t\tcase \"toolcall_start\":\n\t\t\tcase \"toolcall_delta\":\n\t\t\tcase \"toolcall_end\":\n\t\t\t\tif (partialMessage) {\n\t\t\t\t\tpartialMessage = event.partial;\n\t\t\t\t\tcontext.messages[context.messages.length - 1] = partialMessage;\n\t\t\t\t\tstream.push({ type: \"message_update\", assistantMessageEvent: event, message: { ...partialMessage } });\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"done\":\n\t\t\tcase \"error\": {\n\t\t\t\tconst finalMessage = await response.result();\n\t\t\t\tif (addedPartial) {\n\t\t\t\t\tcontext.messages[context.messages.length - 1] = finalMessage;\n\t\t\t\t} else {\n\t\t\t\t\tcontext.messages.push(finalMessage);\n\t\t\t\t}\n\t\t\t\tstream.push({ type: \"message_end\", message: finalMessage });\n\t\t\t\treturn finalMessage;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn await response.result();\n}\n\nasync function executeToolCalls<T>(\n\ttools: AgentTool<any, T>[] | undefined,\n\tassistantMessage: AssistantMessage,\n\tsignal: AbortSignal | undefined,\n\tstream: EventStream<AgentEvent, Message[]>,\n): Promise<ToolResultMessage<T>[]> {\n\tconst toolCalls = assistantMessage.content.filter((c) => c.type === \"toolCall\");\n\tconst results: ToolResultMessage<any>[] = [];\n\n\tfor (const toolCall of toolCalls) {\n\t\tconst tool = tools?.find((t) => t.name === toolCall.name);\n\n\t\tstream.push({\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\targs: toolCall.arguments,\n\t\t});\n\n\t\tlet resultOrError: AgentToolResult<T> | string;\n\t\tlet isError = false;\n\n\t\ttry {\n\t\t\tif (!tool) throw new Error(`Tool ${toolCall.name} not found`);\n\n\t\t\t// Validate arguments using shared validation function\n\t\t\tconst validatedArgs = validateToolArguments(tool, toolCall);\n\n\t\t\t// Execute with validated, typed arguments\n\t\t\tresultOrError = await tool.execute(toolCall.id, validatedArgs, signal);\n\t\t} catch (e) {\n\t\t\tresultOrError = e instanceof Error ? e.message : String(e);\n\t\t\tisError = true;\n\t\t}\n\n\t\tstream.push({\n\t\t\ttype: \"tool_execution_end\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\tresult: resultOrError,\n\t\t\tisError,\n\t\t});\n\n\t\tconst toolResultMessage: ToolResultMessage<T> = {\n\t\t\trole: \"toolResult\",\n\t\t\ttoolCallId: toolCall.id,\n\t\t\ttoolName: toolCall.name,\n\t\t\toutput: typeof resultOrError === \"string\" ? resultOrError : resultOrError.output,\n\t\t\tdetails: typeof resultOrError === \"string\" ? ({} as T) : resultOrError.details,\n\t\t\tisError,\n\t\t};\n\n\t\tresults.push(toolResultMessage);\n\t\tstream.push({ type: \"message_start\", message: toolResultMessage });\n\t\tstream.push({ type: \"message_end\", message: toolResultMessage });\n\t}\n\n\treturn results;\n}\n"]}
|
|
@@ -1,16 +1,11 @@
|
|
|
1
|
-
import { z } from "zod";
|
|
2
1
|
import type { AgentTool } from "../../agent";
|
|
3
2
|
export interface CalculateResult {
|
|
4
3
|
output: string;
|
|
5
4
|
details: undefined;
|
|
6
5
|
}
|
|
7
6
|
export declare function calculate(expression: string): CalculateResult;
|
|
8
|
-
declare const calculateSchema:
|
|
9
|
-
expression:
|
|
10
|
-
}, "strip", z.ZodTypeAny, {
|
|
11
|
-
expression: string;
|
|
12
|
-
}, {
|
|
13
|
-
expression: string;
|
|
7
|
+
declare const calculateSchema: import("@sinclair/typebox").TObject<{
|
|
8
|
+
expression: import("@sinclair/typebox").TString;
|
|
14
9
|
}>;
|
|
15
10
|
export declare const calculateTool: AgentTool<typeof calculateSchema, undefined>;
|
|
16
11
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"calculate.d.ts","sourceRoot":"","sources":["../../../src/agent/tools/calculate.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"calculate.d.ts","sourceRoot":"","sources":["../../../src/agent/tools/calculate.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE7C,MAAM,WAAW,eAAe;IAC/B,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,SAAS,CAAC;CACnB;AAED,wBAAgB,SAAS,CAAC,UAAU,EAAE,MAAM,GAAG,eAAe,CAO7D;AAED,QAAA,MAAM,eAAe;;EAEnB,CAAC;AAIH,eAAO,MAAM,aAAa,EAAE,SAAS,CAAC,OAAO,eAAe,EAAE,SAAS,CAQtE,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Type } from "@sinclair/typebox";
|
|
2
2
|
export function calculate(expression) {
|
|
3
3
|
try {
|
|
4
4
|
const result = new Function("return " + expression)();
|
|
@@ -8,8 +8,8 @@ export function calculate(expression) {
|
|
|
8
8
|
throw new Error(e.message || String(e));
|
|
9
9
|
}
|
|
10
10
|
}
|
|
11
|
-
const calculateSchema =
|
|
12
|
-
expression:
|
|
11
|
+
const calculateSchema = Type.Object({
|
|
12
|
+
expression: Type.String({ description: "The mathematical expression to evaluate" }),
|
|
13
13
|
});
|
|
14
14
|
export const calculateTool = {
|
|
15
15
|
label: "Calculator",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"calculate.js","sourceRoot":"","sources":["../../../src/agent/tools/calculate.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"calculate.js","sourceRoot":"","sources":["../../../src/agent/tools/calculate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAQtD,MAAM,UAAU,SAAS,CAAC,UAAkB;IAC3C,IAAI,CAAC;QACJ,MAAM,MAAM,GAAG,IAAI,QAAQ,CAAC,SAAS,GAAG,UAAU,CAAC,EAAE,CAAC;QACtD,OAAO,EAAE,MAAM,EAAE,GAAG,UAAU,MAAM,MAAM,EAAE,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;IACpE,CAAC;IAAC,OAAO,CAAM,EAAE,CAAC;QACjB,MAAM,IAAI,KAAK,CAAC,CAAC,CAAC,OAAO,IAAI,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;IACzC,CAAC;AACF,CAAC;AAED,MAAM,eAAe,GAAG,IAAI,CAAC,MAAM,CAAC;IACnC,UAAU,EAAE,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,yCAAyC,EAAE,CAAC;CACnF,CAAC,CAAC;AAIH,MAAM,CAAC,MAAM,aAAa,GAAiD;IAC1E,KAAK,EAAE,YAAY;IACnB,IAAI,EAAE,WAAW;IACjB,WAAW,EAAE,mCAAmC;IAChD,UAAU,EAAE,eAAe;IAC3B,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,EAAE;QACpC,OAAO,SAAS,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IACnC,CAAC;CACD,CAAC","sourcesContent":["import { type Static, Type } from \"@sinclair/typebox\";\nimport type { AgentTool } from \"../../agent\";\n\nexport interface CalculateResult {\n\toutput: string;\n\tdetails: undefined;\n}\n\nexport function calculate(expression: string): CalculateResult {\n\ttry {\n\t\tconst result = new Function(\"return \" + expression)();\n\t\treturn { output: `${expression} = ${result}`, details: undefined };\n\t} catch (e: any) {\n\t\tthrow new Error(e.message || String(e));\n\t}\n}\n\nconst calculateSchema = Type.Object({\n\texpression: Type.String({ description: \"The mathematical expression to evaluate\" }),\n});\n\ntype CalculateParams = Static<typeof calculateSchema>;\n\nexport const calculateTool: AgentTool<typeof calculateSchema, undefined> = {\n\tlabel: \"Calculator\",\n\tname: \"calculate\",\n\tdescription: \"Evaluate mathematical expressions\",\n\tparameters: calculateSchema,\n\texecute: async (_toolCallId, args) => {\n\t\treturn calculate(args.expression);\n\t},\n};\n"]}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { z } from "zod";
|
|
2
1
|
import type { AgentTool } from "../../agent";
|
|
3
2
|
import type { AgentToolResult } from "../types";
|
|
4
3
|
export interface GetCurrentTimeResult extends AgentToolResult<{
|
|
@@ -6,12 +5,8 @@ export interface GetCurrentTimeResult extends AgentToolResult<{
|
|
|
6
5
|
}> {
|
|
7
6
|
}
|
|
8
7
|
export declare function getCurrentTime(timezone?: string): Promise<GetCurrentTimeResult>;
|
|
9
|
-
declare const getCurrentTimeSchema:
|
|
10
|
-
timezone:
|
|
11
|
-
}, "strip", z.ZodTypeAny, {
|
|
12
|
-
timezone?: string | undefined;
|
|
13
|
-
}, {
|
|
14
|
-
timezone?: string | undefined;
|
|
8
|
+
declare const getCurrentTimeSchema: import("@sinclair/typebox").TObject<{
|
|
9
|
+
timezone: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TString>;
|
|
15
10
|
}>;
|
|
16
11
|
export declare const getCurrentTimeTool: AgentTool<typeof getCurrentTimeSchema, {
|
|
17
12
|
utcTimestamp: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"get-current-time.d.ts","sourceRoot":"","sources":["../../../src/agent/tools/get-current-time.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"get-current-time.d.ts","sourceRoot":"","sources":["../../../src/agent/tools/get-current-time.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAEhD,MAAM,WAAW,oBAAqB,SAAQ,eAAe,CAAC;IAAE,YAAY,EAAE,MAAM,CAAA;CAAE,CAAC;CAAG;AAE1F,wBAAsB,cAAc,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAoBrF;AAED,QAAA,MAAM,oBAAoB;;EAIxB,CAAC;AAIH,eAAO,MAAM,kBAAkB,EAAE,SAAS,CAAC,OAAO,oBAAoB,EAAE;IAAE,YAAY,EAAE,MAAM,CAAA;CAAE,CAQ/F,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Type } from "@sinclair/typebox";
|
|
2
2
|
export async function getCurrentTime(timezone) {
|
|
3
3
|
const date = new Date();
|
|
4
4
|
if (timezone) {
|
|
@@ -21,8 +21,8 @@ export async function getCurrentTime(timezone) {
|
|
|
21
21
|
details: { utcTimestamp: date.getTime() },
|
|
22
22
|
};
|
|
23
23
|
}
|
|
24
|
-
const getCurrentTimeSchema =
|
|
25
|
-
timezone:
|
|
24
|
+
const getCurrentTimeSchema = Type.Object({
|
|
25
|
+
timezone: Type.Optional(Type.String({ description: "Optional timezone (e.g., 'America/New_York', 'Europe/London')" })),
|
|
26
26
|
});
|
|
27
27
|
export const getCurrentTimeTool = {
|
|
28
28
|
label: "Current Time",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"get-current-time.js","sourceRoot":"","sources":["../../../src/agent/tools/get-current-time.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"get-current-time.js","sourceRoot":"","sources":["../../../src/agent/tools/get-current-time.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAMtD,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,QAAiB;IACrD,MAAM,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC;IACxB,IAAI,QAAQ,EAAE,CAAC;QACd,IAAI,CAAC;YACJ,OAAO;gBACN,MAAM,EAAE,IAAI,CAAC,cAAc,CAAC,OAAO,EAAE;oBACpC,QAAQ,EAAE,QAAQ;oBAClB,SAAS,EAAE,MAAM;oBACjB,SAAS,EAAE,MAAM;iBACjB,CAAC;gBACF,OAAO,EAAE,EAAE,YAAY,EAAE,IAAI,CAAC,OAAO,EAAE,EAAE;aACzC,CAAC;QACH,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACZ,MAAM,IAAI,KAAK,CAAC,qBAAqB,QAAQ,uBAAuB,IAAI,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;QAC3F,CAAC;IACF,CAAC;IACD,OAAO;QACN,MAAM,EAAE,IAAI,CAAC,cAAc,CAAC,OAAO,EAAE,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC;QAC9E,OAAO,EAAE,EAAE,YAAY,EAAE,IAAI,CAAC,OAAO,EAAE,EAAE;KACzC,CAAC;AACH,CAAC;AAED,MAAM,oBAAoB,GAAG,IAAI,CAAC,MAAM,CAAC;IACxC,QAAQ,EAAE,IAAI,CAAC,QAAQ,CACtB,IAAI,CAAC,MAAM,CAAC,EAAE,WAAW,EAAE,+DAA+D,EAAE,CAAC,CAC7F;CACD,CAAC,CAAC;AAIH,MAAM,CAAC,MAAM,kBAAkB,GAAqE;IACnG,KAAK,EAAE,cAAc;IACrB,IAAI,EAAE,kBAAkB;IACxB,WAAW,EAAE,+BAA+B;IAC5C,UAAU,EAAE,oBAAoB;IAChC,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,EAAE;QACpC,OAAO,cAAc,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACtC,CAAC;CACD,CAAC","sourcesContent":["import { type Static, Type } from \"@sinclair/typebox\";\nimport type { AgentTool } from \"../../agent\";\nimport type { AgentToolResult } from \"../types\";\n\nexport interface GetCurrentTimeResult extends AgentToolResult<{ utcTimestamp: number }> {}\n\nexport async function getCurrentTime(timezone?: string): Promise<GetCurrentTimeResult> {\n\tconst date = new Date();\n\tif (timezone) {\n\t\ttry {\n\t\t\treturn {\n\t\t\t\toutput: date.toLocaleString(\"en-US\", {\n\t\t\t\t\ttimeZone: timezone,\n\t\t\t\t\tdateStyle: \"full\",\n\t\t\t\t\ttimeStyle: \"long\",\n\t\t\t\t}),\n\t\t\t\tdetails: { utcTimestamp: date.getTime() },\n\t\t\t};\n\t\t} catch (e) {\n\t\t\tthrow new Error(`Invalid timezone: ${timezone}. Current UTC time: ${date.toISOString()}`);\n\t\t}\n\t}\n\treturn {\n\t\toutput: date.toLocaleString(\"en-US\", { dateStyle: \"full\", timeStyle: \"long\" }),\n\t\tdetails: { utcTimestamp: date.getTime() },\n\t};\n}\n\nconst getCurrentTimeSchema = Type.Object({\n\ttimezone: Type.Optional(\n\t\tType.String({ description: \"Optional timezone (e.g., 'America/New_York', 'Europe/London')\" }),\n\t),\n});\n\ntype GetCurrentTimeParams = Static<typeof getCurrentTimeSchema>;\n\nexport const getCurrentTimeTool: AgentTool<typeof getCurrentTimeSchema, { utcTimestamp: number }> = {\n\tlabel: \"Current Time\",\n\tname: \"get_current_time\",\n\tdescription: \"Get the current date and time\",\n\tparameters: getCurrentTimeSchema,\n\texecute: async (_toolCallId, args) => {\n\t\treturn getCurrentTime(args.timezone);\n\t},\n};\n"]}
|
package/dist/agent/types.d.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { Static, TSchema } from "@sinclair/typebox";
|
|
2
2
|
import type { AssistantMessage, AssistantMessageEvent, Message, Model, SimpleStreamOptions, Tool, ToolResultMessage } from "../types.js";
|
|
3
3
|
export interface AgentToolResult<T> {
|
|
4
4
|
output: string;
|
|
5
5
|
details: T;
|
|
6
6
|
}
|
|
7
|
-
export interface AgentTool<TParameters extends
|
|
7
|
+
export interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any> extends Tool<TParameters> {
|
|
8
8
|
label: string;
|
|
9
|
-
execute: (toolCallId: string, params:
|
|
9
|
+
execute: (toolCallId: string, params: Static<TParameters>, signal?: AbortSignal) => Promise<AgentToolResult<TDetails>>;
|
|
10
10
|
}
|
|
11
11
|
export interface AgentContext {
|
|
12
12
|
systemPrompt: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/agent/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/agent/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,KAAK,EACX,gBAAgB,EAChB,qBAAqB,EACrB,OAAO,EACP,KAAK,EACL,mBAAmB,EACnB,IAAI,EACJ,iBAAiB,EACjB,MAAM,aAAa,CAAC;AAErB,MAAM,WAAW,eAAe,CAAC,CAAC;IAEjC,MAAM,EAAE,MAAM,CAAC;IAEf,OAAO,EAAE,CAAC,CAAC;CACX;AAGD,MAAM,WAAW,SAAS,CAAC,WAAW,SAAS,OAAO,GAAG,OAAO,EAAE,QAAQ,GAAG,GAAG,CAAE,SAAQ,IAAI,CAAC,WAAW,CAAC;IAE1G,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,CACR,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,MAAM,CAAC,WAAW,CAAC,EAC3B,MAAM,CAAC,EAAE,WAAW,KAChB,OAAO,CAAC,eAAe,CAAC,QAAQ,CAAC,CAAC,CAAC;CACxC;AAGD,MAAM,WAAW,YAAY;IAC5B,YAAY,EAAE,MAAM,CAAC;IACrB,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,KAAK,CAAC,EAAE,SAAS,CAAC,GAAG,CAAC,EAAE,CAAC;CACzB;AAGD,MAAM,MAAM,UAAU,GAEnB;IAAE,IAAI,EAAE,a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ings":"","sourcesContent":["import type {
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/agent/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Static, TSchema } from \"@sinclair/typebox\";\nimport type {\n\tAssistantMessage,\n\tAssistantMessageEvent,\n\tMessage,\n\tModel,\n\tSimpleStreamOptions,\n\tTool,\n\tToolResultMessage,\n} from \"../types.js\";\n\nexport interface AgentToolResult<T> {\n\t// Output of the tool to be given to the LLM in ToolResultMessage.content\n\toutput: string;\n\t// Details to be displayed in a UI or loggedty\n\tdetails: T;\n}\n\n// AgentTool extends Tool but adds the execute function\nexport interface AgentTool<TParameters extends TSchema = TSchema, TDetails = any> extends Tool<TParameters> {\n\t// A human-readable label for the tool to be displayed in UI\n\tlabel: string;\n\texecute: (\n\t\ttoolCallId: string,\n\t\tparams: Static<TParameters>,\n\t\tsignal?: AbortSignal,\n\t) => Promise<AgentToolResult<TDetails>>;\n}\n\n// AgentContext is like Context but uses AgentTool\nexport interface AgentContext {\n\tsystemPrompt: string;\n\tmessages: Message[];\n\ttools?: AgentTool<any>[];\n}\n\n// Event types\nexport type AgentEvent =\n\t// Emitted when the agent starts. An agent can emit multiple turns\n\t| { type: \"agent_start\" }\n\t// Emitted when a turn starts. A turn can emit an optional user message (initial prompt), an assistant message (response) and multiple tool result messages\n\t| { type: \"turn_start\" }\n\t// Emitted when a user, assistant or tool result message starts\n\t| { type: \"message_start\"; message: Message }\n\t// Emitted when an asssitant messages is updated due to streaming\n\t| { type: \"message_update\"; assistantMessageEvent: AssistantMessageEvent; message: AssistantMessage }\n\t// Emitted when a user, assistant or tool result message is complete\n\t| { type: \"message_end\"; message: Message }\n\t// Emitted when a tool execution starts\n\t| { type: \"tool_execution_start\"; toolCallId: string; toolName: string; args: any }\n\t// Emitted when a tool execution completes\n\t| {\n\t\t\ttype: \"tool_execution_end\";\n\t\t\ttoolCallId: string;\n\t\t\ttoolName: string;\n\t\t\tresult: AgentToolResult<any> | string;\n\t\t\tisError: boolean;\n\t }\n\t// Emitted when a full turn completes\n\t| { type: \"turn_end\"; assistantMessage: AssistantMessage; toolResults: ToolResultMessage[] }\n\t// Emitted when the agent has completed all its turns. All messages from every turn are\n\t// contained in messages, which can be appended to the context\n\t| { type: \"agent_end\"; messages: AgentContext[\"messages\"] };\n\n// Configuration for prompt execution\nexport interface PromptConfig extends SimpleStreamOptions {\n\tmodel: Model<any>;\n\tpreprocessor?: (messages: AgentContext[\"messages\"], abortSignal?: AbortSignal) => Promise<AgentContext[\"messages\"]>;\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { type Static, Type } from "@sinclair/typebox";
|
|
2
2
|
export * from "./agent/index.js";
|
|
3
3
|
export * from "./models.js";
|
|
4
4
|
export * from "./providers/anthropic.js";
|
|
@@ -6,5 +6,6 @@ export * from "./providers/google.js";
|
|
|
6
6
|
export * from "./providers/openai-completions.js";
|
|
7
7
|
export * from "./providers/openai-responses.js";
|
|
8
8
|
export * from "./stream.js";
|
|
9
|
+
export * from "./typebox-helpers.js";
|
|
9
10
|
export * from "./types.js";
|
|
10
11
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACtD,cAAc,kBAAkB,CAAC;AACjC,cAAc,aAAa,CAAC;AAC5B,cAAc,0BAA0B,CAAC;AACzC,cAAc,uBAAuB,CAAC;AACtC,cAAc,mCAAmC,CAAC;AAClD,cAAc,iCAAiC,CAAC;AAChD,cAAc,aAAa,CAAC;AAC5B,cAAc,sBAAsB,CAAC;AACrC,cAAc,YAAY,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { Type } from "@sinclair/typebox";
|
|
2
2
|
export * from "./agent/index.js";
|
|
3
3
|
export * from "./models.js";
|
|
4
4
|
export * from "./providers/anthropic.js";
|
|
@@ -6,5 +6,6 @@ export * from "./providers/google.js";
|
|
|
6
6
|
export * from "./providers/openai-completions.js";
|
|
7
7
|
export * from "./providers/openai-responses.js";
|
|
8
8
|
export * from "./stream.js";
|
|
9
|
+
export * from "./typebox-helpers.js";
|
|
9
10
|
export * from "./types.js";
|
|
10
11
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACtD,cAAc,kBAAkB,CAAC;AACjC,cAAc,aAAa,CAAC;AAC5B,cAAc,0BAA0B,CAAC;AACzC,cAAc,uBAAuB,CAAC;AACtC,cAAc,mCAAmC,CAAC;AAClD,cAAc,iCAAiC,CAAC;AAChD,cAAc,aAAa,CAAC;AAC5B,cAAc,sBAAsB,CAAC;AACrC,cAAc,YAAY,CAAC","sourcesContent":["export { type Static, Type } from \"@sinclair/typebox\";\nexport * from \"./agent/index.js\";\nexport * from \"./models.js\";\nexport * from \"./providers/anthropic.js\";\nexport * from \"./providers/google.js\";\nexport * from \"./providers/openai-completions.js\";\nexport * from \"./providers/openai-responses.js\";\nexport * from \"./stream.js\";\nexport * from \"./typebox-helpers.js\";\nexport * from \"./types.js\";\n"]}
|
|
@@ -3074,7 +3074,7 @@ export declare const MODELS: {
|
|
|
3074
3074
|
contextWindow: number;
|
|
3075
3075
|
maxTokens: number;
|
|
3076
3076
|
};
|
|
3077
|
-
readonly "mistralai/mistral-7b-instruct
|
|
3077
|
+
readonly "mistralai/mistral-7b-instruct:free": {
|
|
3078
3078
|
id: string;
|
|
3079
3079
|
name: string;
|
|
3080
3080
|
api: "openai-completions";
|
|
@@ -3091,7 +3091,7 @@ export declare const MODELS: {
|
|
|
3091
3091
|
contextWindow: number;
|
|
3092
3092
|
maxTokens: number;
|
|
3093
3093
|
};
|
|
3094
|
-
readonly "mistralai/mistral-7b-instruct
|
|
3094
|
+
readonly "mistralai/mistral-7b-instruct": {
|
|
3095
3095
|
id: string;
|
|
3096
3096
|
name: string;
|
|
3097
3097
|
api: "openai-completions";
|
|
@@ -3108,7 +3108,7 @@ export declare const MODELS: {
|
|
|
3108
3108
|
contextWindow: number;
|
|
3109
3109
|
maxTokens: number;
|
|
3110
3110
|
};
|
|
3111
|
-
readonly "mistralai/mistral-7b-instruct": {
|
|
3111
|
+
readonly "mistralai/mistral-7b-instruct-v0.3": {
|
|
3112
3112
|
id: string;
|
|
3113
3113
|
name: string;
|
|
3114
3114
|
api: "openai-completions";
|
|
@@ -3159,7 +3159,7 @@ export declare const MODELS: {
|
|
|
3159
3159
|
contextWindow: number;
|
|
3160
3160
|
maxTokens: number;
|
|
3161
3161
|
};
|
|
3162
|
-
readonly "meta-llama/llama-3-
|
|
3162
|
+
readonly "meta-llama/llama-3-8b-instruct": {
|
|
3163
3163
|
id: string;
|
|
3164
3164
|
name: string;
|
|
3165
3165
|
api: "openai-completions";
|
|
@@ -3176,7 +3176,7 @@ export declare const MODELS: {
|
|
|
3176
3176
|
contextWindow: number;
|
|
3177
3177
|
maxTokens: number;
|
|
3178
3178
|
};
|
|
3179
|
-
readonly "meta-llama/llama-3-
|
|
3179
|
+
readonly "meta-llama/llama-3-70b-instruct": {
|
|
3180
3180
|
id: string;
|
|
3181
3181
|
name: string;
|
|
3182
3182
|
api: "openai-completions";
|
|
@@ -3295,7 +3295,7 @@ export declare const MODELS: {
|
|
|
3295
3295
|
contextWindow: number;
|
|
3296
3296
|
maxTokens: number;
|
|
3297
3297
|
};
|
|
3298
|
-
readonly "mistralai/mistral-
|
|
3298
|
+
readonly "mistralai/mistral-small": {
|
|
3299
3299
|
id: string;
|
|
3300
3300
|
name: string;
|
|
3301
3301
|
api: "openai-completions";
|
|
@@ -3312,7 +3312,7 @@ export declare const MODELS: {
|
|
|
3312
3312
|
contextWindow: number;
|
|
3313
3313
|
maxTokens: number;
|
|
3314
3314
|
};
|
|
3315
|
-
readonly "mistralai/mistral-
|
|
3315
|
+
readonly "mistralai/mistral-tiny": {
|
|
3316
3316
|
id: string;
|
|
3317
3317
|
name: string;
|
|
3318
3318
|
api: "openai-completions";
|