Appearance
Inference Endpoints
The Inference Endpoints of the Swiss AI Platform provide a powerful and flexible way to access a variety of AI models through OpenAI compliant APIs. This guide will help you get started with the Inference Endpoints, including how to authenticate, make requests, and utilize different models for various tasks.
INFO
Inference Endpoints is currently in early release and under rapid development. While we will try to remain consistent, functionality is subject to change as the product matures. Documentation is updated continuously.
Quickstart
Welcome to the Inference Endpoints of the Swiss AI Platform! This guide will walk you through the basics of accessing and using our API to run inference with state-of-the-art AI models.
1. Get Access
To start using the Inference Endpoints, navigate to our product on the Digital Market Place. Then, head over to the Plans section and subscribe to the desired AI model.
New users can start with the Trial Plan to evaluate all available models before committing to a specific subscription. See the Trial Plan section below for more details.
2. Activate Your Credentials
After subscribing to the desired product plan, navigate to the Credentials tab of your subscription. Choose the production credentials and click on the Activate button.
A single subscription is capable of supporting multiple API keys. Additional API keys can be generated under the same subscription for various use cases or team members, eliminating the need to create a new subscription. The steps to create additional API keys are detailed in Section 3: Create Your API Key. This approach facilitates the management of multiple working API keys within a single subscription, offering flexibility and scalability without duplicating subscriptions.

3. Create Your API Key
Once your credentials are approved, you can generate your API key using the Get Started script provided in the Credentials section of your subscription.
To retrieve your API key:
- Navigate to your subscription in the Digital Marketplace
- Go to the Credentials tab
- Click on the Get Started button
- Copy and execute the provided script in your terminal
The script will automatically use the correct OAuth endpoint and return your access_token (API key).
Example response:
json
{
"access_token": "GyX5BFydx2kzxPqve7Bh1uVfTfhi",
"scope": "",
"token_type": "bearer",
"expires_in": "2591999"
}
The access_token is your API key, which you can use to authenticate your requests to the Inference Endpoints.
4. Make Your First Request
Once you have your API key, you can start making requests. Our APIs are OpenAI-compatible, so you can query our models as you would with OpenAI.
The production URL for this API is available in the corresponding plan for this model in the Digital Marketplace. To retrieve the URL:
- Navigate to the Digital Marketplace.
- Go to the Documentation section.
- Select the plan associated with the desired model.
- Locate the production URL provided in the plan details.
- Set up the environment variable
BASE_URLto the production URL retrieved.

