Examples

Run these Python examples with gpt-6.2-astra andllm-api-adapter==0.11.0.

Setup

Use Python 3.10–3.14 in a virtual environment and set OPENAI_API_KEY in your terminal.

Install for sync examples

python -m pip install llm-api-adapter==0.11.0

Install for the async example

python -m pip install "llm-api-adapter[async]==0.11.0"

For help setting up Python and the key, see the Quickstart.

Sync chat

Send a chat request

Input
Ask for a short greeting.
Expected output
A greeting such as Hello!

After installation, save as quickstart.py and runpython quickstart.py from the same directory.

import os

from llm_api_adapter.models.messages.chat_message import UserMessage
from llm_api_adapter.universal_adapter import UniversalLLMAPIAdapter

api_key = os.environ.get("OPENAI_API_KEY")
if not api_key:
    raise SystemExit("Set OPENAI_API_KEY before running this example.")

adapter = UniversalLLMAPIAdapter(
    organization="openai",
    model="gpt-6.2-astra",
    api_key=api_key,
)
response = adapter.chat(
    messages=[UserMessage("Reply with a short greeting.")],
    reasoning_level="low",
    max_tokens=512,
    timeout_s=30,
)
if not response.content or not response.content.strip():
    raise SystemExit("The model completed without a text response.")
print(response.content)

Async and streaming

Send an async request

Input
Ask for the word Ready using achat().
Expected output
Ready

After installation, save as async_chat.py and runpython async_chat.py from the same directory.

import asyncio
import os

from llm_api_adapter.models.messages.chat_message import UserMessage
from llm_api_adapter.universal_adapter import UniversalLLMAPIAdapter


async def main():
    adapter = UniversalLLMAPIAdapter(
        organization="openai", model="gpt-6.2-astra", api_key=os.environ["OPENAI_API_KEY"],
    )
    response = await adapter.achat(
        messages=[UserMessage("Reply with the word Ready only.")],
        reasoning_level="low",
        max_tokens=512,
        timeout_s=35,
    )
    print(response.content)


asyncio.run(main())

Stream a response

Input
Ask for the words alpha beta gamma.
Expected output
alpha beta gamma, printed as chunks arrive.

After installation, save as streaming.py and runpython streaming.py from the same directory.

import os
from contextlib import closing

from llm_api_adapter.models.messages.chat_message import UserMessage
from llm_api_adapter.universal_adapter import UniversalLLMAPIAdapter

adapter = UniversalLLMAPIAdapter(
    organization="openai", model="gpt-6.2-astra", api_key=os.environ["OPENAI_API_KEY"],
)

with closing(adapter.stream_chat(
    messages=[UserMessage("Write alpha beta gamma, with no punctuation.")],
    reasoning_level="low",
    max_tokens=512,
    timeout_s=35,
)) as stream:
    for text in stream:
        print(text, end="", flush=True)
print()

Tools and structured output

Call a local function

Input
Ask the model to call add with 2 and 3. The Python script validates the tool call and runs add locally.
Expected output
5

After installation, save as tools.py and runpython tools.py from the same directory.

import os

from llm_api_adapter.models.messages.chat_message import UserMessage
from llm_api_adapter.models.tools import ToolSpec
from llm_api_adapter.universal_adapter import UniversalLLMAPIAdapter


def add(a: int, b: int) -> int:
    return a + b


tool = ToolSpec(
    name="add",
    description="Add two integers.",
    json_schema={
        "type": "object",
        "properties": {"a": {"type": "integer"}, "b": {"type": "integer"}},
        "required": ["a", "b"],
        "additionalProperties": False,
    },
)
adapter = UniversalLLMAPIAdapter(
    organization="openai", model="gpt-6.2-astra", api_key=os.environ["OPENAI_API_KEY"],
)
response = adapter.chat(
    messages=[UserMessage("Use add to add 2 and 3.")],
    tools=[tool],
    tool_choice="add",
    reasoning_level="low",
    max_tokens=512,
    timeout_s=35,
)
calls = response.tool_calls or []
if len(calls) != 1 or calls[0].name != "add":
    raise RuntimeError("Expected a single call to add.")

arguments = calls[0].arguments
a, b = arguments.get("a"), arguments.get("b")
if type(a) is not int or type(b) is not int:
    raise ValueError("The add tool requires two integer arguments.")
print(add(a, b))

Validate JSON with a schema

Input
Ask for a JSON object with the city Oslo and the country Norway.
Expected output
{"city": "Oslo", "country": "Norway"}

After installation, save as structured_output.py and runpython structured_output.py from the same directory.

