Skip to content
Orqen Docs

Code Examples

Python tool-calling agent

A complete agent loop in Python. Pick the SDK you already use — Anthropic Messages, OpenAI Chat Completions, or Bedrock Converse — and point it at Orqen. Tool shapes stay in each provider's native format.

New to Orqen? Start with provider migration for minimal before/after snippets, then use this page for a multi-turn loop.

Anthropic SDKagent.py
import anthropic
import json
import os

client = anthropic.Anthropic(
    api_key=os.environ["ORQEN_API_KEY"],
    base_url="https://api.orqen.app",
)

TOOLS = [
    {
        "name": "get_weather",
        "description": "Get current weather for a city.",
        "input_schema": {
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"],
        },
    },
]

def call_tool(name: str, args: dict) -> dict:
    if name == "get_weather":
        return {"city": args["city"], "temperature_c": 13, "conditions": "light rain"}
    return {"error": f"Unknown tool: {name}"}

def run(user_message: str) -> str:
    messages = [{"role": "user", "content": user_message}]
    for _ in range(8):
        response = client.messages.create(
            model="claude-sonnet-4-6",
            max_tokens=4096,
            messages=messages,
            tools=TOOLS,
        )
        if response.stop_reason == "end_turn":
            for block in response.content:
                if hasattr(block, "text"):
                    return block.text
            return ""
        if response.stop_reason != "tool_use":
            break
        messages.append({"role": "assistant", "content": response.content})
        tool_results = []
        for block in response.content:
            if block.type != "tool_use":
                continue
            result = call_tool(block.name, block.input)
            tool_results.append({
                "type": "tool_result",
                "tool_use_id": block.id,
                "content": json.dumps(result),
            })
        messages.append({"role": "user", "content": tool_results})
    return "Stopped after max tool rounds."

print(run("What is the weather in London?"))

Inspect optimization headers

Every response includes x-orqen-* headers. Use the wire format that matches your SDK:

OpenAI SDK
import httpx

r = httpx.post(
    "https://api.orqen.app/v1/chat/completions",
    headers={"Authorization": "Bearer sk-orq-YOUR_KEY"},
    json={
        "model": "gpt-4o",
        "messages": [{"role": "user", "content": "What is the weather in London?"}],
        "tools": [...],
    },
)
print(r.headers.get("x-orqen-tools-input"))
print(r.headers.get("x-orqen-tools-output"))
print(r.headers.get("x-orqen-routing"))