Skip to content

Multi-LLM patterns

Six patterns for building experiences where several LLMs work together. Each one is a few lines of TypeScript on top of the Gambi SDK. Gambi handles routing, room events, and participants on several machines. Your code decides who speaks and when.

All snippets below assume:

import { createGambi } from "gambi-sdk";
import { generateText } from "ai";
const gambi = createGambi({
roomCode: "ABC123",
hubUrl: "http://localhost:3000",
});

Same prompt, every model in the room. Use it for evals, A/B comparisons, or picking a model for a task.

const prompt = "Explain TLS handshakes in one sentence.";
// Model participants that can take a request now
const participants = (await gambi.listParticipants()).filter(
(p) => !p.harness && p.status === "online"
);
const results = await Promise.all(
participants.map((p) =>
generateText({ model: gambi.participant(p.id), prompt })
)
);
results.forEach((r, i) => console.log(`${participants[i].model}: ${r.text}`));

Each call targets a different participant, so they run in parallel. A participant can still pick up someone else’s request between the list and your call; that call fails with HTTP 409. Don’t build an arena from repeated gambi.any() calls. any() picks a random available participant, not the next one in turn, and a participant handling a request is not available. When more any() calls run at once than there are free participants, the extra calls fail with HTTP 404.

Generate the answer once. Send it to N other models with a judging prompt. Count the verdicts. This is the LLM-as-judge pattern (as in G-Eval).

const question = "Is this code thread-safe? <code>...</code>";
const answer = await generateText({
model: gambi.model("llama3"),
prompt: question,
});
const judgePrompt = `
Question: ${question}
Answer: ${answer.text}
Reply with YES or NO and one sentence why.
`;
const judges = ["gpt-4o-mini", "claude-haiku-4-5", "mistral"];
const verdicts = await Promise.all(
judges.map((model) =>
generateText({ model: gambi.model(model), prompt: judgePrompt }),
),
);
const yesVotes = verdicts.filter((v) => v.text.startsWith("YES")).length;
console.log(`Verdict: ${yesVotes}/${judges.length} say yes`);

Mix providers as you like. The answer can come from a local Ollama and the judges from cloud APIs, all in the same room.

A small, fast model drafts, a bigger one critiques, a third polishes. On long-form content this costs less than running the strongest model for every step.

const topic = "How to write a good incident report.";
const draft = await generateText({
model: gambi.model("llama3"),
prompt: `Draft a 200-word essay: ${topic}`,
});
const critique = await generateText({
model: gambi.model("gpt-4o"),
prompt: `Critique this draft. List 3 specific improvements:\n\n${draft.text}`,
});
const polished = await generateText({
model: gambi.model("claude-haiku-4-5"),
prompt: `Apply these improvements to the draft.
DRAFT:
${draft.text}
FEEDBACK:
${critique.text}
Return only the revised essay.`,
});
console.log(polished.text);

The same shape works for code review, translation, or any loop of draft, feedback, and clean copy.

Two models argue, a third moderates. Alternate turns between participants with opposing system prompts, then ask the moderator for a verdict. Room events let an audience follow each turn.

const topic = "Is it OK to lie for a good cause?";
const turns = 4;
const transcript: Array<{ speaker: string; text: string }> = [];
const personas = {
pro: { id: "pro", system: "You argue strongly FOR the proposition." },
con: { id: "con", system: "You argue strongly AGAINST the proposition." },
};
for (let i = 0; i < turns; i++) {
const persona = i % 2 === 0 ? personas.pro : personas.con;
const prior = transcript.map((t) => `${t.speaker}: ${t.text}`).join("\n");
const turn = await generateText({
model: gambi.participant(persona.id),
system: persona.system,
prompt: `TOPIC: ${topic}\nDEBATE SO FAR:\n${prior}\n\nYour turn (3 sentences max).`,
});
transcript.push({ speaker: persona.id, text: turn.text });
}
const verdict = await generateText({
model: gambi.participant("moderator"),
prompt: `As moderator, summarize who made the stronger case:\n${transcript
.map((t) => `${t.speaker}: ${t.text}`)
.join("\n")}`,
});

Watch the room’s SSE stream (gambi events watch --room ABC123 --format ndjson) to see each turn’s llm.request and llm.complete as it happens.

A game where each character has its own model. Register one participant per persona, each on the provider that fits: a small, fast model for the guard, a larger one for the oracle.

const SYSTEM_PROMPTS = {
merchant: "You are a greedy merchant. Always try to upsell.",
guard: "You are a tired city guard. You speak in 5 words or fewer.",
oracle: "You are an ancient oracle. Speak in cryptic verse.",
};
const npcs = {
merchant: gambi.participant("merchant"),
guard: gambi.participant("guard"),
oracle: gambi.participant("oracle"),
};
async function npcSays(npc: keyof typeof npcs, playerInput: string) {
const result = await generateText({
model: npcs[npc],
system: SYSTEM_PROMPTS[npc],
prompt: playerInput,
});
return result.text;
}
console.log(await npcSays("merchant", "Got any potions?"));
console.log(await npcSays("guard", "Let me through."));
console.log(await npcSays("oracle", "Will I survive?"));

Your game logic owns turn-taking and state. Gambi makes “this character speaks now” one call.

Pool the models of everyone in a room, such as friends or students. Each person joins with their own provider (Ollama, OpenRouter, OpenAI). You build the UI; the models stay on their machines.

Set up the hub and create a room:

Terminal window
gambi hub serve --mdns
gambi room create --name "Class arena"
# Created room ABC123 (Class arena).

Each participant joins separately, with whatever provider they brought:

Terminal window
# alice
gambi participant join --room ABC123 --participant-id alice --model llama3
# bob
gambi participant join --room ABC123 --participant-id bob --model mistral \
--endpoint http://localhost:1234
# carol (using OpenRouter)
gambi participant join --room ABC123 --participant-id carol \
--endpoint https://openrouter.ai/api \
--model meta-llama/llama-3.1-8b-instruct:free \
--header-env Authorization=OPENROUTER_AUTH

Then the app fans out the same prompt and renders responses side-by-side, votes, or runs blind comparisons:

// createClient handles management operations (listing participants, rooms).
// createGambi (from the setup above) handles inference. This example needs both.
import { createClient } from "gambi-sdk";
const client = createClient({ hubUrl: "http://localhost:3000" });
const all = await client.participants.list("ABC123");
// The list includes harness, busy, and offline participants.
// Keep model participants that can take a request now.
const participants = all.filter((p) => !p.harness && p.status === "online");
const responses = await Promise.all(
participants.map((p) =>
generateText({
model: gambi.participant(p.id),
prompt: "Explain monads in one sentence.",
}),
),
);

The room is shared; every model stays on the machine that brought it.