Multi LLM API in Python: One Prompt, Five Models, One Consensus Answer
Building a multi LLM API Python integration yourself sounds simple until you list the work: an SDK and key for each provider, retries and timeouts for each, parallel calls, and then the hard part, deciding what to do when the models disagree. For an engineering team shipping an AI feature, that comparison logic is exactly where hallucinations slip through. This tutorial shows a shorter path. Using the official talkory Python package, one call sends a prompt to GPT, Claude, Gemini, Perplexity and Grok in parallel and returns a single consensus answer, the points all models agreed on, a confidence score and the cost. Every code sample below matches the published SDK documentation.
DIY Multi-Provider Code vs a Consensus API
What you build yourself versus what one API call returns.
| Task | Calling each provider yourself | Talkory Python SDK |
|---|---|---|
| SDKs and keys | One per provider | One package, one key |
| Parallel calls | Your own concurrency code | Handled per query |
| Comparing answers | Your own logic | result.consensus and result.common_answer |
| Confidence signal | Build your own | result.confidence (0 to 100) |
| Cost tracking | Per-provider bills | result.charged in USD per query |
| Billing | Several provider accounts | One prepaid wallet |
Step 1: Install and Authenticate
The SDK targets Python 3.9 or newer and is fully typed. Create an API key in the Talkory app under Settings, API Keys, with the query:write scope, then install the package:
pip install talkory
export TALKORY_API_KEY="tk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
Keep the key on the server side only. The SDK redacts keys from logs, exceptions and repr() output.
Step 2: Your First Multi LLM API Python Call
from talkory import Talkory
client = Talkory() # reads TALKORY_API_KEY from the environment
result = client.queries.run("What are the main causes of LLM hallucinations in RAG systems?")
print(result.consensus) # one combined answer from all models
print(result.common_answer) # only the points every model agreed on
print(result.confidence) # 0-100
print(result.charged) # cost of this query in USD
That single call sends the prompt to the five default models in parallel and waits for the consensus. In production, the most useful field is often common_answer: anything missing from it is a point where the models disagreed.
Get Your API Key
Read the full Python SDK and REST API reference before you build.
Read the API DocsStep 3: Choose Models and Options
queries.run() accepts the same options as the REST endpoint as keyword arguments:
result = client.queries.run(
"Summarise the key obligations in this contract clause: ...",
models=["gpt", "claude", "gemini"], # up to 10 model ids; omit for the default 5
recursive=True, # each model reviews its own answer first
)
print(result.consensus, result.confidence)
models: pick specific model ids. Opt-in models such as Kimi K3 run only when named.recursive: adds a self-review round before the consensus.country: localises answers with a country code.consensus=False: runs the models now and computes the consensus later.
result = client.queries.run("Best NAS for home use?", consensus=False)
consensus = client.queries.consensus(result.id) # idempotent: a second call charges 0
print(consensus.consensus, consensus.confidence)
Step 4: Stream Answers as Each Model Responds
For user-facing features, stream events instead of waiting for the full result:
for event in client.queries.stream("Compare Python web frameworks for a new API"):
if event.type == "model_chunk":
print(event.chunk, end="", flush=True)
elif event.type == "model_result":
print(f"\n{event.model_id} scored {event.score}")
elif event.type == "done":
print("\n\nConsensus:", event.consensus)
Async version for multi LLM API Python services
import asyncio
from talkory import AsyncTalkory
async def main():
async with AsyncTalkory() as client:
result = await client.queries.run("Is this SQL query safe from injection? ...")
print(result.consensus)
asyncio.run(main())
Prefer Plain HTTP or Node.js?
The SDK wraps a REST API, so you can call it from any language. The blocking endpoint is POST /v1/query/sync; a full run can take a few minutes, so set a generous timeout:
import os, requests
res = requests.post(
"https://api.talkory.ai/v1/query/sync",
headers={"Authorization": f"Bearer {os.environ['TALKORY_API_KEY']}"},
json={"prompt": "Best commuter motorcycles under $5000?"},
timeout=600, # the run can take a few minutes
)
data = res.json()
print(data["consensus"], data["confidence"], data["charged"])
For JavaScript and TypeScript services, the npm package mirrors the Python API:
import { Talkory } from "talkory";
const client = new Talkory(); // reads TALKORY_API_KEY
const result = await client.queries.run("Best commuter motorcycles under $5000?");
console.log(result.consensus, result.commonAnswer, result.confidence);
See the Python SDK reference, the npm package reference and the REST API reference for every parameter and response field.
Step 5: Production Patterns
- Route by confidence. Show high-confidence consensus answers directly; send low-confidence ones to a human or a fallback flow.
- Log the common answer. Store
common_answerwith each response so you can audit what all models agreed on. - Track cost per feature. Sum
result.chargedby feature to see where spend goes. - Respect rate limits. Queue requests and back off on
RateLimitError. - Never retry paid calls blindly. The SDK does not auto-retry paid requests; keep it that way in your own code.
from talkory import Talkory, RateLimitError, InsufficientBalanceError, TalkoryError
client = Talkory()
try:
result = client.queries.run("Best commuter motorcycles under $5000?")
except RateLimitError as e:
print("slow down:", e.request_id)
except InsufficientBalanceError as e:
print("top up your wallet:", e.message)
except TalkoryError as e:
print(e.code, e.status, e.message, e.request_id)
Try the Consensus Engine in the App First
See what five models return for your prompts before you write code. 3 free query runs.
Try Talkory FreeSecurity notes for production
Treat the API key like any other production secret. Store it in your secrets manager, never in source control or client-side code, and give each service its own key with only the scopes it needs, such as query:write for running queries. Rotate keys when people leave or a key may have leaked. Remember that prompts are sent to several model providers, so apply the same data rules you use for any external AI service: do not send personal or confidential data unless your contract and policy allow it. Enterprise plans add data residency controls and dedicated infrastructure for teams with stricter requirements.
Step 6: Test Your Integration Before Launch
A multi-model call behaves differently from a single-provider call, so test it on its own terms. Build a small evaluation set before you ship:
- Collect 30 to 50 real prompts from your feature, including awkward edge cases.
- Write the expected answer for each, or at least the facts it must contain.
- Run them through the API and store
consensus,common_answer,confidenceandcharged. - Check where confidence was low and whether those were the prompts with wrong or disputed answers.
- Set your routing threshold from that data rather than guessing, and re-run the set whenever you change prompts.
This gives you a cost per query for your real workload, a sensible confidence threshold, and a regression test you can run before every release. Keep the evaluation set in your repository next to the code, so every engineer can run it and see how a prompt change affects agreement between models.
Real Use Cases
These scenarios are illustrative, showing how teams use a consensus API in practice rather than presented as verified case studies.
The support assistant. A SaaS team answers policy questions from the consensus and sends anything below a confidence threshold to a human agent.
The research pipeline. A data team runs nightly questions through the API and stores the common answer as the trusted fact set.
The code reviewer. An internal tool asks several models whether a change introduces a security issue and flags pull requests where they disagree.
Where Talkory Fits for Developers
Talkory replaces the plumbing of a multi-provider integration with one typed SDK, and it adds the part most teams never get round to building: a principled way to combine and compare answers. You get one package, one key, one wallet, parallel calls to five providers, and structured fields for the consensus, the agreed points, confidence and cost. There is also an npm package for Node.js, and the REST API for any other language. Enterprise plans add higher rate limits, dedicated infrastructure and an SLA.
Final Verdict
If your feature depends on LLM answers being right, a single provider call is the riskiest design. A multi LLM API Python integration that compares several models gives you a built-in check, and with the talkory package it takes one call instead of a week of plumbing. Start with client.queries.run(), route by confidence, log the common answer, and you will ship with far fewer surprises.
Ship LLM Features With a Built-In Check
One prompt, five providers, one consensus answer. Start free.
Try Talkory FreeTrademarks and accuracy: product and company names mentioned in this article are trademarks of their respective owners. Talkory.ai is not affiliated with, sponsored by or endorsed by any of them. Product details reflect the information available when this article was last updated and may have changed since. If you spot an error, email [email protected] and we will correct it promptly.
Frequently Asked Questions
Which models does the Talkory API call?
By default, every query runs on five models: GPT, Claude, Gemini, Perplexity and Grok. Kimi K3 is available as an opt-in model. You can pass up to 10 model ids per query with the models parameter.
How is the multi LLM API in Python priced?
API access is included on the Paid plan. Each query is charged from your prepaid wallet, and result.charged tells you the cost in US dollars. The SDK never auto-retries paid requests, so a network blip cannot double-charge you.
What does result.confidence mean?
It is a 0 to 100 score returned with the consensus. Use it as a signal for routing: for example, send low-confidence answers to human review rather than straight to users.
Can I use the API asynchronously?
Yes. Use AsyncTalkory as an async context manager inside asyncio applications, and await client.queries.run(). Streaming is available with client.queries.stream().
What are the rate limits?
The API documentation lists 10 query runs per minute and at most 2 queries in flight per key at the time of writing. Check the API docs for current limits and handle RateLimitError in your code.
Get 5 AI perspectives on this topic
Talkory runs your question through GPT, Claude, Gemini, Grok, Sonar & Kimi K3 simultaneously, then cross-checks the answers.