Генерация текста

Генерация текста

Генерация текста выполняется через POST /api/v1/responses.

Параметры запроса

Параметры запроса идентичны документации OpenAI Responses API.

ПараметрТипОбязательныйОписание
modelstringДаНазвание модели из списка
inputstring / arrayДаТекст запроса или массив частей (сообщения и файлы)
instructionsstringНетСистемная инструкция для модели (1–2000 символов). Работает и для одиночного input, и для диалога. Роли system/developer в input не принимаются
reasoningobjectНетРежим рассуждения. Объект с полем effort: low, medium или high
streambooleanНетtrue — поток SSE (Content-Type: text/event-stream). false или поле не передано — JSON после завершения генерации
toolsarrayНетИнструменты модели

Пример запроса на генерацию текста

from openai import OpenAI
import json

client = OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://ai.mitup.ru/api/v1",
)

response = client.responses.create(
    model="deepseek-flash",
    input="Кратко расскажи, что нового у Mitup AI",
    instructions="Отвечай кратко",
    reasoning={
        "effort": "medium",
    },
    tools=[
        {
            "type": "web_search",
        },
    ],
)

print("Текст ответа:")
print(response.output_text)

for item in response.output:
    if item.type == "reasoning":
        print("Рассуждение:")
        for part in item.summary:
            print(part.text)
    if item.type == "message":
        for part in item.content:
            for annotation in getattr(part, "annotations", []) or []:
                print("Источник:", annotation.url)

print("Полный ответ (JSON):")
print(json.dumps(response.model_dump(), indent=2, ensure_ascii=False))
import json
import requests

url = "https://ai.mitup.ru/api/v1/responses"
api_key = "YOUR_API_KEY"

headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {api_key}"
}

params = {
    "model": "deepseek-flash",
    "input": "Кратко расскажи, что нового у Mitup AI",
    "instructions": "Отвечай кратко",
    "reasoning": {
        "effort": "medium"
    },
    "tools": [
        {
            "type": "web_search"
        }
    ]
}

response = requests.post(url, json=params, headers=headers)
data = response.json()

print("Текст ответа:")
for item in data.get("output") or []:
    if item.get("type") == "reasoning":
        print("Рассуждение:")
        for part in item.get("summary") or []:
            print(part.get("text") or "")
    if item.get("type") != "message":
        continue
    for part in item.get("content") or []:
        if part.get("type") in ("output_text", "text"):
            print(part.get("text") or "")
        for annotation in part.get("annotations") or []:
            print("Источник:", annotation.get("url") or "")

print("Полный ответ (JSON):")
print(json.dumps(data, indent=2, ensure_ascii=False))
curl -X POST "https://ai.mitup.ru/api/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
    "model": "deepseek-flash",
    "input": "Кратко расскажи, что нового у Mitup AI",
    "instructions": "Отвечай кратко",
    "reasoning": {
        "effort": "medium"
    },
    "tools": [
        {
            "type": "web_search"
        }
    ]
}'
<?php
$url = "https://ai.mitup.ru/api/v1/responses";
$api_key = "YOUR_API_KEY";

$headers = [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key,
];
$params = [
    "model" => "deepseek-flash",
    "input" => "Кратко расскажи, что нового у Mitup AI",
    "instructions" => "Отвечай кратко",
    "reasoning" => [
        "effort" => "medium",
    ],
    "tools" => [
        [
            "type" => "web_search",
        ],
    ],
];

$data = json_encode($params, JSON_UNESCAPED_UNICODE);

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'mitupai-API-client');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

$response = curl_exec($ch);
curl_close($ch);

$response = json_decode($response, true);

echo "Текст ответа:\n";
foreach ($response['output'] ?? [] as $item) {
    if (($item['type'] ?? '') === 'reasoning') {
        echo "Рассуждение:\n";
        foreach ($item['summary'] ?? [] as $part) {
            echo ($part['text'] ?? '') . "\n";
        }
    }
    if (($item['type'] ?? '') !== 'message') {
        continue;
    }
    foreach ($item['content'] ?? [] as $part) {
        if (in_array($part['type'] ?? '', ['output_text', 'text'], true)) {
            echo ($part['text'] ?? '') . "\n";
        }
        foreach ($part['annotations'] ?? [] as $annotation) {
            echo "Источник: " . ($annotation['url'] ?? '') . "\n";
        }
    }
}

echo "Полный ответ (JSON):\n";
echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
?>

Пример ответа (успех / ошибка, синхронный ответ):

