|
| 1 | +import { Buffer } from 'node:buffer' |
| 2 | +import { timingSafeEqual } from 'node:crypto' |
| 3 | +import { Agent, OpenAIChatCompletionsModel, run } from '@openai/agents' |
| 4 | +import OpenAI from 'openai' |
| 5 | +import { getPartnersByCityTool, getPartnersTool } from '~~/server/services/tools' |
| 6 | + |
| 7 | +export default defineEventHandler(async (event) => { |
| 8 | + try { |
| 9 | + const { ai } = useRuntimeConfig() |
| 10 | + |
| 11 | + // Requires bearer token |
| 12 | + const bearer = getHeader(event, 'authorization') |
| 13 | + if (!bearer?.startsWith('Bearer ')) { |
| 14 | + throw createError({ |
| 15 | + statusCode: 401, |
| 16 | + message: 'Unauthorized', |
| 17 | + }) |
| 18 | + } |
| 19 | + |
| 20 | + const token = bearer.slice(7) // Remove 'Bearer ' prefix |
| 21 | + if (!ai.serviceToken || !timingSafeEqual(Buffer.from(token), Buffer.from(ai.serviceToken))) { |
| 22 | + throw createError({ |
| 23 | + statusCode: 401, |
| 24 | + message: 'Unauthorized', |
| 25 | + }) |
| 26 | + } |
| 27 | + |
| 28 | + const body = await readBody(event) |
| 29 | + if (!body?.message) { |
| 30 | + throw createError({ |
| 31 | + statusCode: 400, |
| 32 | + message: 'Message is required', |
| 33 | + }) |
| 34 | + } |
| 35 | + |
| 36 | + const client = new OpenAI({ |
| 37 | + apiKey: ai.apiKey, |
| 38 | + baseURL: ai.baseUrl, |
| 39 | + }) |
| 40 | + |
| 41 | + const agent = new Agent({ |
| 42 | + name: 'Дата агент сети доставок "Суши Love"', |
| 43 | + instructions: 'У тебя есть доступ к данным партнеров сети. Отвечай всегда на русском в мужском роде.', |
| 44 | + model: new OpenAIChatCompletionsModel(client, ai.model), |
| 45 | + tools: [ |
| 46 | + getPartnersTool, |
| 47 | + getPartnersByCityTool, |
| 48 | + ], |
| 49 | + }) |
| 50 | + |
| 51 | + const result = await run(agent, body.message) |
| 52 | + |
| 53 | + return { |
| 54 | + ok: true, |
| 55 | + message: result.finalOutput, |
| 56 | + } |
| 57 | + } catch (error) { |
| 58 | + throw errorResolver(error) |
| 59 | + } |
| 60 | +}) |
0 commit comments