UNPKG

@nomyx/assistant

Version:

A powerful assistant library and cli for your AI projects. works with Vertex AI (Claude and Gemini)

64 lines (57 loc) 2.11 kB
import axios from 'axios'; import { ChatMessage, ChatOptions, ProviderResponse } from '../../../types/chat'; import { Tool } from '../../../types/tool'; import { OpenAIConfig } from './config'; import { convertMessages, convertToolSchema, convertToolCalls, convertUsage } from './utils'; export async function chat(config: OpenAIConfig, messages: ChatMessage[], options: ChatOptions, tools?: Tool[]): Promise<ProviderResponse> { const logger = config.getLogger(); try { const requestBody: any = { model: config.getModel(), messages: convertMessages(messages, config.getModel()), max_tokens: options.maxTokens, temperature: options.temperature, }; if (tools && tools.length > 0) { requestBody.tools = tools .map(tool => convertToolSchema(tool.getSchema())) .map(schema => ({ type: 'function', function: schema })); requestBody.tool_choice = 'auto'; } const response = await axios.post( 'https://api.openai.com/v1/chat/completions', requestBody, { headers: { 'Authorization': `Bearer ${config.getApiKey()}`, 'Content-Type': 'application/json', }, } ); logger.debug('OpenAI response received', { content: response.data.choices[0].message?.content, toolCalls: response.data.choices[0].message?.tool_calls }); const providerResponse: ProviderResponse = { content: response.data.choices[0].message?.content || '', toolCalls: convertToolCalls(response.data.choices[0].message?.tool_calls), usage: convertUsage(response.data.usage), }; return providerResponse; } catch (error) { handleError(config, error); throw error; } } function handleError(config: OpenAIConfig, error: any): void { const logger = config.getLogger(); if (axios.isAxiosError(error)) { logger.error('OpenAIProvider: API request failed:', { status: error.response?.status, message: error.message, data: error.response?.data }); } else { logger.error('OpenAIProvider: Unexpected error:', error); } }