Text Models

Before calling, set your API key and TOKENGRID_BASE_URL environment variables. The base URL includes /v1. See the quick start.

Use the Chat Completions API for text, conversations, streaming and other supported model features.

Use an API key and the exact Model ID from the catalog. Features and parameters depend on the selected model and enabled service.

Chat Completions API

Replace YOUR_API_BASE_URL with your assigned gateway base address; the examples already include /v1, so do not add it twice. Setting TOKENGRID_BASE_URL does not change examples with hard-coded addresses; replace the placeholder in those examples separately.

Send messages as an array of roles and content. Select a language below. Consult the model's own prompt guidance and validate its behavior.

Python · OpenAI SDK
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ.get("TOKENGRID_API_KEY"),
    base_url="YOUR_API_BASE_URL/v1"
)

response = client.chat.completions.create(
    model="YOUR_MODEL_ID",
    messages=[
        {"role": "user", "content": "Explain quantum computing in simple terms."}
    ]
)

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

Common patterns

Multi-turn conversations

Your application maintains and sends the history needed for context.

Python
messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "What is the capital of France?"},
    {"role": "assistant", "content": "The capital of France is Paris."},
    {"role": "user", "content": "What is its population?"}
]

response = client.chat.completions.create(
    model="YOUR_MODEL_ID",
    messages=messages
)

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

System prompts

Use a system message to set the model's role and behavior.

Python
messages = [
    {"role": "system", "content": "You are a Python expert. Give concise code examples."},
    {"role": "user", "content": "How do I read a CSV file?"}
]

response = client.chat.completions.create(
    model="YOUR_MODEL_ID",
    messages=messages
)

Streaming responses

Use a supported streaming option to receive incremental output.

Python
stream = client.chat.completions.create(
    model="YOUR_MODEL_ID",
    messages=[{"role": "user", "content": "Tell me a short story."}],
    stream=True
)

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

Asynchronous requests

Use an asynchronous SDK client when your application needs concurrent requests.

Python · AsyncOpenAI
import asyncio
from openai import AsyncOpenAI

client = AsyncOpenAI(
    api_key=os.environ.get("TOKENGRID_API_KEY"),
    base_url="YOUR_API_BASE_URL/v1"
)

async def main():
    response = await client.chat.completions.create(
        model="YOUR_MODEL_ID",
        messages=[{"role": "user", "content": "Hello"}]
    )
    print(response.choices[0].message.content)

asyncio.run(main())

Usage information

When returned, usage reports input, output and total tokens. Streaming usage depends on the interface's supported options.

Python
response = client.chat.completions.create(
    model="YOUR_MODEL_ID",
    messages=[{"role": "user", "content": "Hello"}]
)

print(response.usage.prompt_tokens)      # Input tokens
print(response.usage.completion_tokens)  # Output tokens
print(response.usage.total_tokens)       # Total tokens

Configuration and tuning

Supported parameters and defaults vary by model.

Temperature

temperature controls sampling randomness.

Python
response = client.chat.completions.create(
    model="YOUR_MODEL_ID",
    messages=[{"role": "user", "content": "Write a short poem"}],
    temperature=0.7
)

Maximum output tokens

max_tokens limits output; reaching the limit may result in finish_reason: length.

Nucleus sampling

top_p sets the cumulative probability threshold for sampling.

Repetition penalties

Frequency and presence penalties can reduce repetition where supported.

Python
response = client.chat.completions.create(
    model="YOUR_MODEL_ID",
    messages=[{"role": "user", "content": "Write an article"}],
    temperature=0.7,
    max_tokens=500,
    top_p=0.9,
    frequency_penalty=0.5,
    presence_penalty=0.5
)

Understanding tokens

A token can be a character, part of a word or a whole word. Tokenizers differ between models. Token counts affect context limits, usage and processing time; estimates can differ from actual reported usage.