Примеры использования

Время чтения: 6 мин. 21 просмотров

Python


import requests
import json

# Настройка
api_key = "ваш-api-ключ"
base_url = "https://apirouter.ru"

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

# Простой запрос
data = {
    "model": "openai/gpt-4o-mini",
    "messages": [
        {"role": "user", "content": "Привет! Как дела?"}
    ],
    "max_tokens": 150
}

response = requests.post(
    f"{base_url}/v1/chat/completions",
    headers=headers,
    json=data
)

if response.status_code == 200:
    result = response.json()
    print("Ответ:", result['choices'][0]['message']['content'])
    print("Токены:", result['usage']['total_tokens'])
else:
    print("Ошибка:", response.status_code, response.text)

# Использование с функциями
data_with_tools = {
    "model": "openai/gpt-4o",
    "messages": [
        {"role": "user", "content": "Какая температура в Москве?"}
    ],
    "tools": [
        {
            "type": "function",
            "function": {
                "name": "get_weather",
                "description": "Получить погоду в городе",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "city": {"type": "string"},
                        "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
                    },
                    "required": ["city"]
                }
            }
        }
    ]
}

response = requests.post(
    f"{base_url}/v1/chat/completions",
    headers=headers,
    json=data_with_tools
)

PHP


 'openai/gpt-4o-mini',
    'messages' => [
        ['role' => 'user', 'content' => 'Привет! Как дела?']
    ],
    'max_tokens' => 150
]);

// Инициализация cURL
$ch = curl_init($baseUrl . '/v1/chat/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

// Выполнение запроса
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode === 200) {
    $result = json_decode($response, true);
    echo "Ответ: " . $result['choices'][0]['message']['content'] . "\n";
    echo "Токены: " . $result['usage']['total_tokens'] . "\n";
} else {
    echo "Ошибка: $httpCode\n$response\n";
}

// Структурированный ответ
$structuredData = json_encode([
    'model' => 'openai/gpt-4o',
    'messages' => [
        ['role' => 'user', 'content' => 'Извлеки данные о компании: Apple Inc.']
    ],
    'response_format' => [
        'type' => 'json_schema',
        'json_schema' => [
            'name' => 'company_extraction',
            'schema' => [
                'type' => 'object',
                'properties' => [
                    'name' => ['type' => 'string'],
                    'industry' => ['type' => 'string'],
                    'founded' => ['type' => 'number'],
                    'headquarters' => ['type' => 'string']
                ],
                'required' => ['name', 'industry']
            ]
        ]
    ]
]);

$ch = curl_init($baseUrl . '/v1/chat/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $structuredData);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

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

Go


package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
)

type Message struct {
    Role    string `json:"role"`
    Content string `json:"content"`
}

type ChatRequest struct {
    Model     string    `json:"model"`
    Messages  []Message `json:"messages"`
    MaxTokens int       `json:"max_tokens,omitempty"`
}

type Choice struct {
    Message Message `json:"message"`
}

type Usage struct {
    PromptTokens     int `json:"prompt_tokens"`
    CompletionTokens int `json:"completion_tokens"`
    TotalTokens      int `json:"total_tokens"`
}

type ChatResponse struct {
    ID      string   `json:"id"`
    Choices []Choice `json:"choices"`
    Usage   Usage    `json:"usage"`
}

func main() {
    apiKey := "ваш-api-ключ"
    baseURL := "https://apirouter.ru"
    
    // Подготовка запроса
    reqData := ChatRequest{
        Model: "openai/gpt-4o-mini",
        Messages: []Message{
            {Role: "user", Content: "Привет! Как дела?"},
        },
        MaxTokens: 150,
    }
    
    jsonData, err := json.Marshal(reqData)
    if err != nil {
        panic(err)
    }
    
    // Создание HTTP запроса
    req, err := http.NewRequest("POST", baseURL+"/v1/chat/completions", bytes.NewBuffer(jsonData))
    if err != nil {
        panic(err)
    }
    
    req.Header.Set("Authorization", "Bearer "+apiKey)
    req.Header.Set("Content-Type", "application/json")
    
    // Выполнение запроса
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
    
    // Чтение ответа
    body, err := io.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }
    
    if resp.StatusCode == 200 {
        var chatResp ChatResponse
        err = json.Unmarshal(body, &chatResp)
        if err != nil {
            panic(err)
        }
        
        fmt.Printf("Ответ: %s\n", chatResp.Choices[0].Message.Content)
        fmt.Printf("Токены: %d\n", chatResp.Usage.TotalTokens)
    } else {
        fmt.Printf("Ошибка: %d\n%s\n", resp.StatusCode, string(body))
    }
}

