SwissAI API
Una API de chat completions compatible con OpenAI. Crea una clave en el portal, define el token Bearer y empieza — los SDK de OpenAI existentes funcionan cambiando base_url.
Inicio rápido
Tres pasos hasta tu primera respuesta:
1. En el dashboard de desarrolladores, crea una clave en API Keys. Se muestra solo una vez — guárdala de forma segura. Formato: sk-souheng-…
2. Envía una solicitud al endpoint de chat:
curlcurl -N https://api.swiss-ai.one/api/v1/external/chat/completions \
-H "Authorization: Bearer sk-souheng-TU_CLAVE" \
-H "Content-Type: application/json" \
-d '{
"messages": [{ "role": "user", "content": "Saluda en alemán suizo." }],
"stream": true
}'
3. Recibes un stream SSE compatible con OpenAI (ver Streaming).
Autenticación
Autentica cada solicitud con tu clave API en la cabecera Authorization:
httpAuthorization: Bearer sk-souheng-TU_CLAVE
model en el cuerpo de la solicitud se ignora — puedes enviar cualquier valor (útil para SDK de OpenAI sin modificar).Las claves API se gestionan exclusivamente en el portal (crear, listar, revocar). Hasta 20 claves activas por cuenta.
URL base
| Propósito | URL |
|---|---|
| Base de la API | https://api.swiss-ai.one |
| Chat Completions | /api/v1/external/chat/completions |
SDK de OpenAI base_url | https://api.swiss-ai.one/api/v1/external |
POST/api/v1/external/chat/completions
Genera una respuesta de chat. El streaming está activado por defecto.
Cuerpo de la solicitud
| Campo | Tipo | Predet. | Descripción |
|---|---|---|---|
messages obligatorio | array | — | Lista de { "role", "content" }. Roles: system, user, assistant, tool. |
stream | boolean | true | Streaming SSE on/off. |
temperature | number | 0.7 | 0.0–2.0. |
max_tokens | integer | 4096 | 1–128000. |
tools | array | null | Definiciones de tools en formato OpenAI. |
tool_choice | string | null | p. ej. "auto". |
model se acepta pero se ignora (el modelo lo determina la clave). Los campos desconocidos se ignoran.Streaming (SSE)
Con "stream": true la API devuelve text/event-stream en formato chunk de OpenAI. El stream termina con data: [DONE].
ssedata: {"id":"chatcmpl-1a2b3c4d","object":"chat.completion.chunk","created":1750000000,"model":"swissai","choices":[{"index":0,"delta":{"content":"Hallo"},"finish_reason":null}]}
data: {"id":"chatcmpl-1a2b3c4d","object":"chat.completion.chunk","created":1750000000,"model":"swissai","choices":[{"index":0,"delta":{"content":"!"},"finish_reason":null}]}
data: {"id":"chatcmpl-1a2b3c4d","object":"chat.completion.chunk","created":1750000000,"model":"swissai","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: [DONE]
Sin streaming
Con "stream": false recibes un único objeto chat.completion:
json{
"id": "chatcmpl-1a2b3c4d",
"object": "chat.completion",
"created": 1750000000,
"model": "swissai",
"choices": [
{
"index": 0,
"message": { "role": "assistant", "content": "¡Hola! ¿En qué puedo ayudar?" },
"finish_reason": "stop"
}
]
}
Tools / function calling
Pasa los tools en formato OpenAI. Cuando el modelo llama a un tool, vuelven tool_calls (en streaming o no). Devuelve el resultado como mensaje tool con el tool_call_id correspondiente.
json{
"messages": [{ "role": "user", "content": "¿Qué tiempo hace en Zúrich?" }],
"stream": false,
"tools": [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Tiempo actual de una ciudad",
"parameters": {
"type": "object",
"properties": { "city": { "type": "string" } },
"required": ["city"]
}
}
}],
"tool_choice": "auto"
}
Python
requests (streaming)
pythonimport json, requests
resp = requests.post(
"https://api.swiss-ai.one/api/v1/external/chat/completions",
headers={"Authorization": "Bearer sk-souheng-TU_CLAVE"},
json={"messages": [{"role": "user", "content": "Hola"}], "stream": True},
stream=True,
)
for line in resp.iter_lines():
if not line:
continue
line = line.decode()
if line.startswith("data: "):
data = line[6:]
if data == "[DONE]":
break
delta = json.loads(data)["choices"][0]["delta"]
print(delta.get("content", ""), end="", flush=True)
JavaScript / Node
javascriptconst res = await fetch(
"https://api.swiss-ai.one/api/v1/external/chat/completions",
{
method: "POST",
headers: {
"Authorization": "Bearer sk-souheng-TU_CLAVE",
"Content-Type": "application/json",
},
body: JSON.stringify({
messages: [{ role: "user", content: "Hola" }],
stream: true,
}),
}
);
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
for (;;) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop();
for (const line of lines) {
if (!line.startsWith("data: ")) continue;
const data = line.slice(6);
if (data === "[DONE]") { reader.cancel(); break; }
const delta = JSON.parse(data).choices[0].delta;
if (delta.content) process.stdout.write(delta.content);
}
}
SDK de OpenAI
Los SDK de OpenAI existentes funcionan definiendo base_url y api_key. model es un campo obligatorio del SDK pero se ignora en el servidor.
pythonfrom openai import OpenAI
client = OpenAI(
api_key="sk-souheng-TU_CLAVE",
base_url="https://api.swiss-ai.one/api/v1/external",
)
stream = client.chat.completions.create(
model="swissai", # cualquiera — se ignora
messages=[{"role": "user", "content": "Hola"}],
stream=True,
)
for chunk in stream:
print(chunk.choices[0].delta.content or "", end="")
javascriptimport OpenAI from "openai";
const client = new OpenAI({
apiKey: "sk-souheng-TU_CLAVE",
baseURL: "https://api.swiss-ai.one/api/v1/external",
});
const stream = await client.chat.completions.create({
model: "swissai", // cualquiera — se ignora
messages: [{ role: "user", content: "Hola" }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}
Facturación y límites
- Las solicitudes se cobran por token contra tu saldo (wallet).
- El saldo y el uso los ves en el dashboard, donde también puedes recargar.
- Hasta 20 claves API activas por cuenta.
Códigos de error
| Estado | Significado |
|---|---|
401 | Falta la clave API, es inválida o está inactiva. |
402 | Saldo agotado — recarga en el dashboard. |
404 | Ruta / endpoint desconocido. |
429 | Límite de tasa superado — inténtalo más tarde. |
5xx | Problema temporal del servidor / upstream. |