import json
import os

from llm_api_adapter.models.messages.chat_message import UserMessage
from llm_api_adapter.universal_adapter import UniversalLLMAPIAdapter

schema = {
    "type": "object",
    "properties": {"city": {"type": "string"}, "country": {"type": "string"}},
    "required": ["city", "country"],
    "additionalProperties": False,
}
adapter = UniversalLLMAPIAdapter(
    organization="openai", model="gpt-6.2-astra", api_key=os.environ["OPENAI_API_KEY"],
)
response = adapter.chat(
    messages=[UserMessage("Return a JSON object with city Oslo and country Norway.")],
    json_schema=schema,
    reasoning_level="low",
    max_tokens=512,
    timeout_s=35,
)
print(json.dumps(response.parsed_json, sort_keys=True))

Vision and PDF

Read an image

Input
A solid red PNG. Ask for its color.
Expected output
Red

Download red.png and save it alongside the script.

After installation, save as vision.py and runpython vision.py from the same directory.

import os
from pathlib import Path

from llm_api_adapter.models.messages.chat_message import UserMessage
from llm_api_adapter.models.messages.file_parts import ImagePart
from llm_api_adapter.universal_adapter import UniversalLLMAPIAdapter

image = ImagePart(data=Path("red.png").read_bytes(), media_type="image/png")
adapter = UniversalLLMAPIAdapter(
    organization="openai", model="gpt-6.2-astra", api_key=os.environ["OPENAI_API_KEY"],
)
response = adapter.chat(
    messages=[UserMessage("Reply with the solid color of this image in one word.", files=[image])],
    reasoning_level="low",
    max_tokens=512,
    timeout_s=35,
)
print(response.content)

Read a PDF

Input
A one-page PDF containing a reference code.
Expected output
ORBIT-42

Download sample.pdf and save it alongside the script.

After installation, save as pdf_input.py and runpython pdf_input.py from the same directory.

import os
from pathlib import Path

from llm_api_adapter.models.messages.chat_message import UserMessage
from llm_api_adapter.models.messages.file_parts import DocumentPart
from llm_api_adapter.universal_adapter import UniversalLLMAPIAdapter

pdf = DocumentPart(data=Path("sample.pdf").read_bytes(), media_type="application/pdf")
adapter = UniversalLLMAPIAdapter(
    organization="openai", model="gpt-6.2-astra", api_key=os.environ["OPENAI_API_KEY"],
)
response = adapter.chat(
    messages=[UserMessage("Reply with the reference code from the PDF only.", files=[pdf])],
    reasoning_level="low",
    max_tokens=512,
    timeout_s=35,
)
print(response.content)

Reasoning

Set the reasoning level

Input
Ask how many cards remain when three cards are lost from four packs of six. The request sets reasoning_level to medium.
Expected output
21

After installation, save as reasoning.py and runpython reasoning.py from the same directory.

import os

from llm_api_adapter.models.messages.chat_message import UserMessage
from llm_api_adapter.universal_adapter import UniversalLLMAPIAdapter

adapter = UniversalLLMAPIAdapter(
    organization="openai", model="gpt-6.2-astra", api_key=os.environ["OPENAI_API_KEY"],
)
response = adapter.chat(
    messages=[UserMessage(
        "A box contains 4 packs of 6 cards. Three cards are lost. "
        "Reply with the remaining number only."
    )],
    reasoning_level="medium",
    max_tokens=512,
    timeout_s=35,
)
print(response.content)

Usage and cost

Read token counts and estimated cost

Input
Ask for OK and read the token counts and cost estimate from ChatResponse.
Expected output
Input tokens, output tokens, and the estimated cost in USD. Counts and cost can vary per call.

After installation, save as usage_and_cost.py and runpython usage_and_cost.py from the same directory.

import os

from llm_api_adapter.models.messages.chat_message import UserMessage
from llm_api_adapter.universal_adapter import UniversalLLMAPIAdapter

adapter = UniversalLLMAPIAdapter(
    organization="openai", model="gpt-6.2-astra", api_key=os.environ["OPENAI_API_KEY"],
)
response = adapter.chat(
    messages=[UserMessage("Reply with the word OK only.")],
    reasoning_level="low",
    max_tokens=512,
    timeout_s=35,
)

if response.usage:
    print(f"Input tokens: {response.usage.input_tokens}")
    print(f"Output tokens: {response.usage.output_tokens}")
else:
    print("Usage unavailable")

if response.cost_total is not None and response.currency:
    print(f"Estimated cost: {response.cost_total:.6f} {response.currency}")
else:
    print("Cost unavailable")