consensus() runs N independent completions in parallel with the same prompt at higher temperature, normalizes whitespace, and votes on the result. The winning response is returned with an agreement_ratio score so the caller can gate on confidence.
importasyncioimportosfromexecutionkitimportProvider,consensusasyncdefmain()->None:asyncwithProvider(base_url=os.environ["LLM_BASE_URL"],api_key=os.environ.get("LLM_API_KEY",""),model=os.environ["LLM_MODEL"],)asprovider:result=awaitconsensus(provider,"Classify this support ticket as exactly one of ""'billing', 'tech', or 'other':\n\n""'My card was charged twice this month.'",num_samples=5,strategy="majority",# or "unanimous")print(result.value)# 'billing'print(result.metadata["agreement_ratio"])# e.g. 0.8 = 4 of 5print(result.metadata["unique_responses"])# 2print(result.metadata["tie_count"])# 1 = no tieprint(result.cost.llm_calls)# 5asyncio.run(main())
O(num_samples) LLM calls. All calls are issued concurrently up to max_concurrency.
Concurrent. Calls run concurrently up to max_concurrency; provider
queuing and rate limits still affect elapsed time.
Call-budget enforcement is safe within one asyncio event loop.checked_complete reserves the call slot before awaiting, so concurrent
samples cannot claim the same slot. Retries count as new attempts.
Token budgets are pre-dispatch checks. A completed response can take the
recorded total past a token limit; the next call is then blocked.
Whitespace is normalized for voting (re.sub(r"\s+", " ", text.strip())). Two responses differing only in trailing newlines count as identical. The original (un-normalized) winning string is returned.
Choose temperature for the endpoint and task. More variation can expose
disagreement, but it can also reduce the chance of a clear winner.
Constrain the answer space in the prompt ("answer with exactly one of: …"). Free-form responses rarely vote cleanly.
Gate on agreement_ratio before trusting the answer:
ifresult.metadata["agreement_ratio"]<0.6:# Fall back to a stronger model or human review...