Python · OpenAI

Connect Python to Tikway: OpenAI-compatible Chat Completions with the standard library

Last updated:

Make your first Tikway text request using Python’s standard library. This guide covers environment variables, request JSON, response reading and error handling without installing a third-party SDK. Use it to add text generation to a script or backend service.

Check the endpoint, model and API key

Tikway provides model API access. This example uses its OpenAI-compatible Chat Completions endpoint and a Tikway API key. Create or retrieve your key in the console, then use the model catalog to confirm the chosen model’s endpoint, parameters and current billing rules.

The example uses openai/gpt-5.4-mini, the model ID shown in the homepage example. Keep the openai/ prefix. When choosing a different model, copy its exact catalog ID and check its supported parameters rather than carrying every optional setting across.

Setting Example value
Method POST
Full URL https://api.tikway.ai/v1/chat/completions
Authentication Authorization: Bearer <YOUR_TIKWAY_API_KEY>
Request format Content-Type: application/json
Main required fields model and at least one item in messages
Response mode stream: false for ordinary JSON

This full URL includes /v1/chat/completions. For the OpenAI SDK, the base URL is https://api.tikway.ai/v1; do not interchange these two settings.

1. Install Python and set environment variables

Use Python 3.10 or newer and confirm python --version works. The example uses built-in urllib, json and os, so no pip install is needed. Replace the placeholder with your own key and keep it out of source control and public comments.

Windows PowerShell:

powershell
$env:TIKWAY_API_KEY = "YOUR_TIKWAY_API_KEY"

macOS / Linux:

bash
export TIKWAY_API_KEY='YOUR_TIKWAY_API_KEY'

These variables apply to the current terminal and its child processes. Run the script in the same terminal.

2. Save and run the complete example

Save this as tikway_chat.py. The downloadable script has the same request logic, with Chinese prompts and local messages. The script reads the environment, sends a short prompt and prints the first answer. Running it makes a real model request, billed according to your account and the model’s rules.

python
import json
import os
import sys
from urllib import error, request


ENDPOINT = "https://api.tikway.ai/v1/chat/completions"


def main():
    api_key = os.environ.get("TIKWAY_API_KEY", "").strip()
    if not api_key:
        raise RuntimeError("Set TIKWAY_API_KEY in this terminal first.")

    payload = {
        "model": os.environ.get("TIKWAY_MODEL", "").strip() or "openai/gpt-5.4-mini",
        "messages": [
            {"role": "user", "content": "Explain what an API is in one sentence."}
        ],
        "stream": False,
    }
    req = request.Request(
        ENDPOINT,
        data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
        headers={
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json",
        },
        method="POST",
    )

    try:
        with request.urlopen(req, timeout=60) as response:
            result = json.loads(response.read().decode("utf-8"))
    except error.HTTPError as exc:
        request_id = exc.headers.get("x-request-id", "not provided")
        detail = "Check the error code documentation."
        try:
            body = json.loads(exc.read().decode("utf-8"))
            api_error = body.get("error", {}) if isinstance(body, dict) else {}
            if isinstance(api_error, dict):
                code = api_error.get("code") or api_error.get("type") or "unknown"
                message = str(api_error.get("message", ""))[:300]
                detail = f"{code}: {message}"
        except (ValueError, UnicodeError):
            pass
        raise RuntimeError(
            f"HTTP {exc.code}; request_id={request_id}; {detail}"
        ) from None
    except error.URLError as exc:
        raise RuntimeError(f"Network or TLS connection failed: {exc.reason}") from None

    if not isinstance(result, dict):
        raise RuntimeError("Response is not a JSON object; check the endpoint.")
    choices = result.get("choices")
    if not isinstance(choices, list) or not choices:
        raise RuntimeError("Response has no readable choices.")
    choice = choices[0]
    message = choice.get("message", {}) if isinstance(choice, dict) else {}
    text = message.get("content") if isinstance(message, dict) else None
    if not isinstance(text, str):
        raise RuntimeError("No text content returned; check model capabilities and response structure.")
    print(text)


if __name__ == "__main__":
    try:
        main()
    except (RuntimeError, TimeoutError, ValueError, UnicodeError) as exc:
        print(f"Request did not complete: {exc}", file=sys.stderr)
        sys.exit(1)

Run:

bash
python tikway_chat.py

The model generates the actual answer. Ordinary text is usually in choices[0].message.content; tool calls and other capabilities require their own response handling.

The example leaves out optional temperature and output-length settings so the first request focuses on the URL, authentication and message format. Check the selected model before adding parameters: protocol compatibility does not imply identical parameter support.

3. Change models or add conversation history

Set TIKWAY_MODEL to another catalog ID that supports the same endpoint. For PowerShell:

powershell
$env:TIKWAY_MODEL = "FULL_MODEL_ID_FROM_CATALOG"
python tikway_chat.py

For a multi-turn conversation, include the required history in messages, in order:

json
[
    { "role": "user", "content": "Explain what an API is." },
    { "role": "assistant", "content": "An API is an interface for exchanging data or calling functions between programs." },
    { "role": "user", "content": "Give an example using a weather lookup." }
]

The assistant text here is a fabricated format example. Longer history increases context and input usage; keep it within the model’s limits and your budget.

4. Check completion and record usage

Reading text does not establish that a task finished. Inspect the first choice’s finish_reason: length commonly indicates an output limit, while tool_calls requires the application to handle tools. Treat truncated answers as partial results.

Responses may include usage.prompt_tokens, usage.completion_tokens and finer usage fields. Store the necessary counts and x-request-id, when available, for billing checks and troubleshooting. Avoid logging entire private conversations by default.

Check whether a variable is set without printing its value:

bash
python -c "import os; print('set' if os.getenv('TIKWAY_API_KEY', '').strip() else 'missing')"

An unset or whitespace-only TIKWAY_MODEL uses this script’s default. Confirm that ID in the current catalog. In a web application, keep the key on your server and route browser requests through your own backend.

Troubleshoot common errors

Read the HTTP status, error.code / error.type and message together. A status code alone gives only a broad category.

Symptom What to check
Missing TIKWAY_API_KEY Set it in the terminal that runs the script.
401 Key validity, whitespace and Bearer authentication.
400 or 422 Model ID, message structure and supported parameters.
403 Account or key permissions for the requested resource.
404 Full path and model ID; avoid a repeated /v1.
429 Error fields: distinguish balance or quota issues from rate limits.
5xx or timeout Keep the request ID and timestamp; use bounded retries if appropriate.
JSON without text Text-model suitability and tool or other response blocks.

The script does not retry automatically. A client timeout cannot show whether the server already processed the request; check request records before repeating it.

Further reading