Документация к API нейросети

API доступен только для пользователей с подключенным тарифом Престиж.

1 API Unit = 2 обычных запроса из пользовательского интерфейса сайта. Пересчет происходит автоматически.

То есть подойдут и запросы из купленных пакетов, и из тарифа (сначала будут использованы запросы из дневного лимита тарифа, а затем из пакета запросов, когда дневной лимит кончится).

Что делать, если запросов тарифа не хватает? Оплатить пакеты запросов. Вы можете купить сколько угодно пакетов.

Количество доступных API Units можно проверить запросом на /api/gpt/units.

Максимальная длина запроса — 10 000 символов. В случае превышения длины запрос автоматически обрезается.

Для обработки запросов мы используем современную модель GPT-4o, поэтому качество генерации на высоте.

Совместимый с ChatGPT API

Наш сервис предоставляет полностью совместимый с OpenAI ChatGPT API эндпоинт. Вы можете использовать любые существующие библиотеки и SDK для ChatGPT, просто заменив базовый URL и API ключ.

POST https://chatinfo.ru/v1/chat/completions
Цена: 1 API Unit за запрос
Макс. частота запросов: 1500 в минуту

Заголовки запроса

Authorization: Bearer ВАШ_API_КЛЮЧ
Content-Type: application/json

Request Body

{
    "model": "gpt-4o",
    "messages": [
        {
            "role": "user",
            "content": "Привет, как дела?"
        }
    ]
}

Response

{
    "id": "chatcmpl-123",
    "object": "chat.completion",
    "created": 1677652288,
    "model": "gpt-4o",
    "choices": [
        {
            "index": 0,
            "message": {
                "role": "assistant",
                "content": "Привет! У меня все отлично, спасибо! Как дела у тебя?"
            },
            "finish_reason": "stop"
        }
    ],
    "usage": {
        "prompt_tokens": 12,
        "completion_tokens": 15,
        "total_tokens": 27
    }
}

Пример на Python

АПИ нейросети ChatGPT на Python позволяет легко интегрировать искусственный интеллект в ваши проекты с помощью библиотеки openai:

from openai import OpenAI

# Инициализация клиента с нашим API
client = OpenAI(
    api_key="ВАШ_API_КЛЮЧ",
    base_url="https://chatinfo.ru/v1"
)

# Отправка запроса
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "user", "content": "Привет, как дела?"}
    ]
)

print(response.choices[0].message.content)

Пример с cURL

API ChatGPT через cURL — простой способ тестирования нейросети из командной строки:

curl -X POST "https://chatinfo.ru/v1/chat/completions" \
  -H "Authorization: Bearer ВАШ_API_КЛЮЧ" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {
        "role": "user",
        "content": "Привет, как дела?"
      }
    ]
  }'

Пример на Java

АПИ Чат ГПТ на Java для интеграции искусственного интеллекта в корпоративные приложения, используя официальную библиотеку openai-java:

import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.client.OpenAIClient;
import com.openai.models.ChatModel;
import com.openai.models.chat.completions.*;

public class ChatInfoExample {
    public static void main(String[] args) {
        // Создание клиента с настройкой на наш эндпоинт
        OpenAIClient client = OpenAIOkHttpClient.builder()
            .apiKey("ВАШ_API_КЛЮЧ")
            .baseUrl("https://chatinfo.ru/v1/")
            .build();

        // Создание запроса
        ChatCompletion response = client.chat().completions().create(
            ChatCompletionCreateParams.builder()
                .model(ChatModel.GPT_4_O)
                .addMessage(ChatCompletionMessageParam.ofChatCompletionUserMessageParam(
                    ChatCompletionUserMessageParam.builder()
                        .content("Привет, как дела?")
                        .build()
                ))
                .build()
        );

        // Получение ответа
        String aiResponse = response.choices().get(0).message().content();
        System.out.println(aiResponse);
    }
}

Зависимость для Maven:

<dependency>
    <groupId>com.openai</groupId>
    <artifactId>openai-java</artifactId>
    <version>2.12.1</version>
</dependency>

Зависимость для Gradle:

implementation 'com.openai:openai-java:2.12.1'





Пример на JavaScript (браузер)

API Chat GPT на JavaScript для веб-приложений — подключите нейросеть прямо в браузере:

async function chatWithAI(message) {
    const response = await fetch('https://chatinfo.ru/v1/chat/completions', {
        method: 'POST',
        headers: {
            'Authorization': 'Bearer ВАШ_API_КЛЮЧ',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            model: 'gpt-4o',
            messages: [
                { role: 'user', content: message }
            ]
        })
    });

    const data = await response.json();
    return data.choices[0].message.content;
}

// Использование
chatWithAI('Привет, как дела?').then(response => {
    console.log(response);
});

Пример на PHP

API интеграция ChatGPT на PHP для быстрой интеграции искусственного интеллекта в веб-проекты:

<?php
function chatWithAI($message, $apiKey) {
    $url = 'https://chatinfo.ru/v1/chat/completions';
    
    $data = array(
        'model' => 'gpt-4o',
        'messages' => array(
            array('role' => 'user', 'content' => $message)
        )
    );
    
    $options = array(
        'http' => array(
            'header'  => "Content-Type: application/json\r\n" .
                        "Authorization: Bearer " . $apiKey . "\r\n",
            'method'  => 'POST',
            'content' => json_encode($data)
        )
    );
    
    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    $response = json_decode($result, true);
    
    return $response['choices'][0]['message']['content'];
}

// Использование
$response = chatWithAI('Привет, как дела?', 'ВАШ_API_КЛЮЧ');
echo $response;
?>

Пример на C++

API ChatGPT совместимый с OpenAI на C++ для высокопроизводительных приложений с нейросетевыми возможностями:

#include <iostream>
#include <string>
#include <curl/curl.h>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

struct APIResponse {
    std::string data;
};

size_t WriteCallback(void* contents, size_t size, size_t nmemb, APIResponse* response) {
    response->data.append((char*)contents, size * nmemb);
    return size * nmemb;
}

std::string chatWithAI(const std::string& message, const std::string& apiKey) {
    CURL* curl;
    CURLcode res;
    APIResponse response;

    curl = curl_easy_init();
    if(curl) {
        json requestData;
        requestData["model"] = "gpt-4o";
        requestData["messages"] = json::array({{{"role", "user"}, {"content", message}}});

        std::string jsonString = requestData.dump();

        struct curl_slist* headers = nullptr;
        std::string authHeader = "Authorization: Bearer " + apiKey;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        headers = curl_slist_append(headers, authHeader.c_str());

        curl_easy_setopt(curl, CURLOPT_URL, "https://chatinfo.ru/v1/chat/completions");
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonString.c_str());
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);
        curl_slist_free_all(headers);
    }

    json responseJson = json::parse(response.data);
    return responseJson["choices"][0]["message"]["content"];
}

int main() {
    std::string response = chatWithAI("Привет, как дела?", "ВАШ_API_КЛЮЧ");
    std::cout << response << std::endl;
    return 0;
}

Пример на C#

АПИ нейросети ЧатГПТ на C# для .NET приложений — интегрируйте искусственный интеллект в Windows-проекты:

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

public class ChatInfoClient
{
    private readonly HttpClient httpClient;
    private readonly string apiKey;

    public ChatInfoClient(string apiKey)
    {
        this.apiKey = apiKey;
        this.httpClient = new HttpClient();
        this.httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
    }

    public async Task<string> ChatAsync(string message)
    {
        var requestData = new
        {
            model = "gpt-4o",
            messages = new[]
            {
                new { role = "user", content = message }
            }
        };

        var json = JsonConvert.SerializeObject(requestData);
        var content = new StringContent(json, Encoding.UTF8, "application/json");

        var response = await httpClient.PostAsync("https://chatinfo.ru/v1/chat/completions", content);
        var responseJson = await response.Content.ReadAsStringAsync();
        
        dynamic result = JsonConvert.DeserializeObject(responseJson);
        return result.choices[0].message.content;
    }
}

// Использование
class Program
{
    static async Task Main(string[] args)
    {
        var client = new ChatInfoClient("ВАШ_API_КЛЮЧ");
        var response = await client.ChatAsync("Привет, как дела?");
        Console.WriteLine(response);
    }
}

Проприетарный API ChatInfo

Создать запрос к нейросети

POST /api/gpt/create_request
Цена: 1 API Unit
Макс. частота запросов: 1500 в минуту

Request Body

{
    "content": "string",
    "mode": "string",
    "key": "string"
}

Response

{
    "units": "long",
    "success": "boolean",
    "error": "string",
    "id": "long"
}

Описание параметров запроса

content текст запроса
mode режим работы нейросети (по умолчанию "chat")
key ключ доступа API — на странице https://chatinfo.ru/subscription

Описание параметров ответа

units Число доступных API Units
id ID запроса для последующего получения ответа нейросети
  • "chat" — обычный запрос
  • "shorter" — Сократить текст
  • "continue" — Продолжить текст
  • "names" — Генератор названий
  • "task" — Решить задачу
  • "text" — Написать художественный текст
  • "poems" — Написать стихи
  • "books_list" — Список литературы
  • "song_text" — Написать песню
  • "summary" — Вывод по тексту
  • "paper" — Написать реферат
  • "report" — Написать доклад
  • "originality" — Поднять уникальность
  • "rewrite" — Рерайт текста
  • "essay" — Написать сочинение
  • "plan" — Составить контент-план
  • "post" — Написать пост в соцсети
  • "code" — Написать код
  • "synopsis" — Написать конспект текста
  • "story" — Написать историю
  • "article" — Написать статью
  • "answer" — Ответить на вопрос
import requests
import json

def create_request(key, mode, content):
    url = 'https://chatinfo.ru/api/gpt/create_request'
    parameters = {'key': key, 'mode': mode, 'content': content}
    payload = json.dumps(parameters)
    response = requests.post(url, data=payload)

    return response.json()
HTTP [200]
{
	"success": true,
	"units": 956,
	"id": 1234
}
HTTP [403]
{
	"success": false,
	"units": 0,
	"error": "Недостаточно API Units для создания запроса. Купить еще: https://chatinfo.ru/prices"
}
HTTP [429]
{
  	"success": false
	"error": "Кажется, вы отправляете запросы слишком часто. Обновите страницу, чтобы продолжить",
}
HTTP [403]
{
	"success": false,
	"error": "Использовать API можно только на тарифе Престиж. Ваш тариф: Бесплатный."
}

Получить результат работы нейросети

POST /api/gpt/get_response
Цена: 0 API Units
Макс. частота запросов: 15 000 в минуту

Request Body

{
    "id": "long",
    "key": "string"
}

Response

{
    "success": "boolean",
    "solving": "boolean",
    "error": "string",
    "result": "string"
}

Описание параметров запроса

key ключ доступа API — на странице https://chatinfo.ru/subscription
id ID запроса, который получен в методе /api/gpt/create_request

Описание параметров ответа

solving true, если запрос еще в процессе решения, false — если уже решен
result результат работы нейросети
import requests
import json

def get_response(key, id):
    url = 'https://chatinfo.ru/api/gpt/get_response'
    parameters = {'key': key, 'id': id}
    payload = json.dumps(parameters)
    response = requests.post(url, data=payload)

    return response.json()
HTTP [200]
(запрос успешно решен)
{
	"success": true,
	"solving": false,
	"result": "As an AI, I don't have feelings, but I'm here and ready to help you. How can I assist you today?"
}
HTTP [202]
(запрос в процессе решения)
{
	"success": false,
	"solving": true
}
HTTP [429]
{
  	"success": false
	"error": "Кажется, вы отправляете запросы слишком часто. Обновите страницу, чтобы продолжить",
}

Получить число доступных API Units

POST /api/gpt/units
Цена: 0 API Units
Макс. частота запросов: 500 в минуту

Request Body

{
    "key": "string"
}

Response

{
    "units": "long"
}

Описание параметров запроса

key ключ доступа API — на странице https://chatinfo.ru/subscription

Описание параметров ответа

units Число доступных API Units
import requests
import json

def get_units(key):
    url = 'https://chatinfo.ru/api/gpt/units'
    parameters = {'key': key}
    payload = json.dumps(parameters)
    response = requests.post(url, data=payload)

    return response.json()
HTTP [200]
{
	"success": true,
	"units": 233
}
HTTP [403]
{
	"success": false,
	"error": "Использовать API можно только на тарифе Престиж. Ваш тариф: Бесплатный."
}

Готовая реализация на Python

import json
import time
import requests


def get_units(key):
    url = 'https://chatinfo.ru/api/gpt/units'
    parameters = {'key': key}
    payload = json.dumps(parameters)
    response = requests.post(url, data=payload)

    return response.json()


def create_request(key, mode, content):
    url = 'https://chatinfo.ru/api/gpt/create_request'
    parameters = {'key': key, 'mode': mode, 'content': content}
    payload = json.dumps(parameters)
    response = requests.post(url, data=payload)

    return response.json()


def get_response(key, id):
    url = 'https://chatinfo.ru/api/gpt/get_response'
    parameters = {'key': key, 'id': id}
    payload = json.dumps(parameters)
    response = requests.post(url, data=payload)

    return response.json()


def solve(key, mode, content):
    # Шаг 1: создаем запрос
    request_info = create_request(key, mode, content)

    if 'id' not in request_info:
        print("Failed to create request. Error: " + request_info['error'] + ".")
        return None

    request_id = request_info['id']

    print("Created request with id " + str(request_id) + ".")
    time.sleep(2)

    # Шаг 2: ждем ответа
    max_attempts = 80
    attempts = 0

    while attempts < max_attempts:
        response_info = get_response(key, request_id)

        if 'success' in response_info and response_info['success']:
            return response_info['result']
        elif 'solving' in response_info and response_info['solving']:
            # Ждем 2 секунды перед следующей попыткой
            time.sleep(2)
            attempts += 1
        else:
            print("Failed to get response. Error: " + response_info['error'] + ".")
            return None

    print("Timed out waiting for response.")
    return None


if __name__ == '__main__':
    print(solve('ВАШ_КЛЮЧ', 'text', 'What is the meaning of life?'))

API текстовой нейросети онлайн

Подключите API нейросети к своему сервису и получайте результаты работы искусственного интеллекта для текста в реальном времени. Теперь генерировать контент плагинами или другим способом стало удобно как никогда.

Почему это так удобно? Вы можете платить за API нейронной сети любым удобным способом из России и стран СНГ.