{
    "id": "YOUR_TASK_ID",
    "object": "response",
    "created_at": 1710000000,
    "status": "completed",
    "instructions": "Отвечай кратко",
    "model": "deepseek-flash",
    "output": [
        {
            "id": "rs_YOUR_TASK_ID",
            "type": "reasoning",
            "status": "completed",
            "summary": [{
                "type": "summary_text",
                "text": "Нужно кратко ответить, что нового у Mitup AI. Сверяюсь с официальным сайтом и разделом моделей: сервис запустил API v1 в формате OpenAI Responses API и расширил набор моделей для текста, изображений, аудио и видео."
            }]
        },
        {
            "id": "msg_YOUR_TASK_ID",
            "type": "message",
            "status": "completed",
            "role": "assistant",
            "content": [{
                "type": "output_text",
                "text": "Mitup AI запустил API v1, совместимый с OpenAI Responses API, и расширил каталог моделей для текста, изображений, аудио и видео. Подробнее: https://ai.mitup.ru и https://ai.mitup.ru/models",
                "annotations": [
                    {
                        "type": "url_citation",
                        "url": "https://ai.mitup.ru",
                        "title": "https://ai.mitup.ru",
                        "start_index": 140,
                        "end_index": 159
                    },
                    {
                        "type": "url_citation",
                        "url": "https://ai.mitup.ru/models",
                        "title": "https://ai.mitup.ru/models",
                        "start_index": 162,
                        "end_index": 188
                    }
                ]
            }]
        }
    ],
    "parallel_tool_calls": true,
    "reasoning": {
        "effort": "medium"
    },
    "text": {"format": {"type": "text"}},
    "tool_choice": "auto",
    "tools": [
        {
            "type": "web_search"
        }
    ],
    "usage": {
        "input_tokens": 12,
        "input_tokens_details": {"cached_tokens": 0, "cache_write_tokens": 0},
        "output_tokens": 40,
        "output_tokens_details": {"reasoning_tokens": 8},
        "total_tokens": 52
    }
}
{
    "error": {
        "message": "The model failed to generate a response.",
        "type": "api_error",
        "param": null,
        "code": "api_error"
    }
}

Пример запроса с файлами

В одном input можно передать запрос + файлы.

  • Документ — input_file (file_data или file_url)
  • Картинка — input_image (image_url)
  • Аудио — input_audio
  • Видео — input_video

Передать файл можно как ссылку (URL) или в виде base64. Максимум 10 файлов / 10 МБ суммарно.

from openai import OpenAI

client = OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://ai.mitup.ru/api/v1",
)

response = client.responses.create(
    model="deepseek-flash",
    input=[{
        "role": "user",
        "content": [
            {"type": "input_text", "text": "Опиши изображение одним коротким предложением."},
            {"type": "input_image", "image_url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="},
        ],
    }],
)

print("Текст ответа:")
print(response.output_text)
import requests

url = "https://ai.mitup.ru/api/v1/responses"
api_key = "YOUR_API_KEY"

headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {api_key}"
}

params = {
    "model": "deepseek-flash",
    "input": [{
        "type": "message",
        "role": "user",
        "content": [
            {"type": "input_text", "text": "Опиши изображение одним коротким предложением."},
            {"type": "input_image", "image_url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="},
        ],
    }],
}

response = requests.post(url, json=params, headers=headers)
data = response.json()

print("Текст ответа:")
for item in data.get("output") or []:
    if item.get("type") != "message":
        continue
    for part in item.get("content") or []:
        if part.get("type") in ("output_text", "text"):
            print(part.get("text") or "")
curl -X POST "https://ai.mitup.ru/api/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
    "model": "deepseek-flash",
    "input": [
        {
            "type": "message",
            "role": "user",
            "content": [
                {"type": "input_text", "text": "Опиши изображение одним коротким предложением."},
                {"type": "input_image", "image_url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="}
            ]
        }
    ]
}'
<?php
$url = "https://ai.mitup.ru/api/v1/responses";
$api_key = "YOUR_API_KEY";

$headers = [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $api_key,
];

$params = [
    "model" => "deepseek-flash",
    "input" => [
        "type" => "message",
        "role" => "user",
        "content" => [
            ["type" => "input_text", "text" => "Опиши изображение одним коротким предложением."],
            ["type" => "input_image", "image_url" => "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="],
        ],
    ],
];

$data = json_encode($params, JSON_UNESCAPED_UNICODE);

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'mitupai-API-client');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

$response = curl_exec($ch);
curl_close($ch);

$response = json_decode($response, true);
echo "Текст ответа:\n";
foreach ($response['output'] ?? [] as $item) {
    if (($item['type'] ?? '') !== 'message') {
        continue;
    }
    foreach ($item['content'] ?? [] as $part) {
        if (in_array($part['type'] ?? '', ['output_text', 'text'], true)) {
            echo ($part['text'] ?? '') . "\n";
        }
    }
}
?>

Пример ответа:

{
    "id": "YOUR_TASK_ID",
    "object": "response",
    "created_at": 1710000000,
    "status": "completed",
    "model": "deepseek-flash",
    "output": [
        {
            "id": "msg_YOUR_TASK_ID",
            "type": "message",
            "status": "completed",
            "role": "assistant",
            "content": [{
                "type": "output_text",
                "text": "В вложениях фото, PDF, аудио и видео. На изображении — скрин интерфейса. В PDF краткое ТЗ. Аудио — голосовой комментарий к макету. Видео показывает тот же экран в движении. Все материалы об одном продукте: картинка и видео совпадают, PDF описывает требования, аудио дополняет их устно.",
                "annotations": []
            }]
        }
    ],
    "parallel_tool_calls": true,
    "text": {"format": {"type": "text"}},
    "tool_choice": "auto",
    "tools": [],
    "usage": {
        "input_tokens": 18,
        "input_tokens_details": {"cached_tokens": 0, "cache_write_tokens": 0},
        "output_tokens": 62,
        "output_tokens_details": {"reasoning_tokens": 0},
        "total_tokens": 80
    }
}
{
    "error": {
        "message": "The model failed to generate a response.",
        "type": "api_error",
        "param": null,
        "code": "api_error"
    }
}

Получение статуса задачи

В случае, если вы не дождались ответа (таймаут клиента, сеть) в синхронном запросе, получить результат можно позже, обратившись на отдельный эндпоинт.

GET /api/v1/responses/<id> — возвращает результат запроса по идентификатору.

Получить результат можно также через SDK OpenAI — client.responses.retrieve().

from openai import OpenAI

client = OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://ai.mitup.ru/api/v1",
)

response = client.responses.retrieve("YOUR_TASK_ID")

if response.status == "completed":
    print("Текст ответа:")
    print(response.output_text)
else:
    print("Статус:", response.status)
import requests

url = "https://ai.mitup.ru/api/v1/responses/YOUR_TASK_ID"
api_key = "YOUR_API_KEY"

headers = {
    "Authorization": f"Bearer {api_key}"
}

response = requests.get(url, headers=headers)
data = response.json()

if data.get("status") == "completed":
    print("Текст ответа:")
    for item in data.get("output") or []:
        if item.get("type") != "message":
            continue
        for part in item.get("content") or []:
            if part.get("type") in ("output_text", "text"):
                print(part.get("text") or "")
else:
    print("Статус:", data.get("status"))
curl -X GET "https://ai.mitup.ru/api/v1/responses/YOUR_TASK_ID" \
-H "Authorization: Bearer YOUR_API_KEY"
<?php
$url = "https://ai.mitup.ru/api/v1/responses/YOUR_TASK_ID";
$api_key = "YOUR_API_KEY";

$headers = [
    "Authorization: Bearer " . $api_key,
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "mitupai-API-client");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");

$response = curl_exec($ch);
curl_close($ch);

$response = json_decode($response, true);
if (($response['status'] ?? '') === 'completed') {
    echo "Текст ответа:\n";
    foreach ($response['output'] ?? [] as $item) {
        if (($item['type'] ?? '') !== 'message') {
            continue;
        }
        foreach ($item['content'] ?? [] as $part) {
            if (in_array($part['type'] ?? '', ['output_text', 'text'], true)) {
                echo ($part['text'] ?? '') . "\n";
            }
        }
    }
} else {
    echo "Статус: " . ($response['status'] ?? '') . "\n";
}
?>

Если задача не готова, GET отдаёт короткий объект со статусом in_progress. Когда генерация завершена — полный ответ JSON.

{
    "id": "YOUR_TASK_ID",
    "object": "response",
    "status": "in_progress"
}
{
    "id": "YOUR_TASK_ID",
    "object": "response",
    "created_at": 1710000000,
    "status": "completed",
    "model": "deepseek-flash",
    "output": [
        {
            "id": "msg_YOUR_TASK_ID",
            "type": "message",
            "status": "completed",
            "role": "assistant",
            "content": [{
                "type": "output_text",
                "text": "Mitup AI запустил API v1, совместимый с OpenAI Responses API.",
                "annotations": []
            }]
        }
    ]
}
{
    "error": {
        "message": "The model failed to generate a response.",
        "type": "api_error",
        "param": null,
        "code": "api_error"
    }
}

Удалить задачу можно на странице Удаление задачи.

Чат-боты

Выберите чат-бота на интересующую вас тематику и начните с ним работу

Сайт использует cookies

Продолжая работу, вы принимаете оферту, пользовательское соглашение и политику конфиденциальности.