AIXHUBDocs
SDK integration

Anthropic Python SDK with AIXHUB

Create an isolated Python environment, call AIXHUB Messages, inspect content blocks, stream safely, and manage SDK upgrades.

The Anthropic Python SDK appends /v1/messages to the AIXHUB root Base URL https://api.aixhub.org. This guide passes the AIXHUB key and Base URL explicitly so official Anthropic credentials or profiles cannot silently replace them.

Prerequisites

  • A Python 3 installation supported by the current anthropic package. Check with py -3 --version on Windows or python3 --version on macOS/Linux.
  • A dedicated AIXHUB API key for this application.
  • An exact Anthropic Messages-compatible model ID from Model routes. Examples use panel-anthropic-model-id as a visible stand-in.
  • A disposable project directory that does not already contain a different virtual environment or a file named anthropic.py.

AIXHUB_API_KEY and AIXHUB_MODEL are conventions used by this documentation. The SDK does not automatically read them; the script passes them explicitly to Anthropic(...) and messages.create(...).

Steps

Create and activate a virtual environment

Windows PowerShell:

py -3 -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
python -m pip install anthropic
python -m pip show anthropic

If activation is blocked by local policy, do not weaken the machine-wide policy. Run .\.venv\Scripts\python.exe -m pip ... and .\.venv\Scripts\python.exe aixhub_anthropic.py directly.

macOS or Linux:

python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install anthropic
python -m pip show anthropic

Record the installed version before troubleshooting or upgrading. Do not use sudo pip or install into the system interpreter.

Set temporary credentials without storing the key in history

Open a disposable shell where AIXHUB_API_KEY and AIXHUB_MODEL are not already set. This prevents the test from overwriting another workflow's values.

Bash:

read -rsp "AIXHUB API key: " AIXHUB_API_KEY && echo
export AIXHUB_API_KEY
export AIXHUB_MODEL="panel-anthropic-model-id"

PowerShell:

$secureKey = Read-Host "AIXHUB API key" -AsSecureString
$env:AIXHUB_API_KEY = [System.Net.NetworkCredential]::new("", $secureKey).Password
$env:AIXHUB_MODEL = "panel-anthropic-model-id"

Replace the model stand-in with the complete ID copied from the panel. In production, inject the key from an approved server-side secret store instead of an interactive shell.

Create the complete non-streaming script

Create aixhub_anthropic.py:

import os
import sys

import anthropic
from anthropic import Anthropic


def main() -> None:
    client = Anthropic(
        api_key=os.environ["AIXHUB_API_KEY"],
        base_url="https://api.aixhub.org",
        max_retries=0,
        timeout=60.0,
    )
    try:
        message = client.messages.create(
            model=os.environ["AIXHUB_MODEL"],
            max_tokens=16,
            messages=[
                {"role": "user", "content": "Reply with OK only."},
            ],
        )

        text = "".join(
            block.text for block in message.content if block.type == "text"
        )
        print(text)
        print(message.model_dump_json(indent=2))

        request_id = getattr(message, "_request_id", None)
        if request_id:
            print(f"request_id={request_id}")

        if message.stop_reason != "end_turn":
            raise RuntimeError(f"message ended with stop_reason={message.stop_reason}")
    except anthropic.APIStatusError as exc:
        print(f"status_code={exc.status_code}", file=sys.stderr)
        if exc.request_id:
            print(f"request_id={exc.request_id}", file=sys.stderr)
        raise
    finally:
        client.close()


if __name__ == "__main__":
    main()

The SDK returns typed content blocks. Filter them by type == "text" instead of assuming message.content[0] is text. model_dump_json() exposes the complete message, stop reason, and usage for inspection.

Run the script with the Python from the active virtual environment:

python aixhub_anthropic.py

Stream text and require the final message

Create aixhub_anthropic_stream.py:

import os
import sys

import anthropic
from anthropic import Anthropic


client = Anthropic(
    api_key=os.environ["AIXHUB_API_KEY"],
    base_url="https://api.aixhub.org",
    max_retries=0,
    timeout=60.0,
)

try:
    with client.messages.stream(
        model=os.environ["AIXHUB_MODEL"],
        max_tokens=16,
        messages=[
            {"role": "user", "content": "Reply with OK only."},
        ],
    ) as stream:
        if stream.request_id:
            print(f"request_id={stream.request_id}", file=sys.stderr)
        for text in stream.text_stream:
            print(text, end="", flush=True)
        final_message = stream.get_final_message()

    print()
    print(final_message.model_dump_json(indent=2))
    if final_message.stop_reason != "end_turn":
        raise RuntimeError(
            f"stream ended with stop_reason={final_message.stop_reason}"
        )
