import OpenAI from "openai"; import type { ChatCompletionMessageParam } from "openai/resources/chat/completions"; const PLANNER_SYSTEM_PROMPT = `You are a tool-use planner. Given a user message and available tools, decide: 1. Does this request need any tools? (simple questions like "what is 2+2" do not) 2. If yes, which specific tools are needed? 3. What is the execution plan? Respond in this exact JSON format: {"needs_tools": boolean, "tools_needed": ["tool_name", ...], "plan": "brief description"} Only include tools that are actually necessary. Do not over-plan.`; export interface PlanResult { needsTools: boolean; toolsNeeded: string[]; plan: string; } export async function planToolUsage( client: OpenAI, model: string, userMessage: string, availableTools: string[] ): Promise { try { const response = await client.chat.completions.create({ model, messages: [ { role: "system", content: PLANNER_SYSTEM_PROMPT }, { role: "user", content: `Available tools: ${availableTools.join(", ")}\n\nUser message: ${userMessage}`, }, ], max_tokens: 200, temperature: 0, }); const content = response.choices[0]?.message?.content?.trim() ?? ""; const jsonMatch = content.match(/\{[\s\S]*\}/); if (!jsonMatch) { return { needsTools: true, toolsNeeded: [], plan: "proceed with all tools" }; } const parsed = JSON.parse(jsonMatch[0]); return { needsTools: parsed.needs_tools ?? true, toolsNeeded: parsed.tools_needed ?? [], plan: parsed.plan ?? "", }; } catch { return { needsTools: true, toolsNeeded: [], plan: "" }; } }