Cookbook
Working code for common tasks. Each recipe shows how features work together and where people usually get them wrong. Every feature has its own page with the details, linked at the start of the recipe.
The examples are in Python and read the key from the environment:
export WAIBEE_API_KEY="sk_live_..."pip install openai httpxTool calling loop
Section titled “Tool calling loop”The model asks for a call, you run the function, return the result, and repeat. The detail that matters is the step limit: without it, a confused model goes around in circles at your expense. See Tool calling.
import jsonimport os
from openai import OpenAI
client = OpenAI(base_url="https://api.waibee.com/v1", api_key=os.environ["WAIBEE_API_KEY"])
TOOLS = [ { "type": "function", "function": { "name": "get_order", "description": "Order status by order number", "parameters": { "type": "object", "properties": {"order_id": {"type": "string"}}, "required": ["order_id"], }, }, }]
def get_order(order_id: str) -> dict: if not isinstance(order_id, str) or not order_id.strip(): raise ValueError("order_id must be a non-empty string") return {"order_id": order_id, "status": "shipped", "eta_days": 2}
HANDLERS = {"get_order": get_order}MAX_STEPS = 5
def call_tool(name: str, raw_arguments: str) -> str: handler = HANDLERS.get(name) if handler is None: return json.dumps({"error": f"tool {name} does not exist"}, ensure_ascii=False) try: arguments = json.loads(raw_arguments) if not isinstance(arguments, dict): raise ValueError("arguments must be a JSON object") result = handler(**arguments) except (ValueError, TypeError) as error: return json.dumps({"error": f"invalid arguments: {error}"}, ensure_ascii=False) return json.dumps(result, ensure_ascii=False)
def answer(question: str) -> str: messages = [{"role": "user", "content": question}] for _ in range(MAX_STEPS): choice = client.chat.completions.create( model="waibee/auto", messages=messages, tools=TOOLS ).choices[0] if choice.finish_reason != "tool_calls": return choice.message.content messages.append(choice.message) messages += [ { "role": "tool", "tool_call_id": call.id, "content": call_tool(call.function.name, call.function.arguments), } for call in choice.message.tool_calls ] raise RuntimeError(f"tools are being called in a loop, {MAX_STEPS} steps used up")
print(answer("What is the status of order A-1042? Answer in one sentence."))Order A-1042 has been shipped and is expected to arrive in 2 days.The model’s message goes into the history as is, and each call gets its own role: "tool" message with the matching tool_call_id.
The model passes arguments as a string, so the example checks both the JSON syntax and the function arguments. An array, null, a missing order_id, or an extra field raises an error. The handler returns it to the model as a role: "tool" message, so the model can fix the call on the next step. The loop itself keeps going.
Repeat questions about one document
Section titled “Repeat questions about one document”When a large, unchanging context repeats in every request, mark it for caching: the first request pays for the write, and the rest read it at a lower price. See Prompt caching.
import osimport pathlib
from openai import OpenAI
client = OpenAI(base_url="https://api.waibee.com/v1", api_key=os.environ["WAIBEE_API_KEY"])
POLICY = pathlib.Path("policy.txt").read_text(encoding="utf-8")
def ask(question: str) -> tuple[str, int]: response = client.chat.completions.create( model="anthropic/claude-haiku-4.5", messages=[ { "role": "user", "content": [ # The cached block goes first, the changing question after it. {"type": "text", "text": POLICY, "cache_control": {"type": "ephemeral"}}, {"type": "text", "text": f"{question} Answer in one line."}, ], } ], ) # prompt_tokens_details is missing when the provider sent no breakdown. details = response.usage.prompt_tokens_details cached = getattr(details, "cached_tokens", 0) or 0 return response.choices[0].message.content, cached
for question in ["What is the return period?", "Who pays for return shipping?"]: answer, cached = ask(question) print(f"cached {cached:>6} tokens | {answer.splitlines()[0][:50]}")cached 0 tokens | The return period is 14 days from the date the cuscached 23760 tokens | # Return Shipping CostThe first request writes the cache, and the second reads the whole document from it. The 50-character cut in print is only there for the example.
Extracting data with a schema
Section titled “Extracting data with a schema”A schema sets the shape of the response, but it says nothing about whether the content is plausible: the model fills in a required field even where the text has no data for it. So describe “unknown” in the schema explicitly, and check the meaning in your own code. See Structured outputs.
import jsonimport os
from openai import OpenAI
client = OpenAI(base_url="https://api.waibee.com/v1", api_key=os.environ["WAIBEE_API_KEY"])
INVOICE_SCHEMA = { "type": "object", "properties": { "company": {"type": "string"}, "amount": {"type": "number"}, "currency": {"type": "string", "enum": ["RUB", "USD", "EUR"]}, # An explicit null: otherwise the model invents a date the text does not have. "due_date": {"type": ["string", "null"], "description": "ISO 8601 or null"}, }, "required": ["company", "amount", "currency", "due_date"], "additionalProperties": False,}
def extract_invoice(text: str) -> dict: choice = client.chat.completions.create( model="openai/gpt-5.4-mini", messages=[{"role": "user", "content": text}], response_format={ "type": "json_schema", "json_schema": {"name": "invoice", "strict": True, "schema": INVOICE_SCHEMA}, }, ).choices[0] if choice.finish_reason == "length": raise ValueError("response cut off by the token limit, JSON is incomplete") invoice = json.loads(choice.message.content) if invoice["amount"] <= 0: # the schema checks the shape, not plausibility raise ValueError(f"implausible amount: {invoice['amount']}") return invoice
print(extract_invoice("Invoice from Romashka LLC for 154,200 rubles, due by August 15, 2026."))print(extract_invoice("Invoice from Acme Inc, 1200 EUR, no due date specified.")){'company': 'Romashka LLC', 'amount': 154200, 'currency': 'RUB', 'due_date': '2026-08-15'}{'company': 'Acme Inc', 'amount': 1200, 'currency': 'EUR', 'due_date': None}Image to structured data
Section titled “Image to structured data”A screenshot, a photo of a receipt, a picture of a table: the model reads the image, and the schema brings the response into the shape you need.
import base64import jsonimport osimport pathlib
from openai import OpenAI
client = OpenAI(base_url="https://api.waibee.com/v1", api_key=os.environ["WAIBEE_API_KEY"])
RECEIPT_SCHEMA = { "type": "object", "properties": { "merchant": {"type": "string"}, "total": {"type": "number"}, "currency": {"type": "string"}, "items": { "type": "array", "items": { "type": "object", "properties": {"name": {"type": "string"}, "price": {"type": "number"}}, "required": ["name", "price"], "additionalProperties": False, }, }, }, "required": ["merchant", "total", "currency", "items"], "additionalProperties": False,}
def read_receipt(path: pathlib.Path) -> dict: image = base64.b64encode(path.read_bytes()).decode() choice = client.chat.completions.create( model="google/gemini-3.6-flash", messages=[ { "role": "user", "content": [ {"type": "text", "text": "Extract the receipt data according to the schema."}, {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{image}"}}, ], } ], response_format={ "type": "json_schema", "json_schema": {"name": "receipt", "strict": True, "schema": RECEIPT_SCHEMA}, }, ).choices[0] receipt = json.loads(choice.message.content) # The model reads the image rather than adding up, so the items may not match the total. if abs(sum(item["price"] for item in receipt["items"]) - receipt["total"]) > 0.01: raise ValueError(f"item prices do not add up to the total {receipt['total']}") return receipt
print(read_receipt(pathlib.Path("receipt.png"))){'merchant': 'COFFEE HOUSE', 'total': 10.5, 'currency': 'EUR', 'items': [{'name': 'Espresso', 'price': 2.8}, {'name': 'Croissant', 'price': 3.2}, {'name': 'Orange juice', 'price': 4.5}]}Comparing the sum of the items with the total is a cheap check that a schema cannot do: it catches both a skipped line and a misread digit. You need a model that accepts images as input: image in capabilities.modality_input in the catalog. See Images and PDFs.
Extracting data from PDFs
Section titled “Extracting data from PDFs”The document goes straight into the message; there is no separate file upload. Each document is its own request, so a failure on one file does not stop the rest. See Images and PDFs.
import base64import osimport pathlib
from openai import OpenAI, OpenAIError
client = OpenAI(base_url="https://api.waibee.com/v1", api_key=os.environ["WAIBEE_API_KEY"])
def read_invoice(path: pathlib.Path) -> str: document = base64.b64encode(path.read_bytes()).decode() response = client.chat.completions.create( model="anthropic/claude-haiku-4.5", messages=[ { "role": "user", "content": [ { "type": "file", "file": { "filename": path.name, "file_data": f"data:application/pdf;base64,{document}", }, }, {"type": "text", "text": "Return the document's amount and currency, with no explanation."}, ], } ], ) return response.choices[0].message.content.strip()
for path in sorted(pathlib.Path("invoices").glob("*.pdf")): try: print(f"{path.name}: {read_invoice(path)}") except OpenAIError as error: # one failed document must not stop the processing print(f"{path.name}: skipped, {error}")a.pdf: 154200 RUBb.pdf: 1200 EURA task that needs maximum reasoning
Section titled “A task that needs maximum reasoning”This recipe passes max through output_config.effort on /v1/messages, so it needs the Anthropic SDK (pip install anthropic). Use it where a mistake costs more than waiting: untangling convoluted logic, deriving a formula, reviewing a tricky invariant. See Reasoning.
import os
import anthropic
# Base URL without /v1: the SDK adds the path itself.client = anthropic.Anthropic( base_url="https://api.waibee.com", api_key=os.environ["WAIBEE_API_KEY"], timeout=600.0,)
TASK = ( "A basket holds 12 balls: 5 red, 4 blue, 3 white. Three are drawn in a row without " "replacement. What is the probability that all three are different colors? Answer in one " "line: the fraction in lowest terms and its decimal value.")
response = client.messages.create( model="anthropic/claude-sonnet-5", max_tokens=8192, # The SDK passes the field through as is. extra_body={"output_config": {"effort": "max"}}, messages=[{"role": "user", "content": TASK}],)
answer = "".join(block.text for block in response.content if block.type == "text")print(answer.strip())print(f"[{response.usage.output_tokens} output tokens, including reasoning]")**P(all three different colors) = 3/11 ≈ 0.2727** (since C(5,1)·C(4,1)·C(3,1)/C(12,3) = 60/220 = 3/11)[303 output tokens, including reasoning]At max, the model is silent while it thinks, so do not set a low client timeout: a short read timeout cuts off a live request. thinking blocks come in content before the text, so the answer is assembled only from blocks of type text.
Streaming a response to the user
Section titled “Streaming a response to the user”The text prints as it is generated, and the token counters arrive in the last chunk, which has no content. See Streaming.
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.waibee.com/v1", api_key=os.environ["WAIBEE_API_KEY"])
stream = client.chat.completions.create( model="anthropic/claude-haiku-4.5", messages=[{"role": "user", "content": "Three ways to cache HTTP responses, one line each."}], stream=True,)
usage = Nonefor chunk in stream: if chunk.usage: # last chunk: counters only, no text usage = chunk.usage for choice in chunk.choices: if choice.delta.content: print(choice.delta.content, end="", flush=True)print()
if usage: print(f"[tokens: input {usage.prompt_tokens}, output {usage.completion_tokens}]")You do not need to pass stream_options to get the counters: the router adds them to the stream on its own.
Many requests in parallel
Section titled “Many requests in parallel”You set the limit on concurrent requests: without one, the client runs into the limits and gets 429 or 503 instead of a result. See Limits.
import asyncioimport os
from openai import AsyncOpenAI
client = AsyncOpenAI(base_url="https://api.waibee.com/v1", api_key=os.environ["WAIBEE_API_KEY"])
MAX_CONCURRENCY = 4
async def summarize(text: str, limiter: asyncio.Semaphore) -> str: async with limiter: response = await client.chat.completions.create( model="anthropic/claude-haiku-4.5", messages=[{"role": "user", "content": f"In one sentence, what is this about: {text}"}], ) return response.choices[0].message.content
async def summarize_all(texts: list[str]) -> list[str | BaseException]: limiter = asyncio.Semaphore(MAX_CONCURRENCY) # return_exceptions: one failed request must not wipe out the whole batch of results. return await asyncio.gather( *(summarize(text, limiter) for text in texts), return_exceptions=True )
TICKETS = [ "Customer cannot log in: the password was reset, but the email never arrives.", "Payment went through twice, one transaction needs a refund.", "The app crashes when opening the profile on Android 13.",]
for ticket, result in zip(TICKETS, asyncio.run(summarize_all(TICKETS))): if isinstance(result, BaseException): print(f"! {ticket[:30]}: {result}") else: print(f"- {result}")For long queues, add the retries from the Timeouts and retries in a service recipe.
Fallback model on failure
Section titled “Fallback model on failure”A request has no routing fields, so the fallback chain lives on the client side. Tell the cases apart: when a model is unavailable, moving to the next one helps, but an error in the request itself repeats on any model. See Errors.
import os
from openai import APIStatusError, OpenAI
client = OpenAI(base_url="https://api.waibee.com/v1", api_key=os.environ["WAIBEE_API_KEY"])
# Order matters: the preferred model first, then the fallbacks.MODELS = ["anthropic/claude-sonnet-4.6", "openai/gpt-5.4-mini", "google/gemini-3.6-flash"]FALLBACK_STATUSES = frozenset({404, 429, 502, 503})
def complete(messages: list[dict], models: list[str] = MODELS): for model in models: try: return client.chat.completions.create(model=model, messages=messages) except APIStatusError as error: if error.status_code not in FALLBACK_STATUSES or ( error.status_code == 429 and error.response.json().get("error", {}).get("code") != "provider_rate_limited" ): raise # an error in the request itself: another model will not help raise RuntimeError(f"no model responded: {', '.join(models)}")
response = complete([{"role": "user", "content": "Answer in one word: fallback"}])print(f"{response.model}: {response.choices[0].message.content}")On 429, the recipe switches models only for provider_rate_limited. On api_key_limit_exceeded, check the key’s spending limit and when it resets.
The alternative to a chain of your own is waibee/auto: the router picks a model that suits the request. See Autorouting.
Timeouts and retries in a service
Section titled “Timeouts and retries in a service”What sets production code apart from an example: a long read timeout (reasoning models stay silent for minutes), your own retries that decide by error code, and reading the counters. See Limits and Tokens and usage.
import osimport randomimport time
import httpxfrom openai import APIConnectionError, APIStatusError, APITimeoutError, OpenAIfrom openai.types.chat import ChatCompletion
client = OpenAI( base_url="https://api.waibee.com/v1", api_key=os.environ["WAIBEE_API_KEY"], # Reasoning models stay silent for minutes: a short read timeout cuts off a live request. timeout=httpx.Timeout(connect=10.0, read=600.0, write=30.0, pool=10.0), max_retries=0, # we retry ourselves to decide by error code)
MAX_ATTEMPTS = 3RETRIABLE_STATUSES = frozenset({408, 429, 500, 502, 503})
def is_retriable(error: APIStatusError) -> bool: # The key's spending limit lifts only when the counter resets: a retry will not help. return error.status_code in RETRIABLE_STATUSES and error.code != "api_key_limit_exceeded"
def complete(**kwargs) -> ChatCompletion: for attempt in range(MAX_ATTEMPTS): last_attempt = attempt == MAX_ATTEMPTS - 1 try: return client.chat.completions.create(**kwargs) except APIStatusError as error: if last_attempt or not is_retriable(error): raise except (APITimeoutError, APIConnectionError): if last_attempt: raise # Random jitter spreads out client retries so they do not land in one wave. time.sleep(2**attempt + random.random()) raise AssertionError("unreachable: the loop either returned a response or raised")
response = complete( model="waibee/auto", messages=[{"role": "user", "content": "Answer in one word: ready"}],)usage = response.usagecached = getattr(usage.prompt_tokens_details, "cached_tokens", 0) or 0print( f"model {response.model}: input {usage.prompt_tokens}, output {usage.completion_tokens}, " f"cached {cached}")model anthropic/claude-haiku-4.5: input 13, output 5, cached 0Log response.model together with usage: on waibee/auto, it is the only way to find out later which model answered and what it cost.