|
| 1 | +import { Agent } from '@agentic-kit/agent'; |
| 2 | +import { OpenAIAdapter } from '@agentic-kit/openai'; |
| 3 | +import type { Message } from 'agentic-kit'; |
| 4 | + |
| 5 | +import { tools } from '@/lib/tools'; |
| 6 | + |
| 7 | +export const runtime = 'nodejs'; |
| 8 | +export const dynamic = 'force-dynamic'; |
| 9 | + |
| 10 | +const SYSTEM_PROMPT = [ |
| 11 | + 'You are a friendly assistant in a chat-app demo.', |
| 12 | + 'You have two tools available:', |
| 13 | + '- get_current_time(timezone?): returns the current time in the requested IANA timezone.', |
| 14 | + '- send_email(to, subject, body): drafts an email. The user must approve before it is sent.', |
| 15 | + 'When the user asks for the current time anywhere, call get_current_time.', |
| 16 | + 'When the user asks you to send an email, call send_email exactly once and wait for the user decision.', |
| 17 | + 'Keep replies short.', |
| 18 | +].join('\n'); |
| 19 | + |
| 20 | +interface RequestBody { |
| 21 | + messages: Message[]; |
| 22 | +} |
| 23 | + |
| 24 | +function lastMessageHasPendingDecision(messages: Message[]): boolean { |
| 25 | + const last = messages[messages.length - 1]; |
| 26 | + if (!last || last.role !== 'assistant') return false; |
| 27 | + const completedToolCallIds = new Set( |
| 28 | + messages |
| 29 | + .filter((m): m is Extract<Message, { role: 'toolResult' }> => m.role === 'toolResult') |
| 30 | + .map((m) => m.toolCallId) |
| 31 | + ); |
| 32 | + return last.content.some( |
| 33 | + (block) => |
| 34 | + block.type === 'toolCall' && |
| 35 | + !completedToolCallIds.has(block.id) && |
| 36 | + 'decision' in block && |
| 37 | + block.decision !== undefined |
| 38 | + ); |
| 39 | +} |
| 40 | + |
| 41 | +export async function POST(req: Request): Promise<Response> { |
| 42 | + const apiKey = process.env.OPENAI_API_KEY ?? process.env.LLM_API_KEY; |
| 43 | + const baseUrl = |
| 44 | + process.env.OPENAI_BASE_URL ?? process.env.LLM_BASE_URL ?? 'https://api.openai.com/v1'; |
| 45 | + const modelId = process.env.OPENAI_MODEL ?? process.env.LLM_MODEL ?? 'gpt-5.4-mini'; |
| 46 | + |
| 47 | + if (!apiKey) { |
| 48 | + return new Response('OPENAI_API_KEY (or LLM_API_KEY) is not set on the server', { |
| 49 | + status: 500, |
| 50 | + }); |
| 51 | + } |
| 52 | + |
| 53 | + let body: RequestBody; |
| 54 | + try { |
| 55 | + body = (await req.json()) as RequestBody; |
| 56 | + } catch { |
| 57 | + return new Response('Invalid JSON body', { status: 400 }); |
| 58 | + } |
| 59 | + |
| 60 | + const messages = Array.isArray(body.messages) ? body.messages : []; |
| 61 | + if (messages.length === 0) { |
| 62 | + return new Response('Empty messages', { status: 400 }); |
| 63 | + } |
| 64 | + |
| 65 | + const adapter = new OpenAIAdapter({ apiKey, baseUrl }); |
| 66 | + const model = adapter.createModel(modelId); |
| 67 | + |
| 68 | + const agent = new Agent({ |
| 69 | + initialState: { model, tools, systemPrompt: SYSTEM_PROMPT }, |
| 70 | + streamFn: (m, ctx, opts) => adapter.stream(m, ctx, opts), |
| 71 | + maxSteps: 5, |
| 72 | + }); |
| 73 | + |
| 74 | + const isResume = lastMessageHasPendingDecision(messages); |
| 75 | + |
| 76 | + if (isResume) { |
| 77 | + agent.replaceMessages(messages); |
| 78 | + try { |
| 79 | + const handle = agent.continue(); |
| 80 | + return handle.toResponse(); |
| 81 | + } catch (err) { |
| 82 | + return new Response(`continue() failed: ${(err as Error).message}`, { status: 400 }); |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + const last = messages[messages.length - 1]; |
| 87 | + if (last.role !== 'user') { |
| 88 | + return new Response('Last message must be a user message when not resuming', { status: 400 }); |
| 89 | + } |
| 90 | + |
| 91 | + agent.replaceMessages(messages.slice(0, -1)); |
| 92 | + const handle = agent.prompt(last); |
| 93 | + return handle.toResponse(); |
| 94 | +} |
0 commit comments