7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
fix(fusion): support tool calls in fusion mode
Tashfeenb10e2602d9dd
diff --git a/server/src/__tests__/routes/fusion.test.ts b/server/src/__tests__/routes/fusion.test.tsindex 3f8af961..a7d2395e 100644--- a/server/src/__tests__/routes/fusion.test.ts+++ b/server/src/__tests__/routes/fusion.test.ts@@ -44,10 +44,20 @@ function sseBody(content: string): ReadableStream<Uint8Array> {return new ReadableStream({ start(c) { for (const f of frames) c.enqueue(enc.encode(f)); c.close(); } });}-function mockUpstreams(answers: Record<string, string>, rateLimited: Set<string> = new Set(), streamAnswers: Record<string, string> = {}) {+type MockAnswer = string | {+ content?: string | null;+ tool_calls?: any[];+ finish_reason?: string | null;+ usage?: { prompt_tokens: number; completion_tokens: number; total_tokens: number };+};++function mockUpstreams(answers: Record<string, MockAnswer>, rateLimited: Set<string> = new Set(), streamAnswers: Record<string, string> = {}) {const origFetch = global.fetch;+ const calls: Array<{ url: string; body: any }> = [];vi.spyOn(global, 'fetch').mockImplementation(async (url, init) => {const u = typeof url === 'string' ? url : url.toString();+ const body = typeof (init as any)?.body === 'string' ? JSON.parse((init as any).body) : null;+ calls.push({ url: u, body });for (const host of rateLimited) {if (u.includes(host)) {return { ok: false, status: 429, headers: new Headers(), text: () => Promise.resolve('rate limited') } as any;@@ -61,18 +71,31 @@ function mockUpstreams(answers: Record<string, string>, rateLimited: Set<string>}for (const [host, content] of Object.entries(answers)) {if (u.includes(host)) {+ const message = typeof content === 'string'+ ? { role: 'assistant', content }+ : {+ role: 'assistant',+ content: content.content ?? null,+ ...(content.tool_calls ? { tool_calls: content.tool_calls } : {}),+ };+ const finishReason = typeof content === 'string'+ ? 'stop'+ : content.finish_reason ?? (content.tool_calls?.length ? 'tool_calls' : 'stop');return {ok: true,json: () => Promise.resolve({id: 'chatcmpl-x', object: 'chat.completion', created: 1, model: 'm',- choices: [{ index: 0, message: { role: 'assistant', content }, finish_reason: 'stop' }],- usage: { prompt_tokens: 5, completion_tokens: 7, total_tokens: 12 },+ choices: [{ index: 0, message, finish_reason: finishReason }],+ usage: typeof content === 'string'+ ? { prompt_tokens: 5, completion_tokens: 7, total_tokens: 12 }+ : content.usage ?? { prompt_tokens: 5, completion_tokens: 7, total_tokens: 12 },}),} as any;}}return origFetch(url as any, init as any);});+ return { calls };}describe('isFusionModel', () => {@@ -103,6 +126,9 @@ describe('fusion route (/v1/chat/completions, model: "fusion")', () => {let groqModel: string;let cerebrasModel: string;let openrouterModel: string;+ let toolGroqModel: string;+ let toolCerebrasModel: string;+ let nonToolOpenrouterModel: string;beforeAll(() => {process.env.ENCRYPTION_KEY = '0'.repeat(64);@@ -110,12 +136,15 @@ describe('fusion route (/v1/chat/completions, model: "fusion")', () => {app = createApp();dashToken = mintDashboardToken();const db = getDb();- const pick = (platform: string) => (db.prepare(- 'SELECT m.model_id FROM models m WHERE m.platform = ? AND m.enabled = 1 ORDER BY m.intelligence_rank LIMIT 1',+ const pick = (platform: string, extraWhere = '') => (db.prepare(+ `SELECT m.model_id FROM models m WHERE m.platform = ? AND m.enabled = 1 ${extraWhere} ORDER BY m.intelligence_rank LIMIT 1`,).get(platform) as { model_id: string }).model_id;groqModel = pick('groq');cerebrasModel = pick('cerebras');openrouterModel = pick('openrouter');+ toolGroqModel = pick('groq', 'AND m.supports_tools = 1');+ toolCerebrasModel = pick('cerebras', 'AND m.supports_tools = 1');+ nonToolOpenrouterModel = pick('openrouter', 'AND m.supports_tools = 0');});beforeEach(async () => {@@ -217,14 +246,82 @@ describe('fusion route (/v1/chat/completions, model: "fusion")', () => {expect(body.x_fusion.dropped.some((d: string) => d.includes('no-such-model'))).toBe(true);});- it('rejects tool-bearing fusion requests with 422', async () => {+ it('returns the first structured panel tool_call instead of judging actions', async () => {+ const toolCalls = [{+ id: 'call_weather',+ type: 'function',+ function: { name: 'get_weather', arguments: '{"city":"Karachi"}' },+ }];+ const upstream = mockUpstreams({+ 'api.groq.com': { content: null, tool_calls: toolCalls, finish_reason: 'stop' },+ 'api.cerebras.ai': 'cerebras text should not be judged when a tool call wins',+ 'openrouter.ai': 'JUDGE SHOULD NOT RUN',+ });+const { status, body } = await request(app, 'POST', '/v1/chat/completions', {model: 'fusion',- messages: [{ role: 'user', content: 'q' }],- tools: [{ type: 'function', function: { name: 'f', parameters: {} } }],+ messages: [{ role: 'user', content: 'Weather in Karachi?' }],+ tools: [{+ type: 'function',+ function: {+ name: 'get_weather',+ description: 'Get current weather',+ parameters: {+ type: 'object',+ properties: { city: { type: 'string' } },+ required: ['city'],+ },+ },+ }],+ tool_choice: 'required',+ parallel_tool_calls: true,+ fusion: { models: [toolGroqModel, toolCerebrasModel], judge: openrouterModel, expose_panel: true },+ }, authHeaders());++ expect(status).toBe(200);+ expect(body.model).toBe('fusion');+ expect(body.choices[0].finish_reason).toBe('tool_calls');+ expect(body.choices[0].message.content).toBeNull();+ expect(body.choices[0].message.tool_calls).toEqual(toolCalls);+ expect(body._fusion.tool_call_winner).toEqual({ platform: 'groq', model: toolGroqModel });+ expect(body.x_fusion.tool_call_winner).toEqual({ platform: 'groq', model: toolGroqModel });+ expect(body.x_fusion.panel.find((p: any) => p.platform === 'groq').tool_calls).toEqual(toolCalls);++ const groqCall = upstream.calls.find(c => c.url.includes('api.groq.com'));+ expect(groqCall?.body.tools).toHaveLength(1);+ expect(groqCall?.body.tool_choice).toBe('required');+ expect(groqCall?.body.parallel_tool_calls).toBe(true);+ expect(upstream.calls.some(c => c.url.includes('openrouter.ai'))).toBe(false);+ });++ it('keeps tool-bearing fusion panels on tool-capable models even with tool_choice none', async () => {+ const upstream = mockUpstreams({+ 'api.groq.com': 'groq handled a no-tool turn',+ 'openrouter.ai': 'NON-TOOL MODEL SHOULD NOT RUN',+ });++ const { status, body } = await request(app, 'POST', '/v1/chat/completions', {+ model: 'fusion',+ messages: [{ role: 'user', content: 'Answer without calling a tool.' }],+ tools: [{+ type: 'function',+ function: {+ name: 'get_weather',+ parameters: { type: 'object', properties: { city: { type: 'string' } } },+ },+ }],+ tool_choice: 'none',+ fusion: { models: [nonToolOpenrouterModel, toolGroqModel], expose_panel: true },}, authHeaders());- expect(status).toBe(422);- expect(body.error.code).toBe('fusion_no_tools');++ expect(status).toBe(200);+ expect(body.choices[0].message.content).toBe('groq handled a no-tool turn');+ expect(body.x_fusion.dropped).toContain(`${nonToolOpenrouterModel} (no tool-calling support)`);+ expect(upstream.calls.some(c => c.url.includes('openrouter.ai'))).toBe(false);++ const groqCall = upstream.calls.find(c => c.url.includes('api.groq.com'));+ expect(groqCall?.body.tools).toHaveLength(1);+ expect(groqCall?.body.tool_choice).toBe('none');});it('tags every panel/judge sub-call with requested_model="fusion"', async () => {@@ -396,9 +493,11 @@ describe('fusion route (/v1/chat/completions, model: "fusion")', () => {// Additive _fusion frames: one panel frame per member, plus a judge frame.const panelFrames = frames.filter(f => f._fusion?.event === 'panel');expect(panelFrames).toHaveLength(2);+ expect(panelFrames.every(f => Array.isArray(f.choices) && f.choices[0]?.delta && f.choices[0]?.finish_reason === null)).toBe(true);expect(panelFrames.map(f => f._fusion.model).sort()).toEqual([groqModel, cerebrasModel].sort());expect(panelFrames.every(f => f._fusion.status === 'ok' && typeof f._fusion.content === 'string')).toBe(true);const judgeFrame = frames.find(f => f._fusion?.event === 'judge');+ expect(Array.isArray(judgeFrame.choices)).toBe(true);expect(judgeFrame._fusion).toMatchObject({ platform: 'openrouter', model: openrouterModel });// The final answer still streams as standard content deltas + terminal stop.@@ -408,6 +507,54 @@ describe('fusion route (/v1/chat/completions, model: "fusion")', () => {// _fusion panel frames precede the final content frame.expect(text.indexOf('"event":"panel"')).toBeLessThan(text.indexOf('STREAMED SYNTHESIS'));});++ it('streams fusion tool_calls as OpenAI chunks with terminal tool_calls finish_reason', async () => {+ const toolCalls = [{+ id: 'call_weather_stream',+ type: 'function',+ function: { name: 'get_weather', arguments: '{"city":"Dublin"}' },+ }];+ mockUpstreams({+ 'api.groq.com': { content: null, tool_calls: toolCalls, finish_reason: 'tool_calls' },+ 'api.cerebras.ai': 'text answer loses to structured tool call',+ 'openrouter.ai': 'JUDGE SHOULD NOT RUN',+ });++ const { status, text } = await request(app, 'POST', '/v1/chat/completions', {+ model: 'fusion',+ stream: true,+ messages: [{ role: 'user', content: 'Weather in Dublin?' }],+ tools: [{+ type: 'function',+ function: {+ name: 'get_weather',+ parameters: {+ type: 'object',+ properties: { city: { type: 'string' } },+ required: ['city'],+ },+ },+ }],+ tool_choice: 'required',+ fusion: { models: [toolGroqModel, toolCerebrasModel], judge: openrouterModel },+ }, authHeaders());+ expect(status).toBe(200);++ const frames = text.split('\n')+ .filter(l => l.startsWith('data: ') && l.slice(6).trim() !== '[DONE]')+ .map(l => JSON.parse(l.slice(6)));++ const traceFrames = frames.filter(f => f._fusion);+ expect(traceFrames.length).toBeGreaterThan(0);+ expect(traceFrames.every(f => Array.isArray(f.choices))).toBe(true);+ expect(traceFrames.some(f => f._fusion?.tool_calls?.[0]?.id === 'call_weather_stream')).toBe(true);++ const toolFrame = frames.find(f => f.choices?.[0]?.delta?.tool_calls);+ expect(toolFrame.choices[0].delta.tool_calls).toEqual(toolCalls);+ expect(frames.map(f => f.choices?.[0]?.finish_reason).filter(Boolean)).toEqual(['tool_calls']);+ expect(text).not.toContain('JUDGE SHOULD NOT RUN');+ expect(text.trimEnd().endsWith('data: [DONE]')).toBe(true);+ });});describe('familyKey', () => {diff --git a/server/src/routes/proxy.ts b/server/src/routes/proxy.tsindex 65aa964e..708da15b 100644--- a/server/src/routes/proxy.ts+++ b/server/src/routes/proxy.ts@@ -2,7 +2,7 @@ import crypto from 'crypto';import { Router } from 'express';import type { Request, Response } from 'express';import { z } from 'zod';-import type { ChatMessage, ModelListRow } from '@freellmapi/shared/types.js';+import type { ChatMessage, ChatToolCall, ModelListRow } from '@freellmapi/shared/types.js';import { routeRequest, resolveRoutingChain, resolveModelGroupCandidates, recordRateLimitHit, recordSuccess, hasEnabledVisionModel, hasEnabledToolsModel, type RouteResult, type ResolvedChain, type ChainRow } from '../services/router.js';import { recordRequest, recordTokens, setCooldown, getCooldownDurationForLimit, PAYMENT_REQUIRED_COOLDOWN_MS, MODEL_FORBIDDEN_COOLDOWN_MS, learnLimitFromError } from '../services/ratelimit.js';import { runEmbeddings, EmbeddingsError } from '../services/embeddings.js';@@ -1105,18 +1105,14 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {// in parallel, then a judge synthesizes one answer. It routes each panel/judge// sub-call through the normal path (cooldowns, quotas, analytics), so it// behaves like a normal model from the client's side — just K+1x the tokens.- // v1 has no tools/vision/streaming-panel; reject the first two up front and- // replay the synthesized answer as a single SSE turn when stream is set.+ // Vision is still rejected up front; tool requests run on tool-capable panel+ // members and return the first structured tool call directly.if (isFusionModel(requestedModel)) {if (hasImage) {res.status(422).json({ error: { message: 'Fusion does not support image input yet. Use a vision model directly.', type: 'invalid_request_error', code: 'fusion_no_vision' } });return;}- if (wantsTools) {- res.status(422).json({ error: { message: 'Fusion does not support tool calling yet. Use a tool-capable model directly.', type: 'invalid_request_error', code: 'fusion_no_tools' } });- return;- }- const fusionOptions = { temperature, max_tokens, top_p, stop };+ const fusionOptions = { temperature, max_tokens, top_p, stop, tools, tool_choice, parallel_tool_calls };const fusionConfig = parsed.data.fusion ?? {};if (stream) {@@ -1142,8 +1138,16 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {hooks: {// `a` already carries a sanitized error for failed slots; content is// the model's own answer and is forwarded as-is.- onPanel: (a) => writeFrame({ _fusion: { event: 'panel', ...a } }),- onJudge: (j) => writeFrame({ _fusion: { event: 'judge', ...j } }),+ onPanel: (a) => writeFrame({+ ...base,+ choices: [{ index: 0, delta: {}, finish_reason: null }],+ _fusion: { event: 'panel', ...a },+ }),+ onJudge: (j) => writeFrame({+ ...base,+ choices: [{ index: 0, delta: {}, finish_reason: null }],+ _fusion: { event: 'judge', ...j },+ }),// Stream the judge's synthesis live as standard content deltas, so// the final answer appears as it's written instead of after the wait.onJudgeDelta: (delta) => {@@ -1154,12 +1158,21 @@ proxyRouter.post('/chat/completions', async (req: Request, res: Response) => {});// best_of / single-survivor / judge-fell-back-to-best-of never streamed// a delta — emit the final answer as one chunk in that case.- if (!answerStarted) {- const finalText = contentToString(response.choices[0]?.message?.content ?? '');+ const finalMsg = response.choices[0]?.message;+ const finalToolCalls = (finalMsg as { tool_calls?: ChatToolCall[] } | undefined)?.tool_calls;+ const hasFinalToolCalls = Array.isArray(finalToolCalls) && finalToolCalls.length > 0;+ if (hasFinalToolCalls) {writeFrame({ ...base, choices: [{ index: 0, delta: { role: 'assistant' }, finish_reason: null }] });- writeFrame({ ...base, choices: [{ index: 0, delta: { content: finalText }, finish_reason: null }] });+ writeFrame({ ...base, choices: [{ index: 0, delta: { tool_calls: finalToolCalls }, finish_reason: null }] });+ writeFrame({ ...base, choices: [{ index: 0, delta: {}, finish_reason: 'tool_calls' }], usage: response.usage });+ } else {+ if (!answerStarted) {+ const finalText = contentToString(finalMsg?.content ?? '');+ writeFrame({ ...base, choices: [{ index: 0, delta: { role: 'assistant' }, finish_reason: null }] });+ writeFrame({ ...base, choices: [{ index: 0, delta: { content: finalText }, finish_reason: null }] });+ }+ writeFrame({ ...base, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], usage: response.usage });}- writeFrame({ ...base, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], usage: response.usage });} catch (err: any) {const message = err instanceof FusionError ? err.message : `fusion error: ${sanitizeProviderErrorMessage(err?.message)}`;const type = err instanceof FusionError && err.status === 429 ? 'rate_limit_error' : 'server_error';diff --git a/server/src/services/fusion.ts b/server/src/services/fusion.tsindex 01b29286..fc25b1f5 100644--- a/server/src/services/fusion.ts+++ b/server/src/services/fusion.ts@@ -1,5 +1,5 @@import { z } from 'zod';-import type { ChatMessage, ChatCompletionResponse, TokenUsage } from '@freellmapi/shared/types.js';+import type { ChatMessage, ChatCompletionChoice, ChatCompletionResponse, ChatToolCall, TokenUsage } from '@freellmapi/shared/types.js';import {routePinnedModel, routeRequest, getOrderedFusionChain, resolveFusionCandidate,recordRateLimitHit, recordSuccess, type RouteResult, type FusionCandidate,@@ -162,6 +162,8 @@ interface PanelAnswer {displayName: string;status: 'ok' | 'failed';content?: string;+ toolCalls?: ChatToolCall[];+ rawChoice?: ChatCompletionChoice;error?: string;usage?: TokenUsage;}@@ -170,6 +172,8 @@ interface CallOutcome {ok: boolean;route?: RouteResult;text?: string;+ toolCalls?: ChatToolCall[];+ rawChoice?: ChatCompletionChoice;usage?: TokenUsage;error?: string;}@@ -217,9 +221,12 @@ async function runModelCall(const startedAt = Date.now();try {const result = await route.provider.chatCompletion(route.apiKey, messages, route.modelId, options);- const text = contentToString(result.choices?.[0]?.message?.content ?? '');+ const choice = result.choices?.[0];+ const text = contentToString(choice?.message?.content ?? '');+ const toolCalls = choice?.message?.tool_calls;+ const hasToolCalls = Array.isArray(toolCalls) && toolCalls.length > 0;- if (!text) {+ if (!text && !hasToolCalls) {// Empty completion — fail over like the main proxy path does.logRequest(route.platform, route.modelId, route.keyId, 'error', 0, 0, Date.now() - startedAt, 'empty completion (fusion)', null, FUSION_TAG);skipKeys.add(`${route.platform}:${route.modelId}:${route.keyId}`);@@ -234,7 +241,14 @@ async function runModelCall(recordTokens(route.platform, route.modelId, route.keyId, usage.total_tokens);recordSuccess(route.modelDbId);logRequest(route.platform, route.modelId, route.keyId, 'success', usage.prompt_tokens ?? 0, usage.completion_tokens ?? 0, Date.now() - startedAt, null, null, FUSION_TAG);- return { ok: true, route, text, usage };+ return {+ ok: true,+ route,+ text,+ toolCalls: hasToolCalls ? toolCalls : undefined,+ rawChoice: hasToolCalls ? choice : undefined,+ usage,+ };} catch (err: any) {const safe = sanitizeProviderErrorMessage(err?.message);logRequest(route.platform, route.modelId, route.keyId, 'error', 0, 0, Date.now() - startedAt, safe, null, FUSION_TAG);@@ -405,7 +419,7 @@ export function diversifyChain(ordered: FusionCandidate[]): FusionCandidate[] {* both the panel and its refills span genuinely different perspectives before* doubling up on either axis.*/-function selectPanel(config: FusionConfig): { panel: FusionCandidate[]; overflow: FusionCandidate[]; dropped: string[] } {+function selectPanel(config: FusionConfig, requirements: { requireTools?: boolean } = {}): { panel: FusionCandidate[]; overflow: FusionCandidate[]; dropped: string[] } {const maxK = panelMaxK();if (config.models && config.models.length > 0) {@@ -416,6 +430,7 @@ function selectPanel(config: FusionConfig): { panel: FusionCandidate[]; overflowif (panel.length >= maxK) { dropped.push(`${id} (over cap of ${maxK})`); continue; }const cand = resolveFusionCandidate(id);if (!cand) { dropped.push(`${id} (unknown or disabled)`); continue; }+ if (requirements.requireTools && !cand.supportsTools) { dropped.push(`${id} (no tool-calling support)`); continue; }if (seen.has(cand.modelDbId)) continue; // de-dup repeatsseen.add(cand.modelDbId);panel.push(cand);@@ -425,7 +440,7 @@ function selectPanel(config: FusionConfig): { panel: FusionCandidate[]; overflow}const k = Math.min(Math.max(config.k ?? panelDefaultK(), 1), maxK);- const ordered = getOrderedFusionChain();+ const ordered = getOrderedFusionChain().filter(c => !requirements.requireTools || c.supportsTools);// Diversity-first ordering of the whole servable chain along provider AND// model family (see diversifyChain). The first K are the panel; the rest are@@ -494,7 +509,7 @@ export class FusionError extends Error {// settles and when the judge succeeds, so a client (the Playground) can show the// panel answers arriving and the judge kicking in before the final answer.export interface FusionHooks {- onPanel?: (a: { platform: string; model: string; status: 'ok' | 'failed'; content?: string; error?: string }) => void;+ onPanel?: (a: { platform: string; model: string; status: 'ok' | 'failed'; content?: string; tool_calls?: ChatToolCall[]; error?: string }) => void;onJudge?: (j: { platform: string; model: string }) => void;// When set, the judge STREAMS: onJudge fires at the first token (so the trace// shows the judge model) and onJudgeDelta fires for each token, so the final@@ -515,7 +530,8 @@ export async function runFusion(params: {const config = resolveEffectiveConfig(params.config);const strategy = config.strategy ?? 'synthesize';- const { panel, overflow, dropped } = selectPanel(config);+ const requireTools = (options.tools?.length ?? 0) > 0;+ const { panel, overflow, dropped } = selectPanel(config, { requireTools });if (panel.length === 0) {throw new FusionError('fusion: no usable models for the panel. Provide `fusion.models` with enabled model ids, or enable models in the Fallback Chain.',@@ -533,9 +549,19 @@ export async function runFusion(params: {messages, options, estimatedTokens, MAX_SLOT_ATTEMPTS,).then((outcome): PanelAnswer => {const answer: PanelAnswer = outcome.ok- ? { modelDbId: cand.modelDbId, platform: cand.platform, modelId: cand.modelId, displayName: cand.displayName, status: 'ok', content: outcome.text, usage: outcome.usage }+ ? {+ modelDbId: cand.modelDbId,+ platform: cand.platform,+ modelId: cand.modelId,+ displayName: cand.displayName,+ status: 'ok',+ content: outcome.text,+ toolCalls: outcome.toolCalls,+ rawChoice: outcome.rawChoice,+ usage: outcome.usage,+ }: { modelDbId: cand.modelDbId, platform: cand.platform, modelId: cand.modelId, displayName: cand.displayName, status: 'failed', error: outcome.error };- hooks?.onPanel?.({ platform: answer.platform, model: answer.modelId, status: answer.status, content: answer.content, error: answer.error });+ hooks?.onPanel?.({ platform: answer.platform, model: answer.modelId, status: answer.status, content: answer.content, tool_calls: answer.toolCalls, error: answer.error });return answer;});@@ -560,11 +586,11 @@ export async function runFusion(params: {? s.value: { modelDbId: wave[i].modelDbId, platform: wave[i].platform, modelId: wave[i].modelId, displayName: wave[i].displayName, status: 'failed', error: sanitizeProviderErrorMessage((s as PromiseRejectedResult).reason?.message) };answers.push(a);- if (a.status === 'ok' && a.content) okCount++;+ if (a.status === 'ok' && (a.content || (a.toolCalls?.length ?? 0) > 0)) okCount++;});}- const survivors = answers.filter(a => a.status === 'ok' && a.content);+ const survivors = answers.filter(a => a.status === 'ok' && (a.content || (a.toolCalls?.length ?? 0) > 0));let totalUsage: TokenUsage = { ...ZERO_USAGE };for (const a of survivors) totalUsage = addUsage(totalUsage, a.usage);@@ -575,21 +601,77 @@ export async function runFusion(params: {);}+ // Tool calls are actions, not prose. They cannot be safely synthesized across+ // models, so the first panel survivor that returned structured tool_calls+ // wins and the judge is skipped.+ const toolCallWinner = survivors.find(a => (a.toolCalls?.length ?? 0) > 0 && a.rawChoice);+ if (toolCallWinner) {+ const choice: ChatCompletionChoice = {+ index: 0,+ message: toolCallWinner.rawChoice!.message,+ finish_reason: 'tool_calls',+ };+ const response: ChatCompletionResponse & { x_fusion?: unknown; _fusion?: unknown } = {+ id: `fusion-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,+ object: 'chat.completion',+ created: Math.floor(Date.now() / 1000),+ model: FUSION_MODEL_ID,+ choices: [choice],+ usage: totalUsage,+ };+ const winner = { platform: toolCallWinner.platform, model: toolCallWinner.modelId };+ response._fusion = {+ panel: survivors.map(a => ({ platform: a.platform, model: a.modelId })),+ judge: null,+ synthesized: false,+ tool_call_winner: winner,+ };++ if (config.expose_panel) {+ response.x_fusion = {+ strategy,+ synthesized: false,+ judge: null,+ panel_requested: panel.map(p => p.modelId),+ dropped,+ tool_call_winner: winner,+ panel: answers.map(a => ({+ model: a.modelId,+ platform: a.platform,+ status: a.status,+ ...(a.status === 'ok'+ ? { content: a.content, tool_calls: a.toolCalls }+ : { error: a.error }),+ })),+ };+ }++ return {+ response,+ routedVia: `fusion(${survivors.map(a => a.modelId).join('+')} -> tool_call:${toolCallWinner.modelId})`,+ };+ }++ const textSurvivors = survivors.filter(a => a.content);+// Decide the final answer.let finalText: string;let judgeModelLabel: string | null = null;let judgeRoute: { platform: string; model: string } | null = null;let synthesized = false;- if (survivors.length < SYNTHESIS_QUORUM || strategy === 'best_of') {+ if (textSurvivors.length < SYNTHESIS_QUORUM || strategy === 'best_of') {// One survivor, or best-of requested: return the strongest single answer// (longest as a cheap proxy for completeness) — no judge call.- finalText = survivors.slice().sort((a, b) => (b.content!.length - a.content!.length))[0].content!;+ finalText = textSurvivors.slice().sort((a, b) => (b.content!.length - a.content!.length))[0].content!;} else {- const judgeMessages = buildJudgeMessages(messages, survivors);+ const judgeMessages = buildJudgeMessages(messages, textSurvivors);// The judge prompt carries every panel answer, so its input is much larger// than the original — size the routing estimate accordingly.- const judgeEstimate = estimatedTokens + survivors.reduce((n, a) => n + Math.ceil((a.content?.length ?? 0) / 4), 0);+ const judgeEstimate = estimatedTokens + textSurvivors.reduce((n, a) => n + Math.ceil((a.content?.length ?? 0) / 4), 0);+ const judgeOptions: CompletionOptions = requireTools+ ? { ...options, tools: undefined, tool_choice: undefined, parallel_tool_calls: undefined }+ : options;const getJudgeRoute = config.judge? (skipKeys: Set<string>) => {@@ -601,13 +683,13 @@ export async function runFusion(params: {// Stream the judge when the caller wants live tokens (Playground); otherwise// a single buffered call (plain API clients hitting fusion non-streaming).const judge = hooks?.onJudgeDelta- ? await runJudgeStreaming(getJudgeRoute, judgeMessages, options, judgeEstimate, MAX_JUDGE_ATTEMPTS, {+ ? await runJudgeStreaming(getJudgeRoute, judgeMessages, judgeOptions, judgeEstimate, MAX_JUDGE_ATTEMPTS, {// Surface the judge model the moment it starts emitting, so the trace// shows it while the answer is still streaming.onStart: (r) => { judgeRoute = r; judgeModelLabel = `${r.platform}/${r.model}`; hooks.onJudge?.(r); },onDelta: hooks.onJudgeDelta,})- : await runModelCall(getJudgeRoute, judgeMessages, options, judgeEstimate, MAX_JUDGE_ATTEMPTS);+ : await runModelCall(getJudgeRoute, judgeMessages, judgeOptions, judgeEstimate, MAX_JUDGE_ATTEMPTS);if (judge.ok && judge.text) {finalText = judge.text;@@ -620,11 +702,11 @@ export async function runFusion(params: {totalUsage = addUsage(totalUsage, judge.usage);} else {// Judge failed → best-of fallback rather than erroring the whole request.- finalText = survivors.slice().sort((a, b) => (b.content!.length - a.content!.length))[0].content!;+ finalText = textSurvivors.slice().sort((a, b) => (b.content!.length - a.content!.length))[0].content!;}}- const routedModels = survivors.map(a => a.modelId);+ const routedModels = textSurvivors.map(a => a.modelId);const routedVia = `fusion(${routedModels.join('+')}${synthesized && judgeModelLabel ? ` -> ${judgeModelLabel}` : ''})`;const response: ChatCompletionResponse & { x_fusion?: unknown; _fusion?: unknown } = {