// Пример с изображением
func ExampleWithImage() {
    apiKey := "ваш-api-ключ"
    baseURL := "https://apirouter.ru"
    
    reqData := map[string]interface{}{
        "model": "openai/gpt-4o",
        "messages": []map[string]interface{}{
            {
                "role": "user",
                "content": []map[string]interface{}{
                    {"type": "text", "text": "Что изображено на картинке?"},
                    {
                        "type": "image_url",
                        "image_url": map[string]string{
                            "url": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQ...",
                        },
                    },
                },
            },
        },
        "max_tokens": 300,
    }
    
    jsonData, _ := json.Marshal(reqData)
    
    req, _ := http.NewRequest("POST", baseURL+"/v1/chat/completions", bytes.NewBuffer(jsonData))
    req.Header.Set("Authorization", "Bearer "+apiKey)
    req.Header.Set("Content-Type", "application/json")
    
    client := &http.Client{}
    resp, _ := client.Do(req)
    defer resp.Body.Close()
    
    body, _ := io.ReadAll(resp.Body)
    fmt.Println(string(body))
}

cURL, bash


curl -X POST https://apirouter.ru/v1/chat/completions \
  -H "Authorization: Bearer ваш-api-ключ" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4o-mini",
    "messages": [
      {"role": "user", "content": "Привет! Как дела?"}
    ],
    "max_tokens": 150
  }'

# Запрос с функциями
curl -X POST https://apirouter.ru/v1/chat/completions \
  -H "Authorization: Bearer ваш-api-ключ" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4o",
    "messages": [
      {"role": "user", "content": "Какая погода в Москве?"}
    ],
    "tools": [
      {
        "type": "function",
        "function": {
          "name": "get_weather",
          "description": "Получить погоду в городе",
          "parameters": {
            "type": "object",
            "properties": {
              "city": {"type": "string"},
              "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
            },
            "required": ["city"]
          }
        }
      }
    ]
  }'

# Структурированный ответ
curl -X POST https://apirouter.ru/v1/chat/completions \
  -H "Authorization: Bearer ваш-api-ключ" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4o",
    "messages": [
      {"role": "user", "content": "Извлеки информацию о компании Apple"}
    ],
    "response_format": {
      "type": "json_schema",
      "json_schema": {
        "name": "company_info",
        "schema": {
          "type": "object",
          "properties": {
            "name": {"type": "string"},
            "industry": {"type": "string"},
            "founded": {"type": "number"}
          }
        }
      }
    }
  }'

# Работа с изображениями
curl -X POST https://apirouter.ru/v1/chat/completions \
  -H "Authorization: Bearer ваш-api-ключ" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4o",
    "messages": [
      {
        "role": "user",
        "content": [
          {"type": "text", "text": "Опиши что на картинке"},
          {
            "type": "image_url",
            "image_url": {
              "url": "https://example.com/image.jpg"
            }
          }
        ]
      }
    ]
  }'

# Получение списка моделей
curl -X GET https://apirouter.ru/v1/models \
  -H "Authorization: Bearer ваш-api-ключ"

# Получение статистики
curl -X GET "https://apirouter.ru/v1/generation?id=gen_abc123" \
  -H "Authorization: Bearer ваш-api-ключ"

# Проверка состояния сервиса
curl -X GET https://apirouter.ru/health

JavaScript (Node.js)


const axios = require('axios');

const apiKey = 'ваш-api-ключ';
const baseURL = 'https://apirouter.ru';

const headers = {
    'Authorization': `Bearer ${apiKey}`,
    'Content-Type': 'application/json'
};

// Простой запрос
async function simpleRequest() {
    try {
        const response = await axios.post(`${baseURL}/v1/chat/completions`, {
            model: 'openai/gpt-4o-mini',
            messages: [
                { role: 'user', content: 'Привет! Как дела?' }
            ],
            max_tokens: 150
        }, { headers });

        console.log('Ответ:', response.data.choices[0].message.content);
        console.log('Токены:', response.data.usage.total_tokens);
    } catch (error) {
        console.error('Ошибка:', error.response?.status, error.response?.data);
    }
}

// Потоковый запрос
async function streamRequest() {
    try {
        const response = await axios.post(`${baseURL}/v1/chat/completions`, {
            model: 'openai/gpt-4o-mini',
            messages: [
                { role: 'user', content: 'Напиши короткую историю' }
            ],
            stream: true,
            max_tokens: 200
        }, { 
            headers,
            responseType: 'stream'
        });

        response.data.on('data', (chunk) => {
            const lines = chunk.toString().split('\n');
            lines.forEach(line => {
                if (line.startsWith('data: ')) {
                    const data = line.slice(6);
                    if (data !== '[DONE]') {
                        try {
                            const parsed = JSON.parse(data);
                            const content = parsed.choices[0]?.delta?.content;
                            if (content) {
                                process.stdout.write(content);
                            }
                        } catch (e) {
                            // Игнорируем ошибки парсинга
                        }
                    }
                }
            });
        });
    } catch (error) {
        console.error('Ошибка:', error.message);
    }
}