except anthropic.APIStatusError as exc:
    print(f"status_code={exc.status_code}", file=sys.stderr)
    if exc.request_id:
        print(f"request_id={exc.request_id}", file=sys.stderr)
    raise
finally:
    client.close()

Run it with python aixhub_anthropic_stream.py. The stream helper must be consumed inside its context manager before get_final_message() is used. Partial text and HTTP 200 are not enough; an error event, disconnect, or missing final message is not success. Check Usage before replaying an ambiguous generation.

Verification

The first line from the non-streaming script, and the accumulated streaming text, should be:

OK

Also verify:

  1. The complete message contains a text block with OK, the expected model ID, and stop_reason equal to end_turn.
  2. A request ID is recorded only when the SDK exposes one; do not synthesize it.
  3. AIXHUB Usage contains a request at the same time with the selected model and successful status.
  4. The stream produced a final message after all events were consumed.
The Anthropic SDK returns OK in a typed text block, the final message ends normally, and AIXHUB records the matching Messages request.

Troubleshooting

  • ModuleNotFoundError or import failure: Confirm python -m pip show anthropic points into the active .venv; rename any local anthropic.py, then upgrade the package in that environment.
  • 401 / AuthenticationError: Confirm the explicit AIXHUB_API_KEY is current. Do not rely on ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, or an official profile for this script.
  • 403 / PermissionDeniedError: Check key group, subscription, and balance. INSUFFICIENT_BALANCE is a 403 condition.
  • 404 / NotFoundError: Keep base_url="https://api.aixhub.org"; the SDK appends /v1/messages. Recopy the model and confirm it supports Messages.
  • 413 / RequestTooLargeError: Reduce the prompt or attachments before retrying.
  • 429 / RateLimitError: Honor an actual Retry-After, reduce concurrency, and use a bounded retry budget.
  • APIConnectionError or timeout: Check proxy, TLS, DNS, and network state. The result is ambiguous; inspect Usage before sending another billable generation.
  • APIStatusError: Record status_code and request_id when present. Redact the response body before sharing it.
  • No text at content[0]: This guide intentionally filters content blocks by type. Inspect the complete message for tool-use or other block types.

The verification scripts set max_retries=0 so one command produces one observable SDK attempt. In production, choose exactly one retry owner: either enable SDK retries and do not wrap the call in an application retry loop, or keep max_retries=0 and let the application own retries. Cap all layers together at three total attempts including the original request. For example, SDK max_retries=2 already consumes that complete budget. Check Usage before replaying an ambiguous timeout, 5xx, stream error, or disconnect, and never replay unless the application accepts duplicate output and charges. See Error code reference.

Next step

Compare the typed message with the raw Anthropic Messages reference, or configure the maintained terminal workflow in Claude Code.

Upgrade and restore

Before upgrading, record the working package set:

python -m pip freeze > requirements.before-aixhub-sdk.txt
python -m pip show anthropic

Upgrade only inside the virtual environment, then rerun both scripts and Usage verification:

python -m pip install --upgrade anthropic
python -m pip check
python aixhub_anthropic.py

If an upgrade breaks a previously verified integration, reinstall the recorded version in the same virtual environment and test again:

python -m pip install "anthropic==<recorded-version>"

To stop using the package in this environment:

python -m pip uninstall anthropic
deactivate

Delete the virtual environment or sample scripts only when they were created solely for this guide and contain no work that must be retained. Revoke the dedicated AIXHUB key after confirming no deployed service uses it.

Security

  • Keep the key out of source files, committed .env files, tracebacks, notebooks, telemetry, and full HTTP logs.

  • AIXHUB_API_KEY is plain text in the current process environment after input. Limit child processes and use a real secret store for deployed services.

  • The full message can contain prompts, generated content, tool inputs, and metadata. Redact it before logging or sharing.

  • Set retry, timeout, and duplicate-handling policies explicitly for billable generation.

  • In the disposable shell opened for this guide, clear temporary state after testing:

    unset AIXHUB_API_KEY AIXHUB_MODEL
    Remove-Item Env:AIXHUB_API_KEY, Env:AIXHUB_MODEL -ErrorAction SilentlyContinue
    Remove-Variable secureKey -ErrorAction SilentlyContinue

    If either environment variable existed before this guide, do not run the cleanup commands in that shell. Use a separate terminal for the test, or restore the prior value from its authorized secret source.

Official sources

Last verified: 2026-07-14

On this page