Текстовая генерация
Anthropic Messages API
Anthropic-совместимый endpoint для сообщений и streaming
POST
/
v1
/
messages
Создать сообщение Anthropic Messages API
curl --request POST \
--url https://speshu.ai/api/v1/messages \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--header 'anthropic-version: <anthropic-version>' \
--data '
{
"model": "anthropic/claude-sonnet-4.6",
"messages": [
{
"role": "user",
"content": "Привет!"
}
],
"max_tokens": 1024,
"stream": false,
"temperature": 1,
"top_p": 1,
"top_k": 40,
"stop_sequences": [
"<string>"
],
"system": "You are a helpful assistant.",
"thinking": {
"type": "adaptive"
},
"tools": [
{}
],
"tool_choice": {}
}
'import requests
url = "https://speshu.ai/api/v1/messages"
payload = {
"model": "anthropic/claude-sonnet-4.6",
"messages": [
{
"role": "user",
"content": "Привет!"
}
],
"max_tokens": 1024,
"stream": False,
"temperature": 1,
"top_p": 1,
"top_k": 40,
"stop_sequences": ["<string>"],
"system": "You are a helpful assistant.",
"thinking": { "type": "adaptive" },
"tools": [{}],
"tool_choice": {}
}
headers = {
"anthropic-version": "<anthropic-version>",
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'POST',
headers: {
'anthropic-version': '<anthropic-version>',
Authorization: 'Bearer <token>',
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'anthropic/claude-sonnet-4.6',
messages: [{role: 'user', content: 'Привет!'}],
max_tokens: 1024,
stream: false,
temperature: 1,
top_p: 1,
top_k: 40,
stop_sequences: ['<string>'],
system: 'You are a helpful assistant.',
thinking: {type: 'adaptive'},
tools: [{}],
tool_choice: {}
})
};
fetch('https://speshu.ai/api/v1/messages', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://speshu.ai/api/v1/messages",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'model' => 'anthropic/claude-sonnet-4.6',
'messages' => [
[
'role' => 'user',
'content' => 'Привет!'
]
],
'max_tokens' => 1024,
'stream' => false,
'temperature' => 1,
'top_p' => 1,
'top_k' => 40,
'stop_sequences' => [
'<string>'
],
'system' => 'You are a helpful assistant.',
'thinking' => [
'type' => 'adaptive'
],
'tools' => [
[
]
],
'tool_choice' => [
]
]),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: application/json",
"anthropic-version: <anthropic-version>"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "https://speshu.ai/api/v1/messages"
payload := strings.NewReader("{\n \"model\": \"anthropic/claude-sonnet-4.6\",\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": \"Привет!\"\n }\n ],\n \"max_tokens\": 1024,\n \"stream\": false,\n \"temperature\": 1,\n \"top_p\": 1,\n \"top_k\": 40,\n \"stop_sequences\": [\n \"<string>\"\n ],\n \"system\": \"You are a helpful assistant.\",\n \"thinking\": {\n \"type\": \"adaptive\"\n },\n \"tools\": [\n {}\n ],\n \"tool_choice\": {}\n}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("anthropic-version", "<anthropic-version>")
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://speshu.ai/api/v1/messages")
.header("anthropic-version", "<anthropic-version>")
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.body("{\n \"model\": \"anthropic/claude-sonnet-4.6\",\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": \"Привет!\"\n }\n ],\n \"max_tokens\": 1024,\n \"stream\": false,\n \"temperature\": 1,\n \"top_p\": 1,\n \"top_k\": 40,\n \"stop_sequences\": [\n \"<string>\"\n ],\n \"system\": \"You are a helpful assistant.\",\n \"thinking\": {\n \"type\": \"adaptive\"\n },\n \"tools\": [\n {}\n ],\n \"tool_choice\": {}\n}")
.asString();require 'uri'
require 'net/http'
url = URI("https://speshu.ai/api/v1/messages")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["anthropic-version"] = '<anthropic-version>'
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n \"model\": \"anthropic/claude-sonnet-4.6\",\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": \"Привет!\"\n }\n ],\n \"max_tokens\": 1024,\n \"stream\": false,\n \"temperature\": 1,\n \"top_p\": 1,\n \"top_k\": 40,\n \"stop_sequences\": [\n \"<string>\"\n ],\n \"system\": \"You are a helpful assistant.\",\n \"thinking\": {\n \"type\": \"adaptive\"\n },\n \"tools\": [\n {}\n ],\n \"tool_choice\": {}\n}"
response = http.request(request)
puts response.read_body{
"id": "msg_abc123",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "Привет! Чем помочь?"
}
],
"model": "anthropic/claude-sonnet-4.6",
"stop_reason": "end_turn",
"stop_sequence": "<string>",
"usage": {
"input_tokens": 10,
"output_tokens": 8
}
}{
"error": {
"type": "api_error",
"message": "model is required"
}
}{
"error": {
"type": "api_error",
"message": "model is required"
}
}{
"error": {
"type": "api_error",
"message": "model is required"
}
}{
"error": {
"type": "api_error",
"message": "model is required"
}
}{
"error": {
"type": "api_error",
"message": "model is required"
}
}{
"error": {
"type": "api_error",
"message": "model is required"
}
}SpeShu.AI поддерживает Anthropic-compatible
Ответ
Ответ приходит как
Клиент должен корректно обрабатывать неизвестные event-типы. Anthropic может добавлять новые события без изменения основного контракта.
POST /v1/messages. Если ваш клиент уже работает с Anthropic Messages API, замените base_url и используйте API-ключ SpeShu.AI.
Базовый URL
https://speshu.ai/api/v1
Авторизация
Поддерживаются оба варианта:x-api-key: <SPESHU_AI_API_KEY>
Authorization: Bearer <SPESHU_AI_API_KEY>
Также передавайте версию API:
anthropic-version: 2023-06-01
Синхронный запрос
curl "https://speshu.ai/api/v1/messages" \
-H "x-api-key: <SPESHU_AI_API_KEY>" \
-H "anthropic-version: 2023-06-01" \
-H "Content-Type: application/json" \
-d '{
"model": "anthropic/claude-sonnet-4.6",
"max_tokens": 1024,
"messages": [
{ "role": "user", "content": "Привет!" }
]
}'
Ответ 200
{
"id": "msg_abc123",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "Привет! Чем помочь?"
}
],
"model": "anthropic/claude-sonnet-4.6",
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 10,
"output_tokens": 8
}
}
Streaming
Установитеstream: true, чтобы получать ответ через Server-Sent Events.
curl "https://speshu.ai/api/v1/messages" \
-H "x-api-key: <SPESHU_AI_API_KEY>" \
-H "anthropic-version: 2023-06-01" \
-H "Content-Type: application/json" \
-d '{
"model": "anthropic/claude-sonnet-4.6",
"max_tokens": 1024,
"stream": true,
"messages": [
{ "role": "user", "content": "Посчитай до 3" }
]
}'
text/event-stream:
event: message_start
data: {"type":"message_start","message":{"id":"msg_abc","type":"message","role":"assistant","content":[],"model":"anthropic/claude-sonnet-4.6","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":8,"output_tokens":1}}}
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":"1, 2, 3"}}
event: content_block_stop
data: {"type":"content_block_stop","index":0}
event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":5}}
event: message_stop
data: {"type":"message_stop"}
Параметры
| Параметр | Тип | Обязательный | Описание |
|---|---|---|---|
model | string | Да | ID модели. Например, anthropic/claude-sonnet-4.6. |
messages | array | Да | История сообщений с role и content. |
max_tokens | integer | Да | Максимум токенов в ответе. |
stream | boolean | Нет | Включает SSE streaming. По умолчанию false. |
temperature | number | Нет | Температура генерации. |
top_p | number | Нет | Nucleus sampling. |
top_k | integer | Нет | Top-K sampling. |
stop_sequences | array | Нет | Пользовательские stop sequences. |
system | string или array | Нет | Системная инструкция. |
thinking | object | Нет | Настройки thinking. Например, { "type": "adaptive" }. |
tools | array | Нет | Описание инструментов для tool use. |
tool_choice | object | Нет | Стратегия выбора инструмента. |
Python SDK
from anthropic import Anthropic
client = Anthropic(
api_key="<SPESHU_AI_API_KEY>",
base_url="https://speshu.ai/api/v1",
)
message = client.messages.create(
model="anthropic/claude-sonnet-4.6",
max_tokens=1024,
messages=[{"role": "user", "content": "Привет!"}],
)
print(message.content[0].text)
Ошибки
Ошибки возвращаются в Anthropic-style формате:{
"error": {
"type": "api_error",
"message": "model is required"
}
}
| HTTP status | Описание |
|---|---|
400 | Неверный JSON или параметры запроса. |
401 | API-ключ не передан или недействителен. |
402 | Недостаточно средств на балансе. |
429 | Превышен лимит запросов. |
500 | Внутренняя ошибка сервера. |
502 | Провайдер временно недоступен. |
Авторизации
bearerxApiKey
API ключ передаётся в заголовке: Authorization: Bearer <SPESHU_AI_API_KEY>
Заголовки
Пример:
"2023-06-01"
Тело
application/json
Пример:
"anthropic/claude-sonnet-4.6"
Show child attributes
Show child attributes
Пример:
1024
Пример:
1
Пример:
1
Пример:
40
Пример:
"You are a helpful assistant."
Пример:
{ "type": "adaptive" }
Ответ
Сообщение создано. При stream=true ответ приходит как text/event-stream.
Пример:
"msg_abc123"
Пример:
"message"
Пример:
"assistant"
Show child attributes
Show child attributes
Пример:
"anthropic/claude-sonnet-4.6"
Пример:
"end_turn"
Show child attributes
Show child attributes
⌘I
Создать сообщение Anthropic Messages API
curl --request POST \
--url https://speshu.ai/api/v1/messages \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--header 'anthropic-version: <anthropic-version>' \
--data '
{
"model": "anthropic/claude-sonnet-4.6",
"messages": [
{
"role": "user",
"content": "Привет!"
}
],
"max_tokens": 1024,
"stream": false,
"temperature": 1,
"top_p": 1,
"top_k": 40,
"stop_sequences": [
"<string>"
],
"system": "You are a helpful assistant.",
"thinking": {
"type": "adaptive"
},
"tools": [
{}
],
"tool_choice": {}
}
'import requests
url = "https://speshu.ai/api/v1/messages"
payload = {
"model": "anthropic/claude-sonnet-4.6",
"messages": [
{
"role": "user",
"content": "Привет!"
}
],
"max_tokens": 1024,
"stream": False,
"temperature": 1,
"top_p": 1,
"top_k": 40,
"stop_sequences": ["<string>"],
"system": "You are a helpful assistant.",
"thinking": { "type": "adaptive" },
"tools": [{}],
"tool_choice": {}
}
headers = {
"anthropic-version": "<anthropic-version>",
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'POST',
headers: {
'anthropic-version': '<anthropic-version>',
Authorization: 'Bearer <token>',
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'anthropic/claude-sonnet-4.6',
messages: [{role: 'user', content: 'Привет!'}],
max_tokens: 1024,
stream: false,
temperature: 1,
top_p: 1,
top_k: 40,
stop_sequences: ['<string>'],
system: 'You are a helpful assistant.',
thinking: {type: 'adaptive'},
tools: [{}],
tool_choice: {}
})
};
fetch('https://speshu.ai/api/v1/messages', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://speshu.ai/api/v1/messages",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'model' => 'anthropic/claude-sonnet-4.6',
'messages' => [
[
'role' => 'user',
'content' => 'Привет!'
]
],
'max_tokens' => 1024,
'stream' => false,
'temperature' => 1,
'top_p' => 1,
'top_k' => 40,
'stop_sequences' => [
'<string>'
],
'system' => 'You are a helpful assistant.',
'thinking' => [
'type' => 'adaptive'
],
'tools' => [
[
]
],
'tool_choice' => [
]
]),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: application/json",
"anthropic-version: <anthropic-version>"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "https://speshu.ai/api/v1/messages"
payload := strings.NewReader("{\n \"model\": \"anthropic/claude-sonnet-4.6\",\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": \"Привет!\"\n }\n ],\n \"max_tokens\": 1024,\n \"stream\": false,\n \"temperature\": 1,\n \"top_p\": 1,\n \"top_k\": 40,\n \"stop_sequences\": [\n \"<string>\"\n ],\n \"system\": \"You are a helpful assistant.\",\n \"thinking\": {\n \"type\": \"adaptive\"\n },\n \"tools\": [\n {}\n ],\n \"tool_choice\": {}\n}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("anthropic-version", "<anthropic-version>")
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://speshu.ai/api/v1/messages")
.header("anthropic-version", "<anthropic-version>")
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.body("{\n \"model\": \"anthropic/claude-sonnet-4.6\",\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": \"Привет!\"\n }\n ],\n \"max_tokens\": 1024,\n \"stream\": false,\n \"temperature\": 1,\n \"top_p\": 1,\n \"top_k\": 40,\n \"stop_sequences\": [\n \"<string>\"\n ],\n \"system\": \"You are a helpful assistant.\",\n \"thinking\": {\n \"type\": \"adaptive\"\n },\n \"tools\": [\n {}\n ],\n \"tool_choice\": {}\n}")
.asString();require 'uri'
require 'net/http'
url = URI("https://speshu.ai/api/v1/messages")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["anthropic-version"] = '<anthropic-version>'
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n \"model\": \"anthropic/claude-sonnet-4.6\",\n \"messages\": [\n {\n \"role\": \"user\",\n \"content\": \"Привет!\"\n }\n ],\n \"max_tokens\": 1024,\n \"stream\": false,\n \"temperature\": 1,\n \"top_p\": 1,\n \"top_k\": 40,\n \"stop_sequences\": [\n \"<string>\"\n ],\n \"system\": \"You are a helpful assistant.\",\n \"thinking\": {\n \"type\": \"adaptive\"\n },\n \"tools\": [\n {}\n ],\n \"tool_choice\": {}\n}"
response = http.request(request)
puts response.read_body{
"id": "msg_abc123",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "Привет! Чем помочь?"
}
],
"model": "anthropic/claude-sonnet-4.6",
"stop_reason": "end_turn",
"stop_sequence": "<string>",
"usage": {
"input_tokens": 10,
"output_tokens": 8
}
}{
"error": {
"type": "api_error",
"message": "model is required"
}
}{
"error": {
"type": "api_error",
"message": "model is required"
}
}{
"error": {
"type": "api_error",
"message": "model is required"
}
}{
"error": {
"type": "api_error",
"message": "model is required"
}
}{
"error": {
"type": "api_error",
"message": "model is required"
}
}{
"error": {
"type": "api_error",
"message": "model is required"
}
}