Skip to Content
WikiAPI DocumentationChat Completions

Chat Completions

Creates a model response for the given chat conversation.

Endpoint

POST https://gateway.mytokengate.com/v1/chat/completions

Request Example

curl --request POST \ --url https://gateway.mytokengate.com/v1/chat/completions \ --header 'Authorization: Bearer <token>' \ --header 'Content-Type: application/json' \ --data '{ "model": "gpt-4o", "messages": [ { "role": "user", "content": "What opportunities and challenges will the AI industry face in 2025?" } ] }'

Authentication

All requests require a Bearer token in the Authorization header:

Authorization: Bearer YOUR_API_KEY

Request Parameters

ParameterTypeRequiredDescription
modelstringYesModel name. See Models for available options.
messagesarrayYesA list of messages comprising the conversation so far. See Message Formats.
max_completion_tokensintegerNoMaximum tokens to generate (includes reasoning tokens for o-series models).
max_tokensintegerNoDeprecated. Use max_completion_tokens instead.
temperaturefloatNoControls randomness. Range: 0-2. Default varies by model.
top_pfloatNoNucleus sampling parameter. Range: 0-1.
streambooleanNoIf true, returns tokens as Server-Sent Events. Stream terminates with data: [DONE].
stream_optionsobjectNo{ "include_usage": true } to include usage data in the final streaming chunk.
stopstring or arrayNoUp to 4 sequences where generation will stop.
nintegerNoNumber of completions to generate. Default: 1.
response_formatobjectNoSpecifies output format. See Structured Output.
toolsarrayNoList of tools the model may call. See Function Calling.
tool_choicestring or objectNoControls tool usage. See Function Calling.
reasoning_effortstringNoReasoning depth for o-series models: low, medium, high.
presence_penaltyfloatNoPenalizes new tokens based on presence. Range: -2.0 to 2.0.
frequency_penaltyfloatNoPenalizes repeated tokens. Range: -2.0 to 2.0.
seedintegerNoSampling seed for deterministic outputs.
userstringNoEnd-user identifier for abuse monitoring.

reasoning_effort Parameter

Controls how deeply the model reasons before responding. Only supported by reasoning models (o-series).

ValueDescription
lowLow reasoning depth, fast response
mediumMedium reasoning depth
highHigh reasoning depth, more accurate

Message Formats

System Message

Provides instructions to the model:

{ "role": "system", "content": "You are a helpful assistant." }

For o-series models (o3, o4-mini), use developer instead:

{ "role": "developer", "content": "You are a coding expert." }

User Message (Text Only)

{ "role": "user", "content": "Hello!" }

User Message (With Image)

{ "role": "user", "content": [ { "type": "text", "text": "What is in this image?" }, { "type": "image_url", "image_url": { "url": "https://example.com/photo.jpg", "detail": "auto" } } ] }

The detail parameter controls image resolution:

ValueDescription
autoModel decides (default)
lowLow resolution, fewer tokens
highHigh resolution, more tokens

Assistant Message (With Tool Calls)

{ "role": "assistant", "content": null, "tool_calls": [ { "id": "call_abc123", "type": "function", "function": { "name": "get_weather", "arguments": "{\"location\": \"Paris\"}" } } ] }

Tool Result Message

{ "role": "tool", "tool_call_id": "call_abc123", "content": "22°C and sunny in Paris" }

Response

{ "id": "chatcmpl-abc123", "object": "chat.completion", "created": 1677858242, "model": "gpt-4o", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "The response text...", "tool_calls": [ { "id": "call_abc123", "type": "function", "function": { "name": "function_name", "arguments": "{\"arg\": \"value\"}" } } ] }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 123, "completion_tokens": 456, "total_tokens": 579, "prompt_tokens_details": { "cached_tokens": 0 }, "completion_tokens_details": { "reasoning_tokens": 0 } } }

finish_reason Values

ValueDescription
stopNatural end or hit a stop sequence
lengthReached max_completion_tokens limit
tool_callsModel is calling a tool
content_filterContent was filtered

usage Fields

FieldDescription
prompt_tokensInput token count
completion_tokensOutput token count
total_tokensTotal token count
prompt_tokens_details.cached_tokensTokens served from cache
completion_tokens_details.reasoning_tokensTokens used for reasoning (o-series)

Streaming

Set stream: true to receive responses as Server-Sent Events (SSE):

from openai import OpenAI client = OpenAI( api_key="YOUR_API_KEY", base_url="https://gateway.mytokengate.com/v1" ) stream = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "Hello!"}], stream=True, stream_options={"include_usage": True} ) for chunk in stream: delta = chunk.choices[0].delta if delta.content: print(delta.content, end="")

Streaming Chunk Format

Each chunk is a JSON object with this structure:

{ "id": "chatcmpl-abc", "object": "chat.completion.chunk", "created": 1234, "model": "gpt-4o", "choices": [ { "index": 0, "delta": { "role": "assistant", "content": "token text" }, "finish_reason": null } ] }

The stream ends with:

data: [DONE]

Streaming with Reasoning Content

For models that return reasoning (DeepSeek R1, GLM-5.1, etc.), the delta object may contain reasoning_content:

for chunk in stream: delta = chunk.choices[0].delta if getattr(delta, "reasoning_content", None): # Reasoning/thinking content print(f"[Thinking] {delta.reasoning_content}") if delta.content: # Final response text print(delta.content, end="")

See Interleaved Thinking for important rules about preserving reasoning_content in multi-turn conversations.

Function Calling

Add tools to your request to enable function calling:

tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get current weather for a city", "parameters": { "type": "object", "properties": { "city": { "type": "string", "description": "City name" } }, "required": ["city"] } } } ] response = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "How is the weather in Paris?"}], tools=tools ) # Extract tool call tool_call = response.choices[0].message.tool_calls[0] function_name = tool_call.function.name function_args = json.loads(tool_call.function.arguments) # Execute the function and return results messages.append(response.choices[0].message) messages.append({ "role": "tool", "tool_call_id": tool_call.id, "content": get_weather(**function_args) }) # Continue the conversation response = client.chat.completions.create( model="gpt-4o", messages=messages, tools=tools )

tool_choice Options

ValueDescription
"auto"Model decides whether to use tools (default)
"none"Model will not use any tools
"required"Model must call at least one tool
{"type": "function", "function": {"name": "xxx"}}Model must call the specified tool

For complete examples, see Function Calling.

Error Codes

CodeDescription
400Invalid request parameters
401Invalid or missing API key
404Model not found
429Rate limit exceeded
503/504Service temporarily unavailable
Last updated on