LLM Consensus API: Get One Verified Answer From Multiple Models (Python Example)

A multi LLM API Python example: send one prompt to GPT, Claude, Gemini, Perplexity and Grok with the talkory package and get one consensus answer back.

Multi LLM API in Python: One Prompt, Five Models, One Consensus Answer

Quick Answer: Install the talkory package with pip, set TALKORY_API_KEY, and call client.queries.run(prompt). One call sends the prompt to GPT, Claude, Gemini, Perplexity and Grok and returns result.consensus, result.common_answer, result.confidence and result.charged. Streaming, async and model selection are built in.

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.

TaskCalling each provider yourselfTalkory Python SDK
SDKs and keysOne per providerOne package, one key
Parallel callsYour own concurrency codeHandled per query
Comparing answersYour own logicresult.consensus and result.common_answer
Confidence signalBuild your ownresult.confidence (0 to 100)
Cost trackingPer-provider billsresult.charged in USD per query
BillingSeveral provider accountsOne 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 Docs

Step 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

  1. Route by confidence. Show high-confidence consensus answers directly; send low-confidence ones to a human or a fallback flow.
  2. Log the common answer. Store common_answer with each response so you can audit what all models agreed on.
  3. Track cost per feature. Sum result.charged by feature to see where spend goes.
  4. Respect rate limits. Queue requests and back off on RateLimitError.
  5. 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 Free

Security 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:

  1. Collect 30 to 50 real prompts from your feature, including awkward edge cases.
  2. Write the expected answer for each, or at least the facts it must contain.
  3. Run them through the API and store consensus, common_answer, confidence and charged.
  4. Check where confidence was low and whether those were the prompts with wrong or disputed answers.
  5. 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 Free

Trademarks 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.

MB

Mital Bhayani, AI Researcher & SaaS Growth Specialist

Mital writes about AI adoption, model evaluation, and how teams turn AI output into decisions they can defend. Reviewed by Chetan Kajavadra, Lead AI Researcher, Talkory.ai. Connect on LinkedIn →

๐Ÿค–

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.

Try Talkory.ai free โ†’
โ† Back to all articles

Related Articles

๐Ÿ“ฐAI and Media

Can AI Spot Fake News? How 5 AI Models Compare

How ChatGPT, Claude, Gemini, Grok and Perplexity handle real and fake headlines, where they slip, and why cross-checking models helps you spot fake news.

Read article โ†’
โœˆ๏ธAI Travel

Best AI for Travel Planning: How 5 AI Models Compare

How ChatGPT, Claude, Gemini, Grok and Perplexity handle the same trip-planning prompt, where AI travel advice goes stale, and what to check before you book.

Read article โ†’
๐Ÿ’ฐAI for Finance

How 5 AI Models Approach a $10K Portfolio Question

How ChatGPT, Claude, Gemini, Grok and Perplexity respond to the same $10,000 portfolio question, where their suggestions differ, and why this is not advice.

Read article โ†’
๐Ÿ”’AI Security

The Hidden Security Risk of Trusting AI With Big Decisions

63 percent of cybersecurity professionals now rank AI driven social engineering as their top expected attack vector. The Colorado AI Act takes effect June 30, 2026. The hidden risk is not a bad answer, it is the audit trail nobody can produce afterward.

Read article โ†’
๐Ÿค–

Stop guessing. Get verified AI answers.

Talkory.ai queries GPT, Claude, Gemini, Grok, Sonar and Kimi K3 simultaneously, cross-verifies their answers, and gives you a confidence-scored consensus. Free to start.

โœ“ Free plan includedโœ“ No credit cardโœ“ Results in seconds