@micdrop/openai 1.0.0 → 1.0.1
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 +11 -2
- package/dist/index.d.mts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +33 -12
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +33 -12
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -106,7 +106,7 @@ The OpenAI Agent supports adding and removing custom tools to extend its capabil
|
|
|
106
106
|
|
|
107
107
|
### Adding Tools
|
|
108
108
|
|
|
109
|
-
Use `addTool()` to add custom functions that the agent can call during conversations:
|
|
109
|
+
Use `addTool(tool: Tool)` to add custom functions that the agent can call during conversations:
|
|
110
110
|
|
|
111
111
|
```typescript
|
|
112
112
|
import { z } from 'zod'
|
|
@@ -160,13 +160,22 @@ agent.addTool({
|
|
|
160
160
|
|
|
161
161
|
### Removing Tools
|
|
162
162
|
|
|
163
|
-
Use `removeTool()` to remove tools by name:
|
|
163
|
+
Use `removeTool(name: string)` to remove tools by name:
|
|
164
164
|
|
|
165
165
|
```typescript
|
|
166
166
|
// Remove a specific tool
|
|
167
167
|
agent.removeTool('get_time')
|
|
168
168
|
```
|
|
169
169
|
|
|
170
|
+
### Getting Tools
|
|
171
|
+
|
|
172
|
+
Use `getTool(name: string)` to retrieve a tool by name:
|
|
173
|
+
|
|
174
|
+
```typescript
|
|
175
|
+
// Get a specific tool (undefined if not found)
|
|
176
|
+
const tool = agent.getTool('get_time')
|
|
177
|
+
```
|
|
178
|
+
|
|
170
179
|
## Advanced Features
|
|
171
180
|
|
|
172
181
|
### Auto End Call
|
package/dist/index.d.mts
CHANGED
|
@@ -8,6 +8,7 @@ interface Tool<Schema extends z.ZodObject = z.ZodObject> {
|
|
|
8
8
|
description: string;
|
|
9
9
|
parameters?: Schema;
|
|
10
10
|
callback: (input: z.infer<Schema>) => any | Promise<any>;
|
|
11
|
+
skipAnswer?: boolean;
|
|
11
12
|
}
|
|
12
13
|
|
|
13
14
|
interface OpenaiAgentOptions extends AgentOptions {
|
|
@@ -31,6 +32,7 @@ declare class OpenaiAgent extends Agent<OpenaiAgentOptions> {
|
|
|
31
32
|
private generateAnswer;
|
|
32
33
|
addTool<Schema extends z.ZodObject>(tool: Tool<Schema>): void;
|
|
33
34
|
removeTool(name: string): void;
|
|
35
|
+
getTool(name: string): Tool | undefined;
|
|
34
36
|
private getDefaultTools;
|
|
35
37
|
private executeTool;
|
|
36
38
|
cancel(): void;
|
package/dist/index.d.ts
CHANGED
|
@@ -8,6 +8,7 @@ interface Tool<Schema extends z.ZodObject = z.ZodObject> {
|
|
|
8
8
|
description: string;
|
|
9
9
|
parameters?: Schema;
|
|
10
10
|
callback: (input: z.infer<Schema>) => any | Promise<any>;
|
|
11
|
+
skipAnswer?: boolean;
|
|
11
12
|
}
|
|
12
13
|
|
|
13
14
|
interface OpenaiAgentOptions extends AgentOptions {
|
|
@@ -31,6 +32,7 @@ declare class OpenaiAgent extends Agent<OpenaiAgentOptions> {
|
|
|
31
32
|
private generateAnswer;
|
|
32
33
|
addTool<Schema extends z.ZodObject>(tool: Tool<Schema>): void;
|
|
33
34
|
removeTool(name: string): void;
|
|
35
|
+
getTool(name: string): Tool | undefined;
|
|
34
36
|
private getDefaultTools;
|
|
35
37
|
private executeTool;
|
|
36
38
|
cancel(): void;
|
package/dist/index.js
CHANGED
|
@@ -63,11 +63,11 @@ function createToolCallOutput(toolCall, args) {
|
|
|
63
63
|
var DEFAULT_MODEL = "gpt-4o";
|
|
64
64
|
var DEFAULT_MAX_CALLS = 5;
|
|
65
65
|
var AUTO_END_CALL_TOOL_NAME = "end_call";
|
|
66
|
-
var AUTO_END_CALL_PROMPT = "
|
|
66
|
+
var AUTO_END_CALL_PROMPT = "Call this tool only if user asks to end the call";
|
|
67
67
|
var AUTO_SEMANTIC_TURN_TOOL_NAME = "semantic_turn";
|
|
68
|
-
var AUTO_SEMANTIC_TURN_PROMPT = "
|
|
68
|
+
var AUTO_SEMANTIC_TURN_PROMPT = "Call this tool only if last user message is obviously an incomplete sentence that you need to wait for the end before answering";
|
|
69
69
|
var AUTO_IGNORE_USER_NOISE_TOOL_NAME = "ignore_user_noise";
|
|
70
|
-
var AUTO_IGNORE_USER_NOISE_PROMPT = `
|
|
70
|
+
var AUTO_IGNORE_USER_NOISE_PROMPT = `Call this tool only if last user message is just an interjection or a sound that expresses emotion, hesitation, or reaction (ex: "Uh", "Ahem", "Hmm", "Ah") but doesn't carry any clear meaning like agreeing, refusing, or commanding`;
|
|
71
71
|
var OpenaiAgent = class extends import_server.Agent {
|
|
72
72
|
constructor(options) {
|
|
73
73
|
super(options);
|
|
@@ -90,7 +90,7 @@ var OpenaiAgent = class extends import_server.Agent {
|
|
|
90
90
|
async generateAnswer(stream, textPromise, callCount = 0, toolInputs) {
|
|
91
91
|
if (callCount >= (this.options.maxCalls || DEFAULT_MAX_CALLS)) {
|
|
92
92
|
console.error("[OpenaiAgent] Max calls reached");
|
|
93
|
-
textPromise.
|
|
93
|
+
textPromise.resolve("");
|
|
94
94
|
return;
|
|
95
95
|
}
|
|
96
96
|
this.abortController = new AbortController();
|
|
@@ -119,6 +119,8 @@ var OpenaiAgent = class extends import_server.Agent {
|
|
|
119
119
|
{ signal }
|
|
120
120
|
);
|
|
121
121
|
const toolOutputs = [];
|
|
122
|
+
let hasAnswer = false;
|
|
123
|
+
let skipAnswer = false;
|
|
122
124
|
for await (const event of response) {
|
|
123
125
|
switch (event.type) {
|
|
124
126
|
case "response.output_text.delta":
|
|
@@ -129,28 +131,33 @@ var OpenaiAgent = class extends import_server.Agent {
|
|
|
129
131
|
this.addAssistantMessage(event.text);
|
|
130
132
|
stream.end();
|
|
131
133
|
textPromise.resolve(event.text);
|
|
134
|
+
hasAnswer = true;
|
|
132
135
|
break;
|
|
133
136
|
case "response.output_item.done":
|
|
134
137
|
if (event.item.type === "function_call") {
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
+
const result = await this.executeTool(event.item);
|
|
139
|
+
toolOutputs.push(result.toolCall, result.toolCallOutput);
|
|
140
|
+
if (result.skipAnswer) {
|
|
141
|
+
skipAnswer = true;
|
|
142
|
+
}
|
|
138
143
|
}
|
|
139
144
|
break;
|
|
140
145
|
default:
|
|
141
146
|
break;
|
|
142
147
|
}
|
|
143
148
|
}
|
|
144
|
-
if (toolOutputs.length > 0) {
|
|
149
|
+
if (toolOutputs.length > 0 && !hasAnswer && !skipAnswer) {
|
|
145
150
|
await this.generateAnswer(
|
|
146
151
|
stream,
|
|
147
152
|
textPromise,
|
|
148
153
|
callCount + 1,
|
|
149
154
|
toolOutputs
|
|
150
155
|
);
|
|
156
|
+
} else {
|
|
157
|
+
textPromise.resolve("");
|
|
151
158
|
}
|
|
152
159
|
} catch (error) {
|
|
153
|
-
textPromise.
|
|
160
|
+
textPromise.resolve("");
|
|
154
161
|
if (!(error instanceof import_openai.default.APIUserAbortError)) {
|
|
155
162
|
console.error("[OpenaiAgent] Error answering:", error);
|
|
156
163
|
}
|
|
@@ -162,6 +169,9 @@ var OpenaiAgent = class extends import_server.Agent {
|
|
|
162
169
|
removeTool(name) {
|
|
163
170
|
this.tools = this.tools.filter((tool) => tool.name !== name);
|
|
164
171
|
}
|
|
172
|
+
getTool(name) {
|
|
173
|
+
return this.tools.find((tool) => tool.name === name);
|
|
174
|
+
}
|
|
165
175
|
getDefaultTools() {
|
|
166
176
|
const tools = [];
|
|
167
177
|
if (this.options.autoEndCall) {
|
|
@@ -175,6 +185,7 @@ var OpenaiAgent = class extends import_server.Agent {
|
|
|
175
185
|
tools.push({
|
|
176
186
|
name: AUTO_SEMANTIC_TURN_TOOL_NAME,
|
|
177
187
|
description: typeof this.options.autoSemanticTurn === "string" ? this.options.autoSemanticTurn : AUTO_SEMANTIC_TURN_PROMPT,
|
|
188
|
+
skipAnswer: true,
|
|
178
189
|
callback: () => this.skipAnswer()
|
|
179
190
|
});
|
|
180
191
|
}
|
|
@@ -182,6 +193,7 @@ var OpenaiAgent = class extends import_server.Agent {
|
|
|
182
193
|
tools.push({
|
|
183
194
|
name: AUTO_IGNORE_USER_NOISE_TOOL_NAME,
|
|
184
195
|
description: typeof this.options.autoIgnoreUserNoise === "string" ? this.options.autoIgnoreUserNoise : AUTO_IGNORE_USER_NOISE_PROMPT,
|
|
196
|
+
skipAnswer: true,
|
|
185
197
|
callback: () => this.cancelLastUserMessage()
|
|
186
198
|
});
|
|
187
199
|
}
|
|
@@ -189,17 +201,26 @@ var OpenaiAgent = class extends import_server.Agent {
|
|
|
189
201
|
}
|
|
190
202
|
async executeTool(toolCall) {
|
|
191
203
|
try {
|
|
192
|
-
const tool = this.
|
|
204
|
+
const tool = this.getTool(toolCall.name);
|
|
193
205
|
if (!tool) {
|
|
194
206
|
throw new Error(`Tool not found "${toolCall.name}"`);
|
|
195
207
|
}
|
|
196
208
|
this.log("Executing tool:", toolCall.name, toolCall.arguments);
|
|
197
209
|
const args = JSON.parse(toolCall.arguments);
|
|
198
210
|
const result = await tool.callback(args);
|
|
199
|
-
return
|
|
211
|
+
return {
|
|
212
|
+
toolCall,
|
|
213
|
+
toolCallOutput: createToolCallOutput(toolCall, result || {}),
|
|
214
|
+
skipAnswer: tool.skipAnswer
|
|
215
|
+
};
|
|
200
216
|
} catch (error) {
|
|
201
217
|
console.error("[OpenaiAgent] Error executing tool:", error);
|
|
202
|
-
return
|
|
218
|
+
return {
|
|
219
|
+
toolCall,
|
|
220
|
+
toolCallOutput: createToolCallOutput(toolCall, {
|
|
221
|
+
error: error.message
|
|
222
|
+
})
|
|
223
|
+
};
|
|
203
224
|
}
|
|
204
225
|
}
|
|
205
226
|
cancel() {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/OpenaiAgent.ts","../src/tools.ts","../src/OpenaiSTT.ts"],"sourcesContent":["export * from './OpenaiAgent'\nexport * from './OpenaiSTT'\n","import { Agent, AgentOptions, TextPromise } from '@micdrop/server'\nimport OpenAI from 'openai'\nimport { PassThrough } from 'stream'\nimport { z } from 'zod'\nimport {\n createToolCallOutput,\n createToolSchema,\n Tool,\n ToolCall,\n ToolCallOutput,\n} from './tools'\n\nexport interface OpenaiAgentOptions extends AgentOptions {\n apiKey: string\n model?: string\n maxCalls?: number\n settings?: Omit<\n OpenAI.Responses.ResponseCreateParamsStreaming,\n 'input' | 'model'\n >\n\n // Enable auto ending of the call when user asks to end the call\n // You can provide a custom prompt to use instead of the default one by passing a string\n autoEndCall?: boolean | string\n\n // Enable detection of an incomplete sentence, and skip the answer (assistant waits)\n // You can provide a custom prompt to use instead of the default one by passing a string\n autoSemanticTurn?: boolean | string\n\n // Ignore of the last user message when it's meaningless\n // You can provide a custom prompt to use instead of the default one by passing a string\n autoIgnoreUserNoise?: boolean | string\n}\n\nconst DEFAULT_MODEL = 'gpt-4o'\nconst DEFAULT_MAX_CALLS = 5\n\nconst AUTO_END_CALL_TOOL_NAME = 'end_call'\nconst AUTO_END_CALL_PROMPT = 'User asks to end the call'\n\nconst AUTO_SEMANTIC_TURN_TOOL_NAME = 'semantic_turn'\nconst AUTO_SEMANTIC_TURN_PROMPT = 'Last user message is an incomplete sentence'\n\nconst AUTO_IGNORE_USER_NOISE_TOOL_NAME = 'ignore_user_noise'\nconst AUTO_IGNORE_USER_NOISE_PROMPT =\n 'Last user message is just an interjection or a sound that expresses emotion, hesitation, or reaction (ex: \"Uh\", \"Ahem\", \"Hmm\", \"Ah\") but doesn\\'t carry any clear meaning like agreeing, refusing, or commanding'\n\nexport class OpenaiAgent extends Agent<OpenaiAgentOptions> {\n private openai: OpenAI\n private tools: Tool[]\n private abortController?: AbortController\n\n constructor(options: OpenaiAgentOptions) {\n super(options)\n this.openai = new OpenAI({ apiKey: options.apiKey })\n this.tools = this.getDefaultTools()\n }\n\n answer() {\n this.cancel()\n this.log('Start answering')\n const stream = new PassThrough()\n const textPromise = this.createTextPromise()\n\n this.generateAnswer(stream, textPromise).finally(() => {\n this.abortController = undefined\n if (stream.writable) {\n stream.end()\n }\n })\n\n return { message: textPromise.promise, stream }\n }\n\n private async generateAnswer(\n stream: PassThrough,\n textPromise: TextPromise,\n callCount = 0,\n toolInputs?: OpenAI.Responses.ResponseInputItem[]\n ): Promise<void> {\n if (callCount >= (this.options.maxCalls || DEFAULT_MAX_CALLS)) {\n console.error('[OpenaiAgent] Max calls reached')\n textPromise.reject(new Error('Max calls reached'))\n return\n }\n\n this.abortController = new AbortController()\n const signal = this.abortController.signal\n\n // Disable tools if first message\n const enableTools = this.conversation.length > 1\n\n // Build input\n const input: OpenAI.Responses.ResponseInput = this.conversation.map(\n (message) => ({\n role: message.role,\n content: message.content,\n })\n )\n if (toolInputs) {\n input.push(...toolInputs)\n }\n\n try {\n // Generate answer\n const response = await this.openai.responses.create(\n {\n model: this.options.model || DEFAULT_MODEL,\n input,\n temperature: 0.5,\n max_output_tokens: 250,\n stream: true,\n tools: enableTools ? this.tools.map(createToolSchema) : undefined,\n ...this.options.settings,\n },\n { signal }\n )\n const toolOutputs: OpenAI.Responses.ResponseInputItem[] = []\n\n // Handle response events\n for await (const event of response) {\n switch (event.type) {\n case 'response.output_text.delta':\n this.log(`Answer chunk: \"${event.delta}\"`)\n stream.write(event.delta)\n break\n\n case 'response.output_text.done':\n this.addAssistantMessage(event.text)\n stream.end()\n textPromise.resolve(event.text)\n break\n\n case 'response.output_item.done':\n if (event.item.type === 'function_call') {\n toolOutputs.push(event.item)\n const toolOutput = await this.executeTool(event.item)\n toolOutputs.push(toolOutput)\n }\n break\n\n default:\n break\n }\n }\n\n // Query again in case of tool call\n if (toolOutputs.length > 0) {\n await this.generateAnswer(\n stream,\n textPromise,\n callCount + 1,\n toolOutputs\n )\n }\n } catch (error) {\n textPromise.reject(error)\n if (!(error instanceof OpenAI.APIUserAbortError)) {\n console.error('[OpenaiAgent] Error answering:', error)\n }\n }\n }\n\n addTool<Schema extends z.ZodObject>(tool: Tool<Schema>) {\n this.tools.push(tool)\n }\n\n removeTool(name: string) {\n this.tools = this.tools.filter((tool) => tool.name !== name)\n }\n\n private getDefaultTools() {\n const tools: Tool[] = []\n if (this.options.autoEndCall) {\n tools.push({\n name: AUTO_END_CALL_TOOL_NAME,\n description:\n typeof this.options.autoEndCall === 'string'\n ? this.options.autoEndCall\n : AUTO_END_CALL_PROMPT,\n callback: () => this.endCall(),\n })\n }\n if (this.options.autoSemanticTurn) {\n tools.push({\n name: AUTO_SEMANTIC_TURN_TOOL_NAME,\n description:\n typeof this.options.autoSemanticTurn === 'string'\n ? this.options.autoSemanticTurn\n : AUTO_SEMANTIC_TURN_PROMPT,\n callback: () => this.skipAnswer(),\n })\n }\n if (this.options.autoIgnoreUserNoise) {\n tools.push({\n name: AUTO_IGNORE_USER_NOISE_TOOL_NAME,\n description:\n typeof this.options.autoIgnoreUserNoise === 'string'\n ? this.options.autoIgnoreUserNoise\n : AUTO_IGNORE_USER_NOISE_PROMPT,\n callback: () => this.cancelLastUserMessage(),\n })\n }\n return tools\n }\n\n private async executeTool(toolCall: ToolCall): Promise<ToolCallOutput> {\n try {\n const tool = this.tools.find((tool) => tool.name === toolCall.name)\n if (!tool) {\n throw new Error(`Tool not found \"${toolCall.name}\"`)\n }\n\n this.log('Executing tool:', toolCall.name, toolCall.arguments)\n const args = JSON.parse(toolCall.arguments)\n const result = await tool.callback(args)\n return createToolCallOutput(toolCall, result || {})\n } catch (error: any) {\n console.error('[OpenaiAgent] Error executing tool:', error)\n return createToolCallOutput(toolCall, { error: error.message })\n }\n }\n\n cancel() {\n if (!this.abortController) return\n this.log('Cancel')\n this.abortController.abort()\n this.abortController = undefined\n }\n}\n","import {\n FunctionTool,\n ResponseInputItem,\n Responses,\n} from 'openai/resources/responses/responses'\nimport { toJSONSchema, z } from 'zod'\n\nexport interface Tool<Schema extends z.ZodObject = z.ZodObject> {\n name: string\n description: string\n parameters?: Schema\n callback: (input: z.infer<Schema>) => any | Promise<any>\n}\n\nexport type ToolCall = Responses.ResponseFunctionToolCall\nexport type ToolCallOutput = ResponseInputItem.FunctionCallOutput\n\nexport function createToolSchema<Schema extends z.ZodObject>(\n tool: Tool<Schema>\n): FunctionTool {\n return {\n type: 'function',\n name: tool.name,\n description: tool.description,\n strict: true,\n parameters: toJSONSchema(tool.parameters || z.object()),\n }\n}\n\nexport function createToolCallOutput(\n toolCall: ToolCall,\n args: any\n): ToolCallOutput {\n return {\n type: 'function_call_output',\n call_id: toolCall.call_id,\n output: JSON.stringify(args),\n }\n}\n","import { FileSTT } from '@micdrop/server'\n\n/**\n * OpenAI Whisper STT\n *\n * @see https://platform.openai.com/docs/guides/speech-to-text?lang=curl\n */\n\nexport interface OpenaiSTTOptions {\n apiKey: string\n model?: string\n language?: string\n}\n\nconst DEFAULT_MODEL = 'whisper-1'\n\nexport class OpenaiSTT extends FileSTT {\n constructor(private options: OpenaiSTTOptions) {\n super()\n }\n\n async transcribeFile(file: File) {\n // Prepare form data\n const formData = new FormData()\n formData.append('file', file)\n formData.append('model', this.options.model || DEFAULT_MODEL)\n formData.append('response_format', 'text')\n\n if (this.options.language) {\n formData.append('language', this.options.language)\n }\n\n const response = await fetch(\n 'https://api.openai.com/v1/audio/transcriptions',\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.options.apiKey}`,\n },\n body: formData,\n }\n )\n\n if (!response.ok) {\n this.log('Failed to transcribe audio', await response.json())\n throw new Error(`Failed to transcribe audio: ${response.statusText}`)\n }\n\n const transcript = await response.text()\n this.log(`Received transcript: \"${transcript}\"`)\n\n return transcript\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,oBAAiD;AACjD,oBAAmB;AACnB,oBAA4B;;;ACG5B,iBAAgC;AAYzB,SAAS,iBACd,MACc;AACd,SAAO;AAAA,IACL,MAAM;AAAA,IACN,MAAM,KAAK;AAAA,IACX,aAAa,KAAK;AAAA,IAClB,QAAQ;AAAA,I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ent":["export * from './OpenaiAgent'\nexport * from './OpenaiSTT'\n","import { Agent, AgentOptions, TextPromise } from '@micdrop/server'\nimport OpenAI from 'openai'\nimport { PassThrough } from 'stream'\nimport { z } from 'zod'\nimport {\n createToolCallOutput,\n createToolSchema,\n Tool,\n ToolCall,\n ToolCallOutput,\n} from './tools'\n\nexport interface OpenaiAgentOptions extends AgentOptions {\n apiKey: string\n model?: string\n maxCalls?: number\n settings?: Omit<\n OpenAI.Responses.ResponseCreateParamsStreaming,\n 'input' | 'model'\n >\n\n // Enable auto ending of the call when user asks to end the call\n // You can provide a custom prompt to use instead of the default one by passing a string\n autoEndCall?: boolean | string\n\n // Enable detection of an incomplete sentence, and skip the answer (assistant waits)\n // You can provide a custom prompt to use instead of the default one by passing a string\n autoSemanticTurn?: boolean | string\n\n // Ignore of the last user message when it's meaningless\n // You can provide a custom prompt to use instead of the default one by passing a string\n autoIgnoreUserNoise?: boolean | string\n}\n\nconst DEFAULT_MODEL = 'gpt-4o'\nconst DEFAULT_MAX_CALLS = 5\n\nconst AUTO_END_CALL_TOOL_NAME = 'end_call'\nconst AUTO_END_CALL_PROMPT = 'Call this tool only if user asks to end the call'\n\nconst AUTO_SEMANTIC_TURN_TOOL_NAME = 'semantic_turn'\nconst AUTO_SEMANTIC_TURN_PROMPT =\n 'Call this tool only if last user message is obviously an incomplete sentence that you need to wait for the end before answering'\n\nconst AUTO_IGNORE_USER_NOISE_TOOL_NAME = 'ignore_user_noise'\nconst AUTO_IGNORE_USER_NOISE_PROMPT =\n 'Call this tool only if last user message is just an interjection or a sound that expresses emotion, hesitation, or reaction (ex: \"Uh\", \"Ahem\", \"Hmm\", \"Ah\") but doesn\\'t carry any clear meaning like agreeing, refusing, or commanding'\n\nexport class OpenaiAgent extends Agent<OpenaiAgentOptions> {\n private openai: OpenAI\n private tools: Tool[]\n private abortController?: AbortController\n\n constructor(options: OpenaiAgentOptions) {\n super(options)\n this.openai = new OpenAI({ apiKey: options.apiKey })\n this.tools = this.getDefaultTools()\n }\n\n answer() {\n this.cancel()\n this.log('Start answering')\n const stream = new PassThrough()\n const textPromise = this.createTextPromise()\n\n this.generateAnswer(stream, textPromise).finally(() => {\n this.abortController = undefined\n if (stream.writable) {\n stream.end()\n }\n })\n\n return { message: textPromise.promise, stream }\n }\n\n private async generateAnswer(\n stream: PassThrough,\n textPromise: TextPromise,\n callCount = 0,\n toolInputs?: Array<ToolCall | ToolCallOutput>\n ): Promise<void> {\n if (callCount >= (this.options.maxCalls || DEFAULT_MAX_CALLS)) {\n console.error('[OpenaiAgent] Max calls reached')\n textPromise.resolve('')\n return\n }\n\n this.abortController = new AbortController()\n const signal = this.abortController.signal\n\n // Disable tools if first message\n const enableTools = this.conversation.length > 1\n\n // Build input\n const input: OpenAI.Responses.ResponseInput = this.conversation.map(\n (message) => ({\n role: message.role,\n content: message.content,\n })\n )\n if (toolInputs) {\n input.push(...toolInputs)\n }\n\n try {\n // Generate answer\n const response = await this.openai.responses.create(\n {\n model: this.options.model || DEFAULT_MODEL,\n input,\n temperature: 0.5,\n max_output_tokens: 250,\n stream: true,\n tools: enableTools ? this.tools.map(createToolSchema) : undefined,\n ...this.options.settings,\n },\n { signal }\n )\n const toolOutputs: Array<ToolCall | ToolCallOutput> = []\n let hasAnswer = false\n let skipAnswer = false\n\n // Handle response events\n for await (const event of response) {\n switch (event.type) {\n case 'response.output_text.delta':\n this.log(`Answer chunk: \"${event.delta}\"`)\n stream.write(event.delta)\n break\n\n case 'response.output_text.done':\n this.addAssistantMessage(event.text)\n stream.end()\n textPromise.resolve(event.text)\n hasAnswer = true\n break\n\n case 'response.output_item.done':\n if (event.item.type === 'function_call') {\n const result = await this.executeTool(event.item)\n toolOutputs.push(result.toolCall, result.toolCallOutput)\n if (result.skipAnswer) {\n skipAnswer = true\n }\n }\n break\n\n default:\n break\n }\n }\n\n // Query again in case of tool call\n if (toolOutputs.length > 0 && !hasAnswer && !skipAnswer) {\n await this.generateAnswer(\n stream,\n textPromise,\n callCount + 1,\n toolOutputs\n )\n } else {\n // Ensure promise is resolved (if skipAnswer is true in a tool)\n textPromise.resolve('')\n }\n } catch (error) {\n textPromise.resolve('')\n if (!(error instanceof OpenAI.APIUserAbortError)) {\n console.error('[OpenaiAgent] Error answering:', error)\n }\n }\n }\n\n addTool<Schema extends z.ZodObject>(tool: Tool<Schema>) {\n this.tools.push(tool)\n }\n\n removeTool(name: string) {\n this.tools = this.tools.filter((tool) => tool.name !== name)\n }\n\n getTool(name: string): Tool | undefined {\n return this.tools.find((tool) => tool.name === name)\n }\n\n private getDefaultTools() {\n const tools: Tool[] = []\n if (this.options.autoEndCall) {\n tools.push({\n name: AUTO_END_CALL_TOOL_NAME,\n description:\n typeof this.options.autoEndCall === 'string'\n ? this.options.autoEndCall\n : AUTO_END_CALL_PROMPT,\n callback: () => this.endCall(),\n })\n }\n if (this.options.autoSemanticTurn) {\n tools.push({\n name: AUTO_SEMANTIC_TURN_TOOL_NAME,\n description:\n typeof this.options.autoSemanticTurn === 'string'\n ? this.options.autoSemanticTurn\n : AUTO_SEMANTIC_TURN_PROMPT,\n skipAnswer: true,\n callback: () => this.skipAnswer(),\n })\n }\n if (this.options.autoIgnoreUserNoise) {\n tools.push({\n name: AUTO_IGNORE_USER_NOISE_TOOL_NAME,\n description:\n typeof this.options.autoIgnoreUserNoise === 'string'\n ? this.options.autoIgnoreUserNoise\n : AUTO_IGNORE_USER_NOISE_PROMPT,\n skipAnswer: true,\n callback: () => this.cancelLastUserMessage(),\n })\n }\n return tools\n }\n\n private async executeTool(toolCall: ToolCall) {\n try {\n const tool = this.getTool(toolCall.name)\n if (!tool) {\n throw new Error(`Tool not found \"${toolCall.name}\"`)\n }\n\n this.log('Executing tool:', toolCall.name, toolCall.arguments)\n const args = JSON.parse(toolCall.arguments)\n const result = await tool.callback(args)\n\n return {\n toolCall,\n toolCallOutput: createToolCallOutput(toolCall, result || {}),\n skipAnswer: tool.skipAnswer,\n }\n } catch (error: any) {\n console.error('[OpenaiAgent] Error executing tool:', error)\n return {\n toolCall,\n toolCallOutput: createToolCallOutput(toolCall, {\n error: error.message,\n }),\n }\n }\n }\n\n cancel() {\n if (!this.abortController) return\n this.log('Cancel')\n this.abortController.abort()\n this.abortController = undefined\n }\n}\n","import {\n FunctionTool,\n ResponseInputItem,\n Responses,\n} from 'openai/resources/responses/responses'\nimport { toJSONSchema, z } from 'zod'\n\nexport interface Tool<Schema extends z.ZodObject = z.ZodObject> {\n name: string\n description: string\n parameters?: Schema\n callback: (input: z.infer<Schema>) => any | Promise<any>\n skipAnswer?: boolean\n}\n\nexport type ToolCall = Responses.ResponseFunctionToolCall\nexport type ToolCallOutput = ResponseInputItem.FunctionCallOutput\n\nexport function createToolSchema<Schema extends z.ZodObject>(\n tool: Tool<Schema>\n): FunctionTool {\n return {\n type: 'function',\n name: tool.name,\n description: tool.description,\n strict: true,\n parameters: toJSONSchema(tool.parameters || z.object()),\n }\n}\n\nexport function createToolCallOutput(\n toolCall: ToolCall,\n args: any\n): ToolCallOutput {\n return {\n type: 'function_call_output',\n call_id: toolCall.call_id,\n output: JSON.stringify(args),\n }\n}\n","import { FileSTT } from '@micdrop/server'\n\n/**\n * OpenAI Whisper STT\n *\n * @see https://platform.openai.com/docs/guides/speech-to-text?lang=curl\n */\n\nexport interface OpenaiSTTOptions {\n apiKey: string\n model?: string\n language?: string\n}\n\nconst DEFAULT_MODEL = 'whisper-1'\n\nexport class OpenaiSTT extends FileSTT {\n constructor(private options: OpenaiSTTOptions) {\n super()\n }\n\n async transcribeFile(file: File) {\n // Prepare form data\n const formData = new FormData()\n formData.append('file', file)\n formData.append('model', this.options.model || DEFAULT_MODEL)\n formData.append('response_format', 'text')\n\n if (this.options.language) {\n formData.append('language', this.options.language)\n }\n\n const response = await fetch(\n 'https://api.openai.com/v1/audio/transcriptions',\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.options.apiKey}`,\n },\n body: formData,\n }\n )\n\n if (!response.ok) {\n this.log('Failed to transcribe audio', await response.json())\n throw new Error(`Failed to transcribe audio: ${response.statusText}`)\n }\n\n const transcript = await response.text()\n this.log(`Received transcript: \"${transcript}\"`)\n\n return transcript\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,oBAAiD;AACjD,oBAAmB;AACnB,oBAA4B;;;ACG5B,iBAAgC;AAazB,SAAS,iBACd,MACc;AACd,SAAO;AAAA,IACL,MAAM;AAAA,IACN,MAAM,KAAK;AAAA,IACX,aAAa,KAAK;AAAA,IAClB,QAAQ;AAAA,IACR,gBAAY,yBAAa,KAAK,cAAc,aAAE,OAAO,CAAC;AAAA,EACxD;AACF;AAEO,SAAS,qBACd,UACA,MACgB;AAChB,SAAO;AAAA,IACL,MAAM;AAAA,IACN,SAAS,SAAS;AAAA,IAClB,QAAQ,KAAK,UAAU,IAAI;AAAA,EAC7B;AACF;;;ADLA,IAAM,gBAAgB;AACtB,IAAM,oBAAoB;AAE1B,IAAM,0BAA0B;AAChC,IAAM,uBAAuB;AAE7B,IAAM,+BAA+B;AACrC,IAAM,4BACJ;AAEF,IAAM,mCAAmC;AACzC,IAAM,gCACJ;AAEK,IAAM,cAAN,cAA0B,oBAA0B;AAAA,EAKzD,YAAY,SAA6B;AACvC,UAAM,OAAO;AACb,SAAK,SAAS,IAAI,cAAAA,QAAO,EAAE,QAAQ,QAAQ,OAAO,CAAC;AACnD,SAAK,QAAQ,KAAK,gBAAgB;AAAA,EACpC;AAAA,EAEA,SAAS;AACP,SAAK,OAAO;AACZ,SAAK,IAAI,iBAAiB;AAC1B,UAAM,SAAS,IAAI,0BAAY;AAC/B,UAAM,cAAc,KAAK,kBAAkB;AAE3C,SAAK,eAAe,QAAQ,WAAW,EAAE,QAAQ,MAAM;AACrD,WAAK,kBAAkB;AACvB,UAAI,OAAO,UAAU;AACnB,eAAO,IAAI;AAAA,MACb;AAAA,IACF,CAAC;AAED,WAAO,EAAE,SAAS,YAAY,SAAS,OAA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B,aAAS,OAAO,SAAS,KAAK,QAAQ,SAASA,cAAa;AAC5D,aAAS,OAAO,mBAAmB,MAAM;AAEzC,QAAI,KAAK,QAAQ,UAAU;AACzB,eAAS,OAAO,YAAY,KAAK,QAAQ,QAAQ;AAAA,IACnD;AAEA,UAAM,WAAW,MAAM;AAAA,MACrB;AAAA,MACA;AAAA,QACE,QAAQ;AAAA,QACR,SAAS;AAAA,UACP,eAAe,UAAU,KAAK,QAAQ,MAAM;AAAA,QAC9C;AAAA,QACA,MAAM;AAAA,MACR;AAAA,IACF;AAEA,QAAI,CAAC,SAAS,IAAI;AAChB,WAAK,IAAI,8BAA8B,MAAM,SAAS,KAAK,CAAC;AAC5D,YAAM,IAAI,MAAM,+BAA+B,SAAS,UAAU,EAAE;AAAA,IACtE;AAEA,UAAM,aAAa,MAAM,SAAS,KAAK;AACvC,SAAK,IAAI,yBAAyB,UAAU,GAAG;AAE/C,WAAO;AAAA,EACT;AACF;","names":["OpenAI","import_server","DEFAULT_MODEL"]}
|
package/dist/index.mjs
CHANGED
|
@@ -26,11 +26,11 @@ function createToolCallOutput(toolCall, args) {
|
|
|
26
26
|
var DEFAULT_MODEL = "gpt-4o";
|
|
27
27
|
var DEFAULT_MAX_CALLS = 5;
|
|
28
28
|
var AUTO_END_CALL_TOOL_NAME = "end_call";
|
|
29
|
-
var AUTO_END_CALL_PROMPT = "
|
|
29
|
+
var AUTO_END_CALL_PROMPT = "Call this tool only if user asks to end the call";
|
|
30
30
|
var AUTO_SEMANTIC_TURN_TOOL_NAME = "semantic_turn";
|
|
31
|
-
var AUTO_SEMANTIC_TURN_PROMPT = "
|
|
31
|
+
var AUTO_SEMANTIC_TURN_PROMPT = "Call this tool only if last user message is obviously an incomplete sentence that you need to wait for the end before answering";
|
|
32
32
|
var AUTO_IGNORE_USER_NOISE_TOOL_NAME = "ignore_user_noise";
|
|
33
|
-
var AUTO_IGNORE_USER_NOISE_PROMPT = `
|
|
33
|
+
var AUTO_IGNORE_USER_NOISE_PROMPT = `Call this tool only if last user message is just an interjection or a sound that expresses emotion, hesitation, or reaction (ex: "Uh", "Ahem", "Hmm", "Ah") but doesn't carry any clear meaning like agreeing, refusing, or commanding`;
|
|
34
34
|
var OpenaiAgent = class extends Agent {
|
|
35
35
|
constructor(options) {
|
|
36
36
|
super(options);
|
|
@@ -53,7 +53,7 @@ var OpenaiAgent = class extends Agent {
|
|
|
53
53
|
async generateAnswer(stream, textPromise, callCount = 0, toolInputs) {
|
|
54
54
|
if (callCount >= (this.options.maxCalls || DEFAULT_MAX_CALLS)) {
|
|
55
55
|
console.error("[OpenaiAgent] Max calls reached");
|
|
56
|
-
textPromise.
|
|
56
|
+
textPromise.resolve("");
|
|
57
57
|
return;
|
|
58
58
|
}
|
|
59
59
|
this.abortController = new AbortController();
|
|
@@ -82,6 +82,8 @@ var OpenaiAgent = class extends Agent {
|
|
|
82
82
|
{ signal }
|
|
83
83
|
);
|
|
84
84
|
const toolOutputs = [];
|
|
85
|
+
let hasAnswer = false;
|
|
86
|
+
let skipAnswer = false;
|
|
85
87
|
for await (const event of response) {
|
|
86
88
|
switch (event.type) {
|
|
87
89
|
case "response.output_text.delta":
|
|
@@ -92,28 +94,33 @@ var OpenaiAgent = class extends Agent {
|
|
|
92
94
|
this.addAssistantMessage(event.text);
|
|
93
95
|
stream.end();
|
|
94
96
|
textPromise.resolve(event.text);
|
|
97
|
+
hasAnswer = true;
|
|
95
98
|
break;
|
|
96
99
|
case "response.output_item.done":
|
|
97
100
|
if (event.item.type === "function_call") {
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
+
const result = await this.executeTool(event.item);
|
|
102
|
+
toolOutputs.push(result.toolCall, result.toolCallOutput);
|
|
103
|
+
if (result.skipAnswer) {
|
|
104
|
+
skipAnswer = true;
|
|
105
|
+
}
|
|
101
106
|
}
|
|
102
107
|
break;
|
|
103
108
|
default:
|
|
104
109
|
break;
|
|
105
110
|
}
|
|
106
111
|
}
|
|
107
|
-
if (toolOutputs.length > 0) {
|
|
112
|
+
if (toolOutputs.length > 0 && !hasAnswer && !skipAnswer) {
|
|
108
113
|
await this.generateAnswer(
|
|
109
114
|
stream,
|
|
110
115
|
textPromise,
|
|
111
116
|
callCount + 1,
|
|
112
117
|
toolOutputs
|
|
113
118
|
);
|
|
119
|
+
} else {
|
|
120
|
+
textPromise.resolve("");
|
|
114
121
|
}
|
|
115
122
|
} catch (error) {
|
|
116
|
-
textPromise.
|
|
123
|
+
textPromise.resolve("");
|
|
117
124
|
if (!(error instanceof OpenAI.APIUserAbortError)) {
|
|
118
125
|
console.error("[OpenaiAgent] Error answering:", error);
|
|
119
126
|
}
|
|
@@ -125,6 +132,9 @@ var OpenaiAgent = class extends Agent {
|
|
|
125
132
|
removeTool(name) {
|
|
126
133
|
this.tools = this.tools.filter((tool) => tool.name !== name);
|
|
127
134
|
}
|
|
135
|
+
getTool(name) {
|
|
136
|
+
return this.tools.find((tool) => tool.name === name);
|
|
137
|
+
}
|
|
128
138
|
getDefaultTools() {
|
|
129
139
|
const tools = [];
|
|
130
140
|
if (this.options.autoEndCall) {
|
|
@@ -138,6 +148,7 @@ var OpenaiAgent = class extends Agent {
|
|
|
138
148
|
tools.push({
|
|
139
149
|
name: AUTO_SEMANTIC_TURN_TOOL_NAME,
|
|
140
150
|
description: typeof this.options.autoSemanticTurn === "string" ? this.options.autoSemanticTurn : AUTO_SEMANTIC_TURN_PROMPT,
|
|
151
|
+
skipAnswer: true,
|
|
141
152
|
callback: () => this.skipAnswer()
|
|
142
153
|
});
|
|
143
154
|
}
|
|
@@ -145,6 +156,7 @@ var OpenaiAgent = class extends Agent {
|
|
|
145
156
|
tools.push({
|
|
146
157
|
name: AUTO_IGNORE_USER_NOISE_TOOL_NAME,
|
|
147
158
|
description: typeof this.options.autoIgnoreUserNoise === "string" ? this.options.autoIgnoreUserNoise : AUTO_IGNORE_USER_NOISE_PROMPT,
|
|
159
|
+
skipAnswer: true,
|
|
148
160
|
callback: () => this.cancelLastUserMessage()
|
|
149
161
|
});
|
|
150
162
|
}
|
|
@@ -152,17 +164,26 @@ var OpenaiAgent = class extends Agent {
|
|
|
152
164
|
}
|
|
153
165
|
async executeTool(toolCall) {
|
|
154
166
|
try {
|
|
155
|
-
const tool = this.
|
|
167
|
+
const tool = this.getTool(toolCall.name);
|
|
156
168
|
if (!tool) {
|
|
157
169
|
throw new Error(`Tool not found "${toolCall.name}"`);
|
|
158
170
|
}
|
|
159
171
|
this.log("Executing tool:", toolCall.name, toolCall.arguments);
|
|
160
172
|
const args = JSON.parse(toolCall.arguments);
|
|
161
173
|
const result = await tool.callback(args);
|
|
162
|
-
return
|
|
174
|
+
return {
|
|
175
|
+
toolCall,
|
|
176
|
+
toolCallOutput: createToolCallOutput(toolCall, result || {}),
|
|
177
|
+
skipAnswer: tool.skipAnswer
|
|
178
|
+
};
|
|
163
179
|
} catch (error) {
|
|
164
180
|
console.error("[OpenaiAgent] Error executing tool:", error);
|
|
165
|
-
return
|
|
181
|
+
return {
|
|
182
|
+
toolCall,
|
|
183
|
+
toolCallOutput: createToolCallOutput(toolCall, {
|
|
184
|
+
error: error.message
|
|
185
|
+
})
|
|
186
|
+
};
|
|
166
187
|
}
|
|
167
188
|
}
|
|
168
189
|
cancel() {
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/OpenaiAgent.ts","../src/tools.ts","../src/OpenaiSTT.ts"],"sourcesContent":["import { Agent, AgentOptions, TextPromise } from '@micdrop/server'\nimport OpenAI from 'openai'\nimport { PassThrough } from 'stream'\nimport { z } from 'zod'\nimport {\n createToolCallOutput,\n createToolSchema,\n Tool,\n ToolCall,\n ToolCallOutput,\n} from './tools'\n\nexport interface OpenaiAgentOptions extends AgentOptions {\n apiKey: string\n model?: string\n maxCalls?: number\n settings?: Omit<\n OpenAI.Responses.ResponseCreateParamsStreaming,\n 'input' | 'model'\n >\n\n // Enable auto ending of the call when user asks to end the call\n // You can provide a custom prompt to use instead of the default one by passing a string\n autoEndCall?: boolean | string\n\n // Enable detection of an incomplete sentence, and skip the answer (assistant waits)\n // You can provide a custom prompt to use instead of the default one by passing a string\n autoSemanticTurn?: boolean | string\n\n // Ignore of the last user message when it's meaningless\n // You can provide a custom prompt to use instead of the default one by passing a string\n autoIgnoreUserNoise?: boolean | string\n}\n\nconst DEFAULT_MODEL = 'gpt-4o'\nconst DEFAULT_MAX_CALLS = 5\n\nconst AUTO_END_CALL_TOOL_NAME = 'end_call'\nconst AUTO_END_CALL_PROMPT = 'User asks to end the call'\n\nconst AUTO_SEMANTIC_TURN_TOOL_NAME = 'semantic_turn'\nconst AUTO_SEMANTIC_TURN_PROMPT = 'Last user message is an incomplete sentence'\n\nconst AUTO_IGNORE_USER_NOISE_TOOL_NAME = 'ignore_user_noise'\nconst AUTO_IGNORE_USER_NOISE_PROMPT =\n 'Last user message is just an interjection or a sound that expresses emotion, hesitation, or reaction (ex: \"Uh\", \"Ahem\", \"Hmm\", \"Ah\") but doesn\\'t carry any clear meaning like agreeing, refusing, or commanding'\n\nexport class OpenaiAgent extends Agent<OpenaiAgentOptions> {\n private openai: OpenAI\n private tools: Tool[]\n private abortController?: AbortController\n\n constructor(options: OpenaiAgentOptions) {\n super(options)\n this.openai = new OpenAI({ apiKey: options.apiKey })\n this.tools = this.getDefaultTools()\n }\n\n answer() {\n this.cancel()\n this.log('Start answering')\n const stream = new PassThrough()\n const textPromise = this.createTextPromise()\n\n this.generateAnswer(stream, textPromise).finally(() => {\n this.abortController = undefined\n if (stream.writable) {\n stream.end()\n }\n })\n\n return { message: textPromise.promise, stream }\n }\n\n private async generateAnswer(\n stream: PassThrough,\n textPromise: TextPromise,\n callCount = 0,\n toolInputs?: OpenAI.Responses.ResponseInputItem[]\n ): Promise<void> {\n if (callCount >= (this.options.maxCalls || DEFAULT_MAX_CALLS)) {\n console.error('[OpenaiAgent] Max calls reached')\n textPromise.reject(new Error('Max calls reached'))\n return\n }\n\n this.abortController = new AbortController()\n const signal = this.abortController.signal\n\n // Disable tools if first message\n const enableTools = this.conversation.length > 1\n\n // Build input\n const input: OpenAI.Responses.ResponseInput = this.conversation.map(\n (message) => ({\n role: message.role,\n content: message.content,\n })\n )\n if (toolInputs) {\n input.push(...toolInputs)\n }\n\n try {\n // Generate answer\n const response = await this.openai.responses.create(\n {\n model: this.options.model || DEFAULT_MODEL,\n input,\n temperature: 0.5,\n max_output_tokens: 250,\n stream: true,\n tools: enableTools ? this.tools.map(createToolSchema) : undefined,\n ...this.options.settings,\n },\n { signal }\n )\n const toolOutputs: OpenAI.Responses.ResponseInputItem[] = []\n\n // Handle response events\n for await (const event of response) {\n switch (event.type) {\n case 'response.output_text.delta':\n this.log(`Answer chunk: \"${event.delta}\"`)\n stream.write(event.delta)\n break\n\n case 'response.output_text.done':\n this.addAssistantMessage(event.text)\n stream.end()\n textPromise.resolve(event.text)\n break\n\n case 'response.output_item.done':\n if (event.item.type === 'function_call') {\n toolOutputs.push(event.item)\n const toolOutput = await this.executeTool(event.item)\n toolOutputs.push(toolOutput)\n }\n break\n\n default:\n break\n }\n }\n\n // Query again in case of tool call\n if (toolOutputs.length > 0) {\n await this.generateAnswer(\n stream,\n textPromise,\n callCount + 1,\n toolOutputs\n )\n }\n } catch (error) {\n textPromise.reject(error)\n if (!(error instanceof OpenAI.APIUserAbortError)) {\n console.error('[OpenaiAgent] Error answering:', error)\n }\n }\n }\n\n addTool<Schema extends z.ZodObject>(tool: Tool<Schema>) {\n this.tools.push(tool)\n }\n\n removeTool(name: string) {\n this.tools = this.tools.filter((tool) => tool.name !== name)\n }\n\n private getDefaultTools() {\n const tools: Tool[] = []\n if (this.options.autoEndCall) {\n tools.push({\n name: AUTO_END_CALL_TOOL_NAME,\n description:\n typeof this.options.autoEndCall === 'string'\n ? this.options.autoEndCall\n : AUTO_END_CALL_PROMPT,\n callback: () => this.endCall(),\n })\n }\n if (this.options.autoSemanticTurn) {\n tools.push({\n name: AUTO_SEMANTIC_TURN_TOOL_NAME,\n description:\n typeof this.options.autoSemanticTurn === 'string'\n ? this.options.autoSemanticTurn\n : AUTO_SEMANTIC_TURN_PROMPT,\n callback: () => this.skipAnswer(),\n })\n }\n if (this.options.autoIgnoreUserNoise) {\n tools.push({\n name: AUTO_IGNORE_USER_NOISE_TOOL_NAME,\n description:\n typeof this.options.autoIgnoreUserNoise === 'string'\n ? this.options.autoIgnoreUserNoise\n : AUTO_IGNORE_USER_NOISE_PROMPT,\n callback: () => this.cancelLastUserMessage(),\n })\n }\n return tools\n }\n\n private async executeTool(toolCall: ToolCall): Promise<ToolCallOutput> {\n try {\n const tool = this.tools.find((tool) => tool.name === toolCall.name)\n if (!tool) {\n throw new Error(`Tool not found \"${toolCall.name}\"`)\n }\n\n this.log('Executing tool:', toolCall.name, toolCall.arguments)\n const args = JSON.parse(toolCall.arguments)\n const result = await tool.callback(args)\n return createToolCallOutput(toolCall, result || {})\n } catch (error: any) {\n console.error('[OpenaiAgent] Error executing tool:', error)\n return createToolCallOutput(toolCall, { error: error.message })\n }\n }\n\n cancel() {\n if (!this.abortController) return\n this.log('Cancel')\n this.abortController.abort()\n this.abortController = undefined\n }\n}\n","import {\n FunctionTool,\n ResponseInputItem,\n Responses,\n} from 'openai/resources/responses/responses'\nimport { toJSONSchema, z } from 'zod'\n\nexport interface Tool<Schema extends z.ZodObject = z.ZodObject> {\n name: string\n description: string\n parameters?: Schema\n callback: (input: z.infer<Schema>) => any | Promise<any>\n}\n\nexport type ToolCall = Responses.ResponseFunctionToolCall\nexport type ToolCallOutput = ResponseInputItem.FunctionCallOutput\n\nexport function createToolSchema<Schema extends z.ZodObject>(\n tool: Tool<Schema>\n): FunctionTool {\n return {\n type: 'function',\n name: tool.name,\n description: tool.description,\n strict: true,\n parameters: toJSONSchema(tool.parameters || z.object()),\n }\n}\n\nexport function createToolCallOutput(\n toolCall: ToolCall,\n args: any\n): ToolCallOutput {\n return {\n type: 'function_call_output',\n call_id: toolCall.call_id,\n output: JSON.stringify(args),\n }\n}\n","import { FileSTT } from '@micdrop/server'\n\n/**\n * OpenAI Whisper STT\n *\n * @see https://platform.openai.com/docs/guides/speech-to-text?lang=curl\n */\n\nexport interface OpenaiSTTOptions {\n apiKey: string\n model?: string\n language?: string\n}\n\nconst DEFAULT_MODEL = 'whisper-1'\n\nexport class OpenaiSTT extends FileSTT {\n constructor(private options: OpenaiSTTOptions) {\n super()\n }\n\n async transcribeFile(file: File) {\n // Prepare form data\n const formData = new FormData()\n formData.append('file', file)\n formData.append('model', this.options.model || DEFAULT_MODEL)\n formData.append('response_format', 'text')\n\n if (this.options.language) {\n formData.append('language', this.options.language)\n }\n\n const response = await fetch(\n 'https://api.openai.com/v1/audio/transcriptions',\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.options.apiKey}`,\n },\n body: formData,\n }\n )\n\n if (!response.ok) {\n this.log('Failed to transcribe audio', await response.json())\n throw new Error(`Failed to transcribe audio: ${response.statusText}`)\n }\n\n const transcript = await response.text()\n this.log(`Received transcript: \"${transcript}\"`)\n\n return transcript\n }\n}\n"],"mappings":";AAAA,SAAS,aAAwC;AACjD,OAAO,YAAY;AACnB,SAAS,mBAAmB;;;ACG5B,SAAS,cAAc,SAAS;AAYzB,SAAS,iBACd,MACc;AACd,SAAO;AAAA,IACL,MAAM;AAAA,IACN,MAAM,KAAK;AAAA,IACX,aAAa,KAAK;AAAA,IAClB,QAAQ;AAAA,IACR,YAAY,aAAa,KAAK,cAAc,EAAE,OAAO,CAAC;AAAA,EACxD;AACF;AAEO,SAAS,qBACd,UACA,MACgB;AAChB,SAAO;AAAA,IACL,MAAM;AAAA,IACN,SAAS,SAAS;AAAA,IAClB,QAAQ,KAAK,UAAU,IAAI;AAAA,EAC7B;AACF;;;ADJA,IAAM,gBAAgB;AACtB,IAAM,oBAAoB;AAE1B,IAAM,0BAA0B;AAChC,IAAM,uBAAuB;AAE7B,IAAM,+BAA+B;AACrC,IAAM,4BAA4B;AAElC,IAAM,mCAAmC;AACzC,IAAM,gCACJ;AAEK,I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Y;AAAA,EAEpB;AAAA,EAEA,MAAM,eAAe,MAAY;AAE/B,UAAM,WAAW,IAAI,SAAS;AAC9B,aAAS,OAAO,QAAQ,IAAI;AAC5B,aAAS,OAAO,SAAS,KAAK,QAAQ,SAASA,cAAa;AAC5D,aAAS,OAAO,mBAAmB,MAAM;AAEzC,QAAI,KAAK,QAAQ,UAAU;AACzB,eAAS,OAAO,YAAY,KAAK,QAAQ,QAAQ;AAAA,IACnD;AAEA,UAAM,WAAW,MAAM;AAAA,MACrB;AAAA,MACA;AAAA,QACE,QAAQ;AAAA,QACR,SAAS;AAAA,UACP,eAAe,UAAU,KAAK,QAAQ,MAAM;AAAA,QAC9C;AAAA,QACA,MAAM;AAAA,MACR;AAAA,IACF;AAEA,QAAI,CAAC,SAAS,IAAI;AAChB,WAAK,IAAI,8BAA8B,MAAM,SAAS,KAAK,CAAC;AAC5D,YAAM,IAAI,MAAM,+BAA+B,SAAS,UAAU,EAAE;AAAA,IACtE;AAEA,UAAM,aAAa,MAAM,SAAS,KAAK;AACvC,SAAK,IAAI,yBAAyB,UAAU,GAAG;AAE/C,WAAO;AAAA,EACT;AACF;","names":["tool","DEFAULT_MODEL"]}
|
|
1
|
+
{"version":3,"sources":["../src/OpenaiAgent.ts","../src/tools.ts","../src/OpenaiSTT.ts"],"sourcesContent":["import { Agent, AgentOptions, TextPromise } from '@micdrop/server'\nimport OpenAI from 'openai'\nimport { PassThrough } from 'stream'\nimport { z } from 'zod'\nimport {\n createToolCallOutput,\n createToolSchema,\n Tool,\n ToolCall,\n ToolCallOutput,\n} from './tools'\n\nexport interface OpenaiAgentOptions extends AgentOptions {\n apiKey: string\n model?: string\n maxCalls?: number\n settings?: Omit<\n OpenAI.Responses.ResponseCreateParamsStreaming,\n 'input' | 'model'\n >\n\n // Enable auto ending of the call when user asks to end the call\n // You can provide a custom prompt to use instead of the default one by passing a string\n autoEndCall?: boolean | string\n\n // Enable detection of an incomplete sentence, and skip the answer (assistant waits)\n // You can provide a custom prompt to use instead of the default one by passing a string\n autoSemanticTurn?: boolean | string\n\n // Ignore of the last user message when it's meaningless\n // You can provide a custom prompt to use instead of the default one by passing a string\n autoIgnoreUserNoise?: boolean | string\n}\n\nconst DEFAULT_MODEL = 'gpt-4o'\nconst DEFAULT_MAX_CALLS = 5\n\nconst AUTO_END_CALL_TOOL_NAME = 'end_call'\nconst AUTO_END_CALL_PROMPT = 'Call this tool only if user asks to end the call'\n\nconst AUTO_SEMANTIC_TURN_TOOL_NAME = 'semantic_turn'\nconst AUTO_SEMANTIC_TURN_PROMPT =\n 'Call this tool only if last user message is obviously an incomplete sentence that you need to wait for the end before answering'\n\nconst AUTO_IGNORE_USER_NOISE_TOOL_NAME = 'ignore_user_noise'\nconst AUTO_IGNORE_USER_NOISE_PROMPT =\n 'Call this tool only if last user message is just an interjection or a sound that expresses emotion, hesitation, or reaction (ex: \"Uh\", \"Ahem\", \"Hmm\", \"Ah\") but doesn\\'t carry any clear meaning like agreeing, refusing, or commanding'\n\nexport class OpenaiAgent extends Agent<OpenaiAgentOptions> {\n private openai: OpenAI\n private tools: Tool[]\n private abortController?: AbortController\n\n constructor(options: OpenaiAgentOptions) {\n super(options)\n this.openai = new OpenAI({ apiKey: options.apiKey })\n this.tools = this.getDefaultTools()\n }\n\n answer() {\n this.cancel()\n this.log('Start answering')\n const stream = new PassThrough()\n const textPromise = this.createTextPromise()\n\n this.generateAnswer(stream, textPromise).finally(() => {\n this.abortController = undefined\n if (stream.writable) {\n stream.end()\n }\n })\n\n return { message: textPromise.promise, stream }\n }\n\n private async generateAnswer(\n stream: PassThrough,\n textPromise: TextPromise,\n callCount = 0,\n toolInputs?: Array<ToolCall | ToolCallOutput>\n ): Promise<void> {\n if (callCount >= (this.options.maxCalls || DEFAULT_MAX_CALLS)) {\n console.error('[OpenaiAgent] Max calls reached')\n textPromise.resolve('')\n return\n }\n\n this.abortController = new AbortController()\n const signal = this.abortController.signal\n\n // Disable tools if first message\n const enableTools = this.conversation.length > 1\n\n // Build input\n const input: OpenAI.Responses.ResponseInput = this.conversation.map(\n (message) => ({\n role: message.role,\n content: message.content,\n })\n )\n if (toolInputs) {\n input.push(...toolInputs)\n }\n\n try {\n // Generate answer\n const response = await this.openai.responses.create(\n {\n model: this.options.model || DEFAULT_MODEL,\n input,\n temperature: 0.5,\n max_output_tokens: 250,\n stream: true,\n tools: enableTools ? this.tools.map(createToolSchema) : undefined,\n ...this.options.settings,\n },\n { signal }\n )\n const toolOutputs: Array<ToolCall | ToolCallOutput> = []\n let hasAnswer = false\n let skipAnswer = false\n\n // Handle response events\n for await (const event of response) {\n switch (event.type) {\n case 'response.output_text.delta':\n this.log(`Answer chunk: \"${event.delta}\"`)\n stream.write(event.delta)\n break\n\n case 'response.output_text.done':\n this.addAssistantMessage(event.text)\n stream.end()\n textPromise.resolve(event.text)\n hasAnswer = true\n break\n\n case 'response.output_item.done':\n if (event.item.type === 'function_call') {\n const result = await this.executeTool(event.item)\n toolOutputs.push(result.toolCall, result.toolCallOutput)\n if (result.skipAnswer) {\n skipAnswer = true\n }\n }\n break\n\n default:\n break\n }\n }\n\n // Query again in case of tool call\n if (toolOutputs.length > 0 && !hasAnswer && !skipAnswer) {\n await this.generateAnswer(\n stream,\n textPromise,\n callCount + 1,\n toolOutputs\n )\n } else {\n // Ensure promise is resolved (if skipAnswer is true in a tool)\n textPromise.resolve('')\n }\n } catch (error) {\n textPromise.resolve('')\n if (!(error instanceof OpenAI.APIUserAbortError)) {\n console.error('[OpenaiAgent] Error answering:', error)\n }\n }\n }\n\n addTool<Schema extends z.ZodObject>(tool: Tool<Schema>) {\n this.tools.push(tool)\n }\n\n removeTool(name: string) {\n this.tools = this.tools.filter((tool) => tool.name !== name)\n }\n\n getTool(name: string): Tool | undefined {\n return this.tools.find((tool) => tool.name === name)\n }\n\n private getDefaultTools() {\n const tools: Tool[] = []\n if (this.options.autoEndCall) {\n tools.push({\n name: AUTO_END_CALL_TOOL_NAME,\n description:\n typeof this.options.autoEndCall === 'string'\n ? this.options.autoEndCall\n : AUTO_END_CALL_PROMPT,\n callback: () => this.endCall(),\n })\n }\n if (this.options.autoSemanticTurn) {\n tools.push({\n name: AUTO_SEMANTIC_TURN_TOOL_NAME,\n description:\n typeof this.options.autoSemanticTurn === 'string'\n ? this.options.autoSemanticTurn\n : AUTO_SEMANTIC_TURN_PROMPT,\n skipAnswer: true,\n callback: () => this.skipAnswer(),\n })\n }\n if (this.options.autoIgnoreUserNoise) {\n tools.push({\n name: AUTO_IGNORE_USER_NOISE_TOOL_NAME,\n description:\n typeof this.options.autoIgnoreUserNoise === 'string'\n ? this.options.autoIgnoreUserNoise\n : AUTO_IGNORE_USER_NOISE_PROMPT,\n skipAnswer: true,\n callback: () => this.cancelLastUserMessage(),\n })\n }\n return tools\n }\n\n private async executeTool(toolCall: ToolCall) {\n try {\n const tool = this.getTool(toolCall.name)\n if (!tool) {\n throw new Error(`Tool not found \"${toolCall.name}\"`)\n }\n\n this.log('Executing tool:', toolCall.name, toolCall.arguments)\n const args = JSON.parse(toolCall.arguments)\n const result = await tool.callback(args)\n\n return {\n toolCall,\n toolCallOutput: createToolCallOutput(toolCall, result || {}),\n skipAnswer: tool.skipAnswer,\n }\n } catch (error: any) {\n console.error('[OpenaiAgent] Error executing tool:', error)\n return {\n toolCall,\n toolCallOutput: createToolCallOutput(toolCall, {\n error: error.message,\n }),\n }\n }\n }\n\n cancel() {\n if (!this.abortController) return\n this.log('Cancel')\n this.abortController.abort()\n this.abortController = undefined\n }\n}\n","import {\n FunctionTool,\n ResponseInputItem,\n Responses,\n} from 'openai/resources/responses/responses'\nimport { toJSONSchema, z } from 'zod'\n\nexport interface Tool<Schema extends z.ZodObject = z.ZodObject> {\n name: string\n description: string\n parameters?: Schema\n callback: (input: z.infer<Schema>) => any | Promise<any>\n skipAnswer?: boolean\n}\n\nexport type ToolCall = Responses.ResponseFunctionToolCall\nexport type ToolCallOutput = ResponseInputItem.FunctionCallOutput\n\nexport function createToolSchema<Schema extends z.ZodObject>(\n tool: Tool<Schema>\n): FunctionTool {\n return {\n type: 'function',\n name: tool.name,\n description: tool.description,\n strict: true,\n parameters: toJSONSchema(tool.parameters || z.object()),\n }\n}\n\nexport function createToolCallOutput(\n toolCall: ToolCall,\n args: any\n): ToolCallOutput {\n return {\n type: 'function_call_output',\n call_id: toolCall.call_id,\n output: JSON.stringify(args),\n }\n}\n","import { FileSTT } from '@micdrop/server'\n\n/**\n * OpenAI Whisper STT\n *\n * @see https://platform.openai.com/docs/guides/speech-to-text?lang=curl\n */\n\nexport interface OpenaiSTTOptions {\n apiKey: string\n model?: string\n language?: string\n}\n\nconst DEFAULT_MODEL = 'whisper-1'\n\nexport class OpenaiSTT extends FileSTT {\n constructor(private options: OpenaiSTTOptions) {\n super()\n }\n\n async transcribeFile(file: File) {\n // Prepare form data\n const formData = new FormData()\n formData.append('file', file)\n formData.append('model', this.options.model || DEFAULT_MODEL)\n formData.append('response_format', 'text')\n\n if (this.options.language) {\n formData.append('language', this.options.language)\n }\n\n const response = await fetch(\n 'https://api.openai.com/v1/audio/transcriptions',\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.options.apiKey}`,\n },\n body: formData,\n }\n )\n\n if (!response.ok) {\n this.log('Failed to transcribe audio', await response.json())\n throw new Error(`Failed to transcribe audio: ${response.statusText}`)\n }\n\n const transcript = await response.text()\n this.log(`Received transcript: \"${transcript}\"`)\n\n return transcript\n }\n}\n"],"mappings":";AAAA,SAAS,aAAwC;AACjD,OAAO,YAAY;AACnB,SAAS,mBAAmB;;;ACG5B,SAAS,cAAc,SAAS;AAazB,SAAS,iBACd,MACc;AACd,SAAO;AAAA,IACL,MAAM;AAAA,IACN,MAAM,KAAK;AAAA,IACX,aAAa,KAAK;AAAA,IAClB,QAAQ;AAAA,IACR,YAAY,aAAa,KAAK,cAAc,EAAE,OAAO,CAAC;AAAA,EACxD;AACF;AAEO,SAAS,qBACd,UACA,MACgB;AAChB,SAAO;AAAA,IACL,MAAM;AAAA,IACN,SAAS,SAAS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