Skip to content

Python SDK Integration ​

When using the official OpenAI Python SDK, simply replace api_key, base_url, and model with CoreRouter information.

Installation ​

bash
pip install openai

To read environment variables from a .env file, additionally install:

bash
pip install python-dotenv

Basic Usage ​

python
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.environ["COREROUTER_API_KEY"],
    base_url="https://api.corerouter.cloud/v1",
)

completion = client.chat.completions.create(
    model="claude-sonnet-4-5",
    messages=[
        {"role": "user", "content": "Hello, please introduce yourself."}
    ],
)

print(completion.choices[0].message.content)

Streaming Output ​

python
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.environ["COREROUTER_API_KEY"],
    base_url="https://api.corerouter.cloud/v1",
)

stream = client.chat.completions.create(
    model="claude-sonnet-4-5",
    messages=[{"role": "user", "content": "Introduce CoreRouter in three sentences."}],
    stream=True,
)

for chunk in stream:
    if not chunk.choices:
        continue
    content = chunk.choices[0].delta.content
    if content:
        print(content, end="", flush=True)

Streaming responses may include usage events with an empty choices array. Skip these events before reading text deltas.

Multi-Turn Conversation ​

python
messages = [
    {"role": "user", "content": "Hello"},
]

completion = client.chat.completions.create(
    model="claude-sonnet-4-5",
    messages=messages,
)

messages.append({
    "role": "assistant",
    "content": completion.choices[0].message.content,
})
messages.append({"role": "user", "content": "Please write a Python hello function."})

completion = client.chat.completions.create(
    model="claude-sonnet-4-5",
    messages=messages,
)

print(completion.choices[0].message.content)

Tool Calling ​

python
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get weather information for a specified city",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {"type": "string", "description": "City name"}
                },
                "required": ["city"],
            },
        },
    }
]

completion = client.chat.completions.create(
    model="claude-sonnet-4-5",
    messages=[{"role": "user", "content": "What's the weather like in Beijing?"}],
    tools=tools,
)

tool_calls = completion.choices[0].message.tool_calls
if tool_calls:
    print(tool_calls[0].function.name)
    print(tool_calls[0].function.arguments)

Tool calling availability depends on model capabilities. For Agents or coding tools, prioritize models marked as supporting Tool Calling / Coding Agent in the console.

Vision Understanding ​

python
completion = client.chat.completions.create(
    model="claude-sonnet-4-5",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "What's in this image?"},
                {
                    "type": "image_url",
                    "image_url": {"url": "https://example.com/image.jpg"},
                },
            ],
        }
    ],
)

print(completion.choices[0].message.content)

Responses API ​

This example requires the Model ID to support Responses. Regular chat models may not work. If the current SDK doesn't have client.responses, upgrade the openai package first, or call directly following Responses API curl examples.

python
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.environ["COREROUTER_API_KEY"],
    base_url="https://api.corerouter.cloud/v1",
)

response = client.responses.create(
    model="responses-model-id",
    input="Introduce CoreRouter in three sentences.",
)

print(response.output_text)

Embeddings ​

python
result = client.embeddings.create(
    model="embedding-model-id",
    input=["First text segment", "Second text segment"],
)

print(len(result.data[0].embedding))

Using .env ​

Python doesn't automatically read .env files. You can either set Keys in system environment variables or use python-dotenv.

.env example:

bash
COREROUTER_API_KEY=sk-xxxxxxxxxxxxxxxx
COREROUTER_BASE_URL=https://api.corerouter.cloud/v1
COREROUTER_MODEL=claude-sonnet-4-5

Code example:

python
from dotenv import load_dotenv
from openai import OpenAI
import os

load_dotenv()

client = OpenAI(
    api_key=os.environ["COREROUTER_API_KEY"],
    base_url=os.environ.get("COREROUTER_BASE_URL", "https://api.corerouter.cloud/v1"),
)

completion = client.chat.completions.create(
    model=os.environ.get("COREROUTER_MODEL", "claude-sonnet-4-5"),
    messages=[{"role": "user", "content": "Hello"}],
)

print(completion.choices[0].message.content)

Add .env to .gitignore; don't commit API Keys to repositories.

Error Handling ​

python
from openai import APIConnectionError, APIError, APIStatusError, AuthenticationError, OpenAI
import os

client = OpenAI(
    api_key=os.environ["COREROUTER_API_KEY"],
    base_url="https://api.corerouter.cloud/v1",
    max_retries=0,
)

try:
    completion = client.chat.completions.create(
        model="claude-sonnet-4-5",
        messages=[{"role": "user", "content": "Hello"}],
    )
    print(completion.choices[0].message.content)
except AuthenticationError:
    print("Invalid API Key, check Authorization configuration.")
except APIConnectionError:
    print("Connection failed or timed out; an HTTP status code may not be available.")
except APIStatusError as exc:
    request_id = exc.response.headers.get("x-oneapi-request-id", "not provided")
    print(f"API request failed: HTTP {exc.status_code}, Request ID: {request_id}")
except APIError:
    print("The SDK could not process the response; check SDK version and response format.")

Connection errors, including timeouts, may have no status_code; read it only for HTTP error responses. The example disables SDK retries with max_retries=0 for troubleshooting. If enabling retries in your application, limit attempts and check whether the original request was accepted, especially for media generation.

Released under the MIT License.