Text Models
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.
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.
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)import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.TOKENGRID_API_KEY,
baseURL: "YOUR_API_BASE_URL/v1",
});
const response = await client.chat.completions.create({
model: "YOUR_MODEL_ID",
messages: [
{ role: "user", content: "Explain quantum computing in simple terms." },
],
});
console.log(response.choices[0].message.content);curl "$TOKENGRID_BASE_URL/chat/completions" \
-H "request-id: $REQUEST_ID" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKENGRID_API_KEY" \
-d '{
"model": "YOUR_MODEL_ID",
"messages": [
{"role": "user", "content": "Explain quantum computing in simple terms."}
]
}'Common patterns
Multi-turn conversations
Your application maintains and sends the history needed for context.
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.
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.
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.
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())import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.TOKENGRID_API_KEY,
baseURL: "YOUR_API_BASE_URL/v1",
});
async function main() {
const response = await client.chat.completions.create({
model: "YOUR_MODEL_ID",
messages: [{ role: "user", content: "Hello!" }],
});
console.log(response.choices[0].message.content);
}
main().catch(console.error);Usage information
When returned, usage reports input, output and total tokens. Streaming usage depends on the interface's supported options.
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 tokensConfiguration and tuning
Supported parameters and defaults vary by model.
Temperature
temperature controls sampling randomness.
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.
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.