mono/packages/kbot/src/commands/run-responses.ts
2025-06-28 12:45:24 +02:00

64 lines
1.9 KiB
TypeScript

import OpenAI from 'openai'
import { ChatCompletionMessageParam } from 'openai/resources/index.mjs'
import { IKBotTask } from '@polymech/ai-tools'
import { sync as readFS } from '@polymech/fs/read'
import { sync as exists } from '@polymech/fs/exists'
import { onCompletion } from './run-completion.js'
export const runResponses = async (client: OpenAI, params: any, options: IKBotTask) => {
if (options.dry) {
options.logger?.info('Dry run - skipping API call')
return false
}
const input = params.messages
.map((m: ChatCompletionMessageParam) => m.content)
.join('\n\n')
const tools = [
{
type: "web_search",
user_location: {
type: "approximate",
country: "ES",
city: "Sentmenant",
region: "Barcelona",
},
},
// { type: "web_search_preview" },
]
let format = null;
if (exists(options.format)) {
const content = readFS(options.format);
format = JSON.parse(content.toString());
}
try {
const response = await client.responses.create({
model: options.model,
input,
stream: false,
parallel_tool_calls: false,
tools: tools as any,
text: {
format: {
type: "json_schema",
name: "format",
schema: format,
strict: false
}
}
})
if (!response || !response.output_text) {
return ''
}
let result = response.output_text
result = await onCompletion(result, options)
return result
} catch (e) {
options.logger?.error(`Error running responses mode: ${e.message}`, e.stack)
}
}