Here's how to call a chat model using curl or Python:
bash
curl -X POST $BASE_URL/v1/chat/completions \
-H "Authorization: Bearer <your-api-key>" \
-H "Content-Type: application/json" \
-d '{
"model": "google/gemma-4-31b-it",
"messages": [
{"role": "user", "content": "Hello, how are you?"}
]
}'python
import os
import openai
client = openai.OpenAI(
api_key=os.getenv("GEMMA_4_31B_API_KEY"),
base_url=os.getenv("BASE_URL") + "/v1"
)
stream = client.chat.completions.create(
model="google/gemma-4-31b-it",
messages=[
{"role": "system", "content": "You are a travel agent. Be descriptive and helpful"},
{"role": "user", "content": "What are the best places to visit in Switzerland?"}
],
stream=True
)
for chunk in stream:
print(chunk.choices[0].delta.content or "", end="", flush=True)🎉 Concratulations! You have successfully made your first request to the Swiss AI Platform's Inference Endpoints!
Available APIs
The Swiss AI Platform Inference Endpoints support multiple API standards, allowing you to choose the interface that best fits your workflow:
| API | Endpoint | Compatibility | Best For |
|---|---|---|---|
| Chat Completions | POST /v1/chat/completions | OpenAI | Standard chat workflows, legacy OpenAI integrations |
| Responses API | POST /v1/responses | OpenAI | Advanced reasoning, tool integration, flexible input formats |
| Messages API | POST /v1/messages | Anthropic | Anthropic Claude migrations, extended thinking, JSON schema validation |
| Document Conversion | POST /v1/convert/file or POST /v1/convert/source | Docling | Document conversion, OCR, and structured content extraction |
INFO
The conversational APIs are stateless - conversation history must be provided with each request. No conversation data is stored between requests, ensuring complete privacy and GDPR compliance.
For model-specific API support, see API Support by Model.
For GLM-5.3 Flash, available in Preview since 7 October 2026, see the model documentation and examples. It supports text and image input through Chat Completions, Responses, and Messages. It replaces GLM-5.2, which is deprecated from 7 October 2026 and will be removed on 7 November 2026; see the migration guidance.
For Llama Nemotron Rerank 1B v2, available in Preview since 9 October 2026, see the model documentation and examples. It reranks documents by relevance to a query through the Rerank API (POST /v1/rerank), compatible with the Jina AI and Cohere rerank API interfaces.
For synchronous and asynchronous document conversion examples, supported formats, and processing options, see the Docling API documentation.
Trial Plan
The Trial Plan is designed to enable new users to evaluate the Inference Endpoints offering without financial commitment. It helps you:
- Explore and benchmark different models (quality, latency, throughput)
- Validate integration and API compatibility
- Make an informed decision about selecting the most suitable model and subscription plan
Trial Plan Overview
| Feature | Value |
|---|---|
| Access Scope | All available models (Preview & GA) |
| Duration | 30 days from first usage |
| Chat Budget | 10M input tokens + 2.5M output tokens |
| Embeddings Budget | 5M input tokens |
| Audio Budget | 60 input minutes |
| Speech Budget | 50K input tokens |
| Rate Limit | 50K input tokens/min, 12.5K output tokens/min |
| Usage Warning | At 80% of budget |
| Cost | Free, no monthly charges |
Available Models
The Trial Plan provides access to all models available on the Swiss AI Platform. For a complete list of available models, see the Available Models overview.
Getting Started
To start your trial, follow the steps in the Quickstart section above and subscribe to the Trial Plan in the Digital Marketplace.
Troubleshooting
GATEWAY_TIMEOUT (504) Error
Requests to Inference Endpoints return a GATEWAY_TIMEOUT (504) error:
json
{
"status": "504",
"code": "GATEWAY_TIMEOUT",
"message": "The server was acting as a gateway or proxy and did not receive a timely response from the upstream server."
}Cause
Request exceeds the configured timeout limit for your Digital Marketplace subscription (default: 1 minute, max: 2 minutes).
Resolution
Use streaming mode for API calls to avoid timeouts. Streaming delivers responses in chunks as they're generated.
Example:
python
response = client.chat.completions.create(
model="google/gemma-4-31b-it",
messages=[{"role": "user", "content": "Your prompt here"}],
stream=True # Enable streaming
)
for chunk in response:
print(chunk.choices[0].delta.content or "", end="", flush=True)Best Practice
Streaming is recommended for all production workloads to avoid timeouts and improve user experience with immediate response feedback.
Chat Completions API Examples
The following examples demonstrate the Chat Completions API (POST /v1/chat/completions). For Responses API and Messages API examples, see the sections below.
The Inference Endpoints provide access to a variety of models, including:
- Chat models (e.g., Gemma 4 31B, GLM-5.3 Flash)
- Multimodal models (e.g., Gemma 4 31B)
- Reasoning models (e.g., Llama 3.3 Nemotron super 49b)
- Embedding models (e.g., Llama 3 2 nv embedqa 1b v2)
- Audio models (e.g., Whisper)
- Guardrail models (e.g., Llama 3.1 Nemoguard 8b Content Safety)
- Document processing (Docling)
Below is a non-exhaustive list of examples of how to use the models:
Chat Models
Streaming
python
import openai
client = openai.OpenAI(
api_key=os.getenv("GEMMA_4_31B_API_KEY"),
base_url=os.getenv("BASE_URL") + "/v1",
)
response = client.chat.completions.create(
model="google/gemma-4-31b-it",
messages=[
{"role": "system", "content": "You are a travel agent. Be descriptive and helpful"},
{"role": "user", "content": "What are the best places to visit in Switzerland?"}
],
stream=True
)
for chunk in response:
print(chunk.choices[0].delta.content or "", end="", flush=True)Tool Use
You can connect our chat models to external tools using tool calling. By providing a list of available tools, the model can choose to output arguments for the relevant tool, which you can execute to augment the prompt with relevant external information.
Tool calling is controlled using the tools and tool_choice paramenters.
This example shows how to use a tool with automatic tool choice:
python
tools = [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "Get the current weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and country, e.g. San Francisco, USA"
},
"unit": {
"type": "string",
"enum": [
"celsius",
"fahrenheit"
]
}
}
}
}
}
]
messages = [
{"role": "system", "content": "You are a helpful assistant that can access external tools. The responses from these tool calls will be appended to this dialogue. Please provide responses based on the information from these tool calls."},
{"role": "user", "content": "What is the current temperature of Bern?"}
]
response = self.client.chat.completions.create(
model=self.model,
messages=messages,
tools=tools,
tool_choice="auto",
)
print(json.dumps(response.choices[0].message.model_dump()['tool_calls'], indent=2))INFO
Please note, that parallel tool calling via the parallel_tool_calls parameter is currently not supported with the Llama 3.3 70B model.
Reasoning
Reasoning models like Llama 3.3 Nemotron super 49b are LLMs trained with reinforcement learning to perform reasoning. Reasoning models think before they answer, producing a long internal chain of thought before responding to the user. Reasoning models excel in complex problem solving, coding, scientific reasoning, and multi-step planning for agentic workflows.
The reasoning mode (ON/OFF) of Llama 3.3 Nemotron super 49b is controlled via the system prompt, which must be set as shown in the example below
python
import openai
client = openai.OpenAI(
api_key=os.getenv("API_KEY"),
base_url=os.getenv("BASE_URL") + "/v1",
)
response = client.chat.completions.create(
model="nvidia/llama-3.3-nemotron-super-49b-v1",
messages=[
{"role": "system", "content": "detailed thinking on"},
{"role": "user", "content": "If a+|a|=0, try to prove that a<=0."}
],
temperature=0.6,
top_p=0.95,
stream=True
)
for chunk in response:
print(chunk.choices[0].delta.content or "", end="", flush=True)Note
- We recommend setting temperature to 0.6, and Top P to 0.95 for Reasoning ON mode.
- The model will include
<think></think>if no reasoning was necessary in Reasoning ON model, this is expected behaviour.
Multimodal Models
In the multimodal domain, we currently offer the Gemma 4 31B model, which is a multimodal reasoning model with advanced text and image understanding (text+images in / text out). More information can be found in the Gemma 4 31B model card.
Image Input
You can provide provide images as input to generation requests by providing an image as a Base64-encoded data URL.
python
import base64
from openai import OpenAI
client = openai.OpenAI(
api_key=os.getenv("GEMMA_4_31B_API_KEY"),
base_url=os.getenv("BASE_URL") + "/v1",
)
# Function to encode the image
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
# Path to your image
image_path = "path_to_your_image.jpg"
# Getting the Base64 string
picture_base64 = encode_image(image_path)
response = client.chat.completions.create(
model="google/gemma-4-31b-it",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "What do you see in this image?"},
{"type": "image_url", "image_url": {
"url": f"data:image/jpeg;base64,{picture_base64}"}
}
]
}
],
)
print(response.choices[0].message.content)Check out our suggested best practices for using multimodal models to get the most out of your multimodal experiences.
Guardrail Models
To make sure that AI-generated content is safe and appropriate, Swisscom provides access to guardrail models.
Guardrail models are specialized content safety models designed to detect and filter harmful content. Currently, we offer the Llama 3.1 Nemoguard 8b Content Safety model, which can analyze text for safety concerns and provide detailed reasoning for its decisions. More information can be found in the Llama 3.1 Nemoguard 8b model card.
Content Safety Evaluation (Non-streaming)
python
import openai
client = openai.OpenAI(
api_key=os.getenv("NEMOGUARD_API_KEY"),
base_url=os.getenv("BASE_URL") + "/v1",
)
response = client.chat.completions.create(
model="nvidia/llama-3.1-nemoguard-8b-content-safety",
messages=[
{
"role": "system",
"content": "You are a content safety evaluator. Analyze content and respond with SAFE or UNSAFE with reasoning."
},
{
"role": "user",
"content": "Please evaluate this text for safety: Hello, how are you today?"
}
],
temperature=0.1,
max_completion_tokens=100,
stream=False
)
print(response.choices[0].message.content)Content Safety Evaluation (Streaming)
python
import openai
client = openai.OpenAI(
api_key=os.getenv("NEMOGUARD_API_KEY"),
base_url=os.getenv("BASE_URL") + "/v1",
)
response = client.chat.completions.create(
model="nvidia/llama-3.1-nemoguard-8b-content-safety",
messages=[
{
"role": "system",
"content": "You are a content safety evaluator. Analyze content and respond with SAFE or UNSAFE with reasoning."
},
{
"role": "user",
"content": "This is a normal message."
}
],
temperature=0.1,
max_completion_tokens=50,
stream=True
)
for chunk in response:
print(chunk.choices[0].delta.content or "", end="", flush=True)INFO
Guardrail models work best with low temperature settings (0.1-0.3) to ensure consistent and reliable safety evaluations.
Check out our Guardrail Best Practices for more information on how to use guardrail models effectively.
Embedding Models
The embedding models are used to convert text into vector representations, which can be used for various tasks such as semantic search, clustering, and classification. Currently, we offer the Llama 3 2 nv embedqa 1b v2 model, which is a multilingual, text question-answering and retrieval embedding model with long context support (up to 8192 tokens). More information can be found in the Llama 3 2 nv embedqa 1b v2 model card.
Create text embedding
python
from openai import OpenAI
client = openai.OpenAI(
api_key=os.getenv("LLAMA_3_2_NVEMBED_API_KEY"),
base_url=os.getenv("BASE_URL") + "/v1",
)
response = client.embeddings.create(
input=["What is the capital of France?"],
model="nvidia/llama-3.2-nv-embedqa-1b-v2",
encoding_format="float"
)
print(response.data[0].embedding)Audio Models
Currently, we offer the faster-whisper-large-v3 model, which is a large model for ASR (automatic speech recognition) that can be used to transcribe audio files. More information can be found in the faster-whisper-large-v3 model card.
Create transcription
python
import os
import openai
client = openai.OpenAI(
api_key=os.getenv("WHISPER_API_KEY"),
base_url=os.getenv("BASE_URL") + "/v1",
)
audio_file = open("Your-Audio-File.mp3", "rb")
transcript = client.audio.transcriptions.create(
model="Systran/faster-whisper-large-v3",
file=audio_file,
)
print(transcript.text)Text-to-Speech Synthesis
The Swiss AI Platform provides text-to-speech synthesis capabilities through the Magpie TTS Multilingual model. This model supports both offline synthesis (complete WAV file) and streaming synthesis (real-time RAW PCM audio).
Offline Synthesis
python
import requests
url = '$BASE_URL/v1/audio/synthesize'
headers = {
'Authorization': 'Bearer $YOUR_API_KEY',
}
data = {
'text': 'Hello, this is a TTS test',
'model': 'magpie-tts-multilingual',
'language': 'en-US',
'voice': 'Magpie-Multilingual.EN-US.Aria',
}
response = requests.post(url, headers=headers, data=data)
response.raise_for_status()
with open('output.wav', 'wb') as f:
f.write(response.content)
print("Audio saved to output.wav")Streaming Synthesis
python
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
import pyaudio
# Initialize PyAudio
p = pyaudio.PyAudio()
stream = p.open(
format=pyaudio.paInt16,
channels=1,
rate=22050,
output=True
)
# Configuration
url = '$BASE_URL/v1/audio/synthesize_online'
headers = {
'Authorization': 'Bearer $YOUR_API_KEY',
}
data = {
'text': 'Hello, this is streaming TTS!',
'model': 'magpie-tts-multilingual',
'language': 'en-US',
'voice': 'Magpie-Multilingual.EN-US.Aria',
}
# Create multipart encoder
multipart_data = MultipartEncoder(fields=data)
headers['Content-Type'] = multipart_data.content_type
# Stream and play
response = requests.post(
url,
headers=headers,
data=multipart_data,
stream=True
)
response.raise_for_status()
print("Streaming TTS audio...")
for chunk in response.iter_content(chunk_size=4096):
if chunk:
stream.write(chunk) # Plays immediately!
# Cleanup
stream.stop_stream()
stream.close()
p.terminate()For more detailed information, see the Magpie TTS Multilingual model documentation.
Responses API (OpenAI-Compatible)
The Responses API provides an OpenAI-compatible conversational interface with advanced features for reasoning, tool integration, and flexible input formats.
The Qwen3.8 examples below use a model that thinks by default. Output limits must allow for reasoning as well as the final answer; increase the illustrative token budgets for complex tasks. See Qwen3.8 thinking controls for model-specific behavior. For Python Responses API calls, use response.output_text to read the final text without assuming the first output item is a message.
Key Features
- Stateless conversations - Each request is independent; no conversation state is stored
- Advanced reasoning support - Native support for reasoning tokens and extended thinking
- Tool integration - Built-in function calling with structured tool definitions
- Flexible input formats - Accept both simple text strings and structured conversation arrays
- Streaming support - Real-time SSE streaming for progressive response delivery
- Enhanced token tracking - Detailed breakdown including cached tokens, reasoning tokens, tool output tokens
Privacy & Model Stability
Response persistence is NOT supported. The previous_response_id parameter is not available. Each request must include the full conversation context. This ensures:
- No customer data is stored between requests (GDPR compliance, data sovereignty)
- Prevents model OOM (Out of Memory) crashes - Long-running conversations with accumulated state can exhaust model memory, causing crashes. Stateless architecture ensures stable, predictable performance.
Request Parameters
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
model | string | ✅ | - | Model ID (e.g., qwen/qwen3.8-27b) |
input | string/array | ✅ | - | Input text or structured messages array |
instructions | string | ❌ | - | System prompt/instructions |
max_output_tokens | integer | ❌ | Model default | Maximum tokens to generate |
temperature | number | ❌ | 1.0 | Sampling temperature (0.0-2.0) |
top_p | number | ❌ | 1.0 | Nucleus sampling parameter |
tools | array | ❌ | - | List of tool definitions |
tool_choice | string/object | ❌ | auto | auto, none, required, or {type: "function", name: "..."} |
stream | boolean | ❌ | false | Enable SSE streaming |
stream_options | object | ❌ | - | {include_usage: true} for token usage in streaming |
text.format | object | ❌ | - | JSON schema for structured output |
Examples
1. Basic Text Generation
bash
curl -X POST $BASE_URL/v1/responses \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen/qwen3.8-27b",
"input": "What is the capital of Switzerland?",
"max_output_tokens": 5000,
"temperature": 0.7
}'python
from openai import OpenAI
import os
client = OpenAI(
api_key=os.getenv("YOUR_API_KEY"),
base_url=os.getenv("BASE_URL") + "/v1"
)
response = client.responses.create(
model="qwen/qwen3.8-27b",
input="What is the capital of Switzerland?",
max_output_tokens=5000,
temperature=0.7
)
print(response.output_text)2. Streaming
bash
curl -X POST $BASE_URL/v1/responses \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen/qwen3.8-27b",
"input": "Explain quantum computing in detail",
"stream": true,
"stream_options": {"include_usage": true},
"max_output_tokens": 600
}'python
from openai import OpenAI
import os
client = OpenAI(
api_key=os.getenv("YOUR_API_KEY"),
base_url=os.getenv("BASE_URL") + "/v1"
)
response = client.responses.create(
model="qwen/qwen3.8-27b",
input="Explain quantum computing in detail",
stream=True,
stream_options={"include_usage": True},
max_output_tokens=600
)
for chunk in response:
if chunk.output and chunk.output[0].delta:
print(chunk.output[0].delta, end="", flush=True)3. Multi-turn Conversation
bash
curl -X POST $BASE_URL/v1/responses \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen/qwen3.8-27b",
"input": [
{"type": "message", "role": "user", "content": [{"type": "input_text", "text": "What is 2+2?"}]},
{"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "4"}]},
{"type": "message", "role": "user", "content": [{"type": "input_text", "text": "Now multiply that by 3"}]}
],
"instructions": "You are a helpful math tutor.",
"max_output_tokens": 600,
"temperature": 0.7
}'python
from openai import OpenAI
import os
client = OpenAI(
api_key=os.getenv("YOUR_API_KEY"),
base_url=os.getenv("BASE_URL") + "/v1"
)
response = client.responses.create(
model="qwen/qwen3.8-27b",
input=[
{"type": "message", "role": "user", "content": [{"type": "input_text", "text": "What is 2+2?"}]},
{"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "4"}]},
{"type": "message", "role": "user", "content": [{"type": "input_text", "text": "Now multiply that by 3"}]}
],
instructions="You are a helpful math tutor.",
max_output_tokens=600,
temperature=0.7
)
print(response.output_text)4. System Instructions
bash
curl -X POST $BASE_URL/v1/responses \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen/qwen3.8-27b",
"input": "Explain derivatives in short and simple terms.",
"instructions": "You are a helpful math tutor.",
"max_output_tokens": 2000,
"temperature": 0.7
}'python
from openai import OpenAI
import os
client = OpenAI(
api_key=os.getenv("YOUR_API_KEY"),
base_url=os.getenv("BASE_URL") + "/v1"
)
response = client.responses.create(
model="qwen/qwen3.8-27b",
input="Explain derivatives in short and simple terms.",
instructions="You are a helpful math tutor.",
max_output_tokens=2000,
temperature=0.7
)
print(response.output_text)5. Tool Calling
bash
curl -X POST $BASE_URL/v1/responses \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen/qwen3.8-27b",
"input": "What is the weather in Zurich?",
"tools": [{
"type": "function",
"name": "get_weather",
"description": "Get current weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name"}
},
"required": ["location"]
}
}],
"tool_choice": "auto",
"max_output_tokens": 600,
"temperature": 0.7
}'python
from openai import OpenAI
import os
client = OpenAI(
api_key=os.getenv("YOUR_API_KEY"),
base_url=os.getenv("BASE_URL") + "/v1"
)
tools = [{
"type": "function",
"name": "get_weather",
"description": "Get current weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name"}
},
"required": ["location"]
}
}]
response = client.responses.create(
model="qwen/qwen3.8-27b",
input="What is the weather in Zurich?",
tools=tools,
tool_choice="auto",
max_output_tokens=600,
temperature=0.7
)
print(response.output[0])6. Tool Choice Control
bash
curl -X POST $BASE_URL/v1/responses \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen/qwen3.8-27b",
"input": "What is 5+5?",
"tools": [{
"type": "function",
"name": "calculator",
"description": "Perform mathematical calculations",
"parameters": {
"type": "object",
"properties": {
"expression": {"type": "string", "description": "Math expression"}
},
"required": ["expression"]
}
}],
"tool_choice": "none",
"max_output_tokens": 600
}'python
from openai import OpenAI
import os
client = OpenAI(
api_key=os.getenv("YOUR_API_KEY"),
base_url=os.getenv("BASE_URL") + "/v1"
)
response = client.responses.create(
model="qwen/qwen3.8-27b",
input="What is 5+5?",
tools=[{
"type": "function",
"name": "calculator",
"description": "Perform mathematical calculations",
"parameters": {
"type": "object",
"properties": {
"expression": {"type": "string", "description": "Math expression"}
},
"required": ["expression"]
}
}],
tool_choice="none",
max_output_tokens=600
)
print(response.output_text)8. Output Length Control
bash
curl -X POST $BASE_URL/v1/responses \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen/qwen3.8-27b",
"input": "Write a detailed essay about machine learning",
"max_output_tokens": 600
}'python
from openai import OpenAI
import os
client = OpenAI(
api_key=os.getenv("YOUR_API_KEY"),
base_url=os.getenv("BASE_URL") + "/v1"
)
response = client.responses.create(
model="qwen/qwen3.8-27b",
input="Write a detailed essay about machine learning",
max_output_tokens=600
)
print(response.output_text)9. Vision (Multimodal)
bash
curl -X POST $BASE_URL/v1/responses \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen/qwen3.8-27b",
"input": [{
"type": "message",
"role": "user",
"content": [
{"type": "input_image", "image_url": "data:image/jpeg;base64,iVBORw0KG...", "detail": "auto"},
{"type": "input_text", "text": "What color is this?"}
]
}],
"max_output_tokens": 600
}'python
import base64
from openai import OpenAI
import os
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
client = OpenAI(
api_key=os.getenv("YOUR_API_KEY"),
base_url=os.getenv("BASE_URL") + "/v1"
)
image_base64 = encode_image("path_to_image.jpg")
response = client.responses.create(
model="qwen/qwen3.8-27b",
input=[{
"type": "message",
"role": "user",
"content": [
{"type": "input_image", "image_url": f"data:image/jpeg;base64,{image_base64}", "detail": "auto"},
{"type": "input_text", "text": "What color is this?"}
]
}],
max_output_tokens=600
)
print(response.output_text)10. Structured Output (JSON Schema)
bash
curl -X POST $BASE_URL/v1/responses \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen/qwen3.8-27b",
"input": "Extract: John is 25 years old, lives in Zurich",
"text": {
"format": {
"type": "json_schema",
"name": "person",
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"city": {"type": "string"}
},
"required": ["name", "age", "city"],
"strict": true
}
}
},
"max_output_tokens": 600
}'python
from openai import OpenAI
import os
client = OpenAI(
api_key=os.getenv("YOUR_API_KEY"),
base_url=os.getenv("BASE_URL") + "/v1"
)
response = client.responses.create(
model="qwen/qwen3.8-27b",
input="Extract: John is 25 years old, lives in Zurich",
text={
"format": {
"type": "json_schema",
"name": "person",
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"city": {"type": "string"}
},
"required": ["name", "age", "city"],
"strict": True
}
}
},
max_output_tokens=600
)
print(response.output_text)Response Format
json
{
"id": "resp_abc123",
"object": "response",
"created_at": 1743765837,
"model": "qwen/qwen3.8-27b",
"status": "completed",
"output": [
{
"type": "message",
"role": "assistant",
"content": [
{
"type": "output_text",
"text": "The capital of Switzerland is Bern."
}
]
}
],
"usage": {
"input_tokens": 17,
"output_tokens": 9,
"total_tokens": 26,
"cached_tokens": 0,
"reasoning_tokens": 0
}
}
Streaming Events
When stream: true is enabled, the API returns Server-Sent Events (SSE):
event: response.created
data: {"type":"response.created","response":{"id":"resp_123","status":"processing"}}
event: response.output_text.delta
data: {"type":"response.output_text.delta","delta":"Bern"}
event: response.completed
data: {"type":"response.completed","response":{"usage":{"input_tokens":17,"output_tokens":9}}}Messages API (Anthropic-Compatible)
The Messages API provides an Anthropic Claude-compatible conversational interface with advanced features for extended thinking, sophisticated tool calling, and multi-modal content blocks.
Qwen3.8 thinks by default. Allow enough output tokens for reasoning and the final answer, and handle thinking blocks separately from text blocks. See the model guidance before migrating an existing Qwen3.6 client.
Key Features
- Anthropic Claude API compatibility - Drop-in replacement for Anthropic's Messages API
- Extended thinking support - Native chain-of-thought and reasoning block support
- Advanced tool calling - Sophisticated tool definitions with JSON schema validation
- Multi-modal content - Support for text, images (URL and base64), and structured content blocks
- Granular streaming events - Content block-level deltas for fine-grained control
- Enhanced token tracking - Cache creation/read tokens, per-turn accounting
Privacy & Model Stability
Stateful multi-turn conversations are NOT supported. All conversation history must be provided with each request. No messages, responses, or conversation state are stored between requests. This ensures:
- Complete data privacy and compliance with data protection requirements (GDPR, data sovereignty)
- Prevents model OOM (Out of Memory) crashes - Long-running conversations with accumulated state can exhaust model memory, causing crashes. Stateless architecture ensures stable, predictable performance.
Request Parameters
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
model | string | ✅ | - | Model ID (e.g., qwen/qwen3.8-27b) |
messages | array | ✅ | - | Array of message objects with content blocks |
system | string | ❌ | - | System prompt |
max_tokens | integer | ✅ | - | Maximum tokens to generate |
temperature | number | ❌ | 1.0 | Sampling temperature (0.0-2.0) |
top_p | number | ❌ | 1.0 | Nucleus sampling parameter |
tools | array | ❌ | - | List of tool definitions with input_schema |
tool_choice | object | ❌ | {type: "auto"} | {type: "auto"}, {type: "any"}, {type: "tool", name: "..."}, {type: "none"} |
stream | boolean | ❌ | false | Enable SSE streaming |
output_config.format | object | ❌ | - | JSON schema for structured output |
stop_sequences | array | ❌ | - | Custom stop sequences |
Content Block Types
| Type | Description |
|---|---|
text | Plain text content |
image | Image content (URL or base64 encoded) |
tool_use | Function/tool invocations with structured inputs |
tool_result | Tool execution results |
thinking | Extended reasoning/chain-of-thought (with signature verification) |
redacted_thinking | Safety-filtered reasoning blocks |
Examples
1. Basic Text Generation
bash
curl -X POST $BASE_URL/v1/messages \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen/qwen3.8-27b",
"max_tokens": 5000,
"temperature": 0.7,
"messages": [
{"role": "user", "content": "What is the capital of Switzerland?"}
]
}'python
import os
import requests
response = requests.post(
f"{os.getenv('BASE_URL')}/v1/messages",
headers={
"Authorization": f"Bearer {os.getenv('YOUR_API_KEY')}",
"Content-Type": "application/json"
},
json={
"model": "qwen/qwen3.8-27b",
"max_tokens": 5000,
"temperature": 0.7,
"messages": [
{"role": "user", "content": "What is the capital of Switzerland?"}
]
}
)
result = response.json()
print(result["content"][0]["text"])2. Streaming
bash
curl -X POST $BASE_URL/v1/messages \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen/qwen3.8-27b",
"max_tokens": 600,
"stream": true,
"messages": [
{"role": "user", "content": "Explain quantum computing in detail"}
]
}'python
import os
import requests
import json
response = requests.post(
f"{os.getenv('BASE_URL')}/v1/messages",
headers={
"Authorization": f"Bearer {os.getenv('YOUR_API_KEY')}",
"Content-Type": "application/json"
},
json={
"model": "qwen/qwen3.8-27b",
"max_tokens": 600,
"stream": True,
"messages": [
{"role": "user", "content": "Explain quantum computing in detail"}
]
},
stream=True
)
for line in response.iter_lines():
if line:
line = line.decode('utf-8')
if line.startswith('data: '):
data = json.loads(line[6:])
if data.get('type') == 'content_block_delta':
print(data['delta']['text'], end='', flush=True)3. Multi-turn Conversation
bash
curl -X POST $BASE_URL/v1/messages \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen/qwen3.8-27b",
"max_tokens": 600,
"temperature": 0.7,
"messages": [
{"role": "user", "content": "What is 2+2?"},
{"role": "assistant", "content": "4"},
{"role": "user", "content": "Now multiply that by 3"}
]
}'python
import os
import requests
response = requests.post(
f"{os.getenv('BASE_URL')}/v1/messages",
headers={
"Authorization": f"Bearer {os.getenv('YOUR_API_KEY')}",
"Content-Type": "application/json"
},
json={
"model": "qwen/qwen3.8-27b",
"max_tokens": 600,
"temperature": 0.7,
"messages": [
{"role": "user", "content": "What is 2+2?"},
{"role": "assistant", "content": "4"},
{"role": "user", "content": "Now multiply that by 3"}
]
}
)
result = response.json()
print(result["content"][0]["text"])4. System Instructions
bash
curl -X POST $BASE_URL/v1/messages \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen/qwen3.8-27b",
"system": "You are a helpful math tutor.",
"max_tokens": 2000,
"temperature": 0.7,
"messages": [
{"role": "user", "content": "Explain derivatives in short and simple terms."}
]
}'python
import os
import requests
response = requests.post(
f"{os.getenv('BASE_URL')}/v1/messages",
headers={
"Authorization": f"Bearer {os.getenv('YOUR_API_KEY')}",
"Content-Type": "application/json"
},
json={
"model": "qwen/qwen3.8-27b",
"system": "You are a helpful math tutor.",
"max_tokens": 2000,
"temperature": 0.7,
"messages": [
{"role": "user", "content": "Explain derivatives in short and simple terms."}
]
}
)
result = response.json()
print(result["content"][0]["text"])6. Tool Choice Control
bash
curl -X POST $BASE_URL/v1/messages \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen/qwen3.8-27b",
"max_tokens": 600,
"tool_choice": {"type": "none"},
"messages": [
{"role": "user", "content": "What is 5+5?"}
],
"tools": [{
"name": "calculator",
"description": "Perform mathematical calculations",
"input_schema": {
"type": "object",
"properties": {
"expression": {"type": "string", "description": "Math expression"}
},
"required": ["expression"]
}
}]
}'python
import os
import requests
response = requests.post(
f"{os.getenv('BASE_URL')}/v1/messages",
headers={
"Authorization": f"Bearer {os.getenv('YOUR_API_KEY')}",
"Content-Type": "application/json"
},
json={
"model": "qwen/qwen3.8-27b",
"max_tokens": 600,
"tool_choice": {"type": "none"},
"messages": [
{"role": "user", "content": "What is 5+5?"}
],
"tools": [{
"name": "calculator",
"description": "Perform mathematical calculations",
"input_schema": {
"type": "object",
"properties": {
"expression": {"type": "string", "description": "Math expression"}
},
"required": ["expression"]
}
}]
}
)
result = response.json()
print(result["content"][0]["text"])7. Temperature and Sampling
bash
curl -X POST $BASE_URL/v1/messages \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen/qwen3.8-27b",
"max_tokens": 600,
"temperature": 0.9,
"top_p": 0.95,
"messages": [
{"role": "user", "content": "Write a creative haiku about AI"}
]
}'python
import os
import requests
response = requests.post(
f"{os.getenv('BASE_URL')}/v1/messages",
headers={
"Authorization": f"Bearer {os.getenv('YOUR_API_KEY')}",
"Content-Type": "application/json"
},
json={
"model": "qwen/qwen3.8-27b",
"max_tokens": 600,
"temperature": 0.9,
"top_p": 0.95,
"messages": [
{"role": "user", "content": "Write a creative haiku about AI"}
]
}
)
result = response.json()
print(result["content"][0]["text"])8. Output Length Control
bash
curl -X POST $BASE_URL/v1/messages \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen/qwen3.8-27b",
"max_tokens": 600,
"messages": [
{"role": "user", "content": "Write a detailed essay about machine learning"}
]
}'python
import os
import requests
response = requests.post(
f"{os.getenv('BASE_URL')}/v1/messages",
headers={
"Authorization": f"Bearer {os.getenv('YOUR_API_KEY')}",
"Content-Type": "application/json"
},
json={
"model": "qwen/qwen3.8-27b",
"max_tokens": 600,
"messages": [
{"role": "user", "content": "Write a detailed essay about machine learning"}
]
}
)
result = response.json()
print(result["content"][0]["text"])9. Vision (Multimodal)
bash
curl -X POST $BASE_URL/v1/messages \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen/qwen3.8-27b",
"max_tokens": 600,
"messages": [
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/jpeg",
"data": "iVBORw0KG..."
}
},
{"type": "text", "text": "What color is this?"}
]
}
]
}'python
import base64
import os
import requests
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")
image_base64 = encode_image("path_to_image.jpg")
response = requests.post(
f"{os.getenv('BASE_URL')}/v1/messages",
headers={
"Authorization": f"Bearer {os.getenv('YOUR_API_KEY')}",
"Content-Type": "application/json"
},
json={
"model": "qwen/qwen3.8-27b",
"max_tokens": 600,
"messages": [
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/jpeg",
"data": image_base64
}
},
{"type": "text", "text": "What color is this?"}
]
}
]
}
)
result = response.json()
print(result["content"][0]["text"])10. Structured Output (JSON Schema)
bash
curl -X POST $BASE_URL/v1/messages \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen/qwen3.8-27b",
"max_tokens": 600,
"output_config": {
"format": {
"type": "json_schema",
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"city": {"type": "string"}
},
"required": ["name", "age", "city"]
}
}
},
"messages": [
{"role": "user", "content": "Extract: John is 25 years old, lives in Zurich"}
]
}'python
import os
import requests
response = requests.post(
f"{os.getenv('BASE_URL')}/v1/messages",
headers={
"Authorization": f"Bearer {os.getenv('YOUR_API_KEY')}",
"Content-Type": "application/json"
},
json={
"model": "qwen/qwen3.8-27b",
"max_tokens": 600,
"output_config": {
"format": {
"type": "json_schema",
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"city": {"type": "string"}
},
"required": ["name", "age", "city"]
}
}
},
"messages": [
{"role": "user", "content": "Extract: John is 25 years old, lives in Zurich"}
]
}
)
result = response.json()
print(result["content"][0]["text"])Response Format
json
{
"id": "msg_abc123",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "The capital of Switzerland is Bern."
}
],
"model": "qwen/qwen3.8-27b",
"stop_reason": "end_turn",
"usage": {
"input_tokens": 15,
"output_tokens": 8,
"cache_creation_input_tokens": 0,
"cache_read_input_tokens": 0
}
}Streaming Events
When stream: true is enabled, the API returns Server-Sent Events (SSE):
event: message_start
data: {"type":"message_start","message":{"id":"msg_123","type":"message","role":"assistant","content":[],"model":"qwen/qwen3.8-27b"}}
event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}
event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Bern"}}
event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":8}}
event: message_stop
data: {"type":"message_stop"}