(request: NextRequest)
| 12 | |
| 13 | const chatApiLogger = serverLogger.withTag("chat-api") |
| 14 | export async function POST(request: NextRequest) { |
| 15 | try { |
| 16 | const { searchParams } = new URL(request.url) |
| 17 | const provider = searchParams.get("id") |
| 18 | const body = await request.json() |
| 19 | const messages: Message[] = body.messages || [] |
| 20 | |
| 21 | if (!messages.length) { |
| 22 | return NextResponse.json( |
| 23 | { |
| 24 | type: "error", |
| 25 | error: "No messages provided", |
| 26 | }, |
| 27 | { status: 400 }, |
| 28 | ) |
| 29 | } |
| 30 | |
| 31 | const openai = createOpenAI({ |
| 32 | apiKey: process.env.OPENAI_API_KEY, |
| 33 | baseURL: process.env.OPENAI_BASE_URL, |
| 34 | }) |
| 35 | |
| 36 | const tools = await (async function () { |
| 37 | if (!provider) { |
| 38 | return [] |
| 39 | } |
| 40 | |
| 41 | const accessToken = await getServerToken() |
| 42 | |
| 43 | const transport = new StreamableHTTPClientTransport( |
| 44 | new URL(`/api/mcp/${provider}`, baseURL), |
| 45 | { |
| 46 | requestInit: { |
| 47 | headers: { |
| 48 | Authorization: `Bearer ${accessToken}`, |
| 49 | }, |
| 50 | }, |
| 51 | }, |
| 52 | ) |
| 53 | |
| 54 | const customClient = await experimental_createMCPClient({ transport }) |
| 55 | const tools = await customClient.tools() |
| 56 | |
| 57 | return tools |
| 58 | })() |
| 59 | |
| 60 | const response = streamText({ |
| 61 | model: openai("gpt-4.1"), |
| 62 | messages, |
| 63 | tools, |
| 64 | toolCallStreaming: true, |
| 65 | maxSteps: 5, |
| 66 | } as any) |
| 67 | |
| 68 | return response.toDataStreamResponse() |
| 69 | } catch (error) { |
| 70 | chatApiLogger.error("Error in chat API", { error }) |
| 71 | return NextResponse.json({ error: "Internal server error" }, { status: 500 }) |
nothing calls this directly
no test coverage detected