// Использование функций
async function functionCall() {
    try {
        const response = await axios.post(`${baseURL}/v1/chat/completions`, {
            model: 'openai/gpt-4o',
            messages: [
                { role: 'user', content: 'Какая погода в Санкт-Петербурге?' }
            ],
            tools: [
                {
                    type: 'function',
                    function: {
                        name: 'get_weather',
                        description: 'Получить текущую погоду в городе',
                        parameters: {
                            type: 'object',
                            properties: {
                                city: { type: 'string', description: 'Название города' },
                                unit: { type: 'string', enum: ['celsius', 'fahrenheit'], default: 'celsius' }
                            },
                            required: ['city']
                        }
                    }
                }
            ]
        }, { headers });

        const choice = response.data.choices[0];
        if (choice.message.tool_calls) {
            console.log('Вызов функции:', choice.message.tool_calls[0].function);
        } else {
            console.log('Ответ:', choice.message.content);
        }
    } catch (error) {
        console.error('Ошибка:', error.response?.status, error.response?.data);
    }
}

// Работа с изображениями
async function imageAnalysis() {
    try {
        const response = await axios.post(`${baseURL}/v1/chat/completions`, {
            model: 'openai/gpt-4o',
            messages: [
                {
                    role: 'user',
                    content: [
                        { type: 'text', text: 'Опиши что изображено на картинке' },
                        {
                            type: 'image_url',
                            image_url: {
                                url: 'https://example.com/image.jpg'
                            }
                        }
                    ]
                }
            ],
            max_tokens: 300
        }, { headers });

        console.log('Описание изображения:', response.data.choices[0].message.content);
    } catch (error) {
        console.error('Ошибка:', error.response?.status, error.response?.data);
    }
}

// Выполнение примеров
simpleRequest();
streamRequest();
functionCall();
imageAnalysis();

JavaScript (Browser/Frontend)


class APIRouter {
    constructor(apiKey) {
        this.apiKey = apiKey;
        this.baseURL = 'https://apirouter.ru';
    }

    async request(endpoint, data) {
        try {
            const response = await fetch(`${this.baseURL}${endpoint}`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${this.apiKey}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            });

            if (!response.ok) {
                throw new Error(`HTTP ${response.status}`);
            }

            return await response.json();
        } catch (error) {
            console.error('API Error:', error);
            throw error;
        }
    }

    async chat(model, messages, options = {}) {
        return this.request('/v1/chat/completions', {
            model,
            messages,
            ...options
        });
    }

    async chatWithImage(model, text, imageUrl, options = {}) {
        const messages = [{
            role: 'user',
            content: [
                { type: 'text', text },
                { type: 'image_url', image_url: { url: imageUrl } }
            ]
        }];

        return this.chat(model, messages, options);
    }

    async structuredResponse(model, prompt, schema, options = {}) {
        return this.chat(model, [
            { role: 'user', content: prompt }
        ], {
            response_format: {
                type: 'json_schema',
                json_schema: {
                    name: 'structured_response',
                    schema
                }
            },
            ...options
        });
    }
}

// Использование
const apiRouter = new APIRouter('ваш-api-ключ');

// Простой чат
apiRouter.chat('openai/gpt-4o-mini', [
    { role: 'user', content: 'Привет! Как дела?' }
], { max_tokens: 150 })
.then(response => {
    console.log('Ответ:', response.choices[0].message.content);
})
.catch(error => {
    console.error('Ошибка:', error);
});

// Анализ изображения
apiRouter.chatWithImage(
    'openai/gpt-4o',
    'Опиши что изображено на картинке',
    'https://example.com/image.jpg'
)
.then(response => {
    console.log('Описание:', response.choices[0].message.content);
});

// Структурированный ответ
const companySchema = {
    type: 'object',
    properties: {
        name: { type: 'string' },
        industry: { type: 'string' },
        founded: { type: 'number' },
        employees: { type: 'number' }
    },
    required: ['name', 'industry']
};

apiRouter.structuredResponse(
    'openai/gpt-4o',
    'Извлеки информацию о компании Microsoft',
    companySchema
)
.then(response => {
    const data = JSON.parse(response.choices[0].message.content);
    console.log('Структурированные данные:', data);
});

Поделиться этой страницей

Примеры использования

Или скопируйте ссылку

СОДЕРЖИМОЕ