Перейти к основному содержанию

Базовое использование

  • Python
  • JavaScript
  • cURL
  • Go
from openai import OpenAI

client = OpenAI(
    base_url="https://ai.megallm.io/v1",
    api_key="your-api-key"
)

response = client.chat.completions.create(
    model="gpt-4",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What's the weather like?"}
    ],
    temperature=0.7,
    max_tokens=150
)

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

Расширенные возможности

Роли сообщений

API поддерживает различные роли сообщений для контекста разговора:
РольОписаниеПример
systemУстанавливает поведение и контекст”You are a helpful assistant”
userВвод пользователя/вопросы”What’s the capital of France?”
assistantОтветы AI”The capital of France is Paris”
toolРезультаты инструментов/функцийFunction execution results

Контроль температуры

Настройте креативность ответов с помощью параметра temperature:
# Более детерминированный (0.0 - 0.3)
response = client.chat.completions.create(
    model="gpt-4",
    messages=[...],
    temperature=0.2  # Более сфокусированные, последовательные ответы
)

# Сбалансированный (0.4 - 0.7)
response = client.chat.completions.create(
    model="gpt-4",
    messages=[...],
    temperature=0.5  # Сбалансированная креативность и связность
)

# Более креативный (0.8 - 1.0)
response = client.chat.completions.create(
    model="gpt-4",
    messages=[...],
    temperature=0.9  # Более разнообразные, креативные ответы
)

Многоходовые разговоры

Поддержание контекста через несколько обменов:
messages = [
    {"role": "system", "content": "You are a math tutor."},
    {"role": "user", "content": "What is 15 * 12?"},
    {"role": "assistant", "content": "15 * 12 = 180"},
    {"role": "user", "content": "Now divide that by 6"}
]

response = client.chat.completions.create(
    model="gpt-4",
    messages=messages
)
# Ответ понимает, что "that" относится к 180

Поддержка изображений

Обработка изображений вместе с текстом (требуются модели с поддержкой vision):
response = client.chat.completions.create(
    model="gpt-4-vision",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "What's in this image?"},
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "https://example.com/image.jpg",
                        "detail": "high"  # "low", "high", или "auto"
                    }
                }
            ]
        }
    ],
    max_tokens=300
)

Формат ответа

Стандартный ответ

{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "created": 1677858242,
  "model": "gpt-4",
  "usage": {
    "prompt_tokens": 13,
    "completion_tokens": 17,
    "total_tokens": 30
  },
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "The capital of France is Paris."
      },
      "finish_reason": "stop",
      "index": 0
    }
  ]
}

Причины завершения

ПричинаОписание
stopЕстественное завершение
lengthДостигнут лимит max_tokens
tool_callsМодель хочет вызвать функцию
content_filterКонтент был отфильтрован

Лучшие практики

Системные сообщения: Всегда включайте четкое системное сообщение для установки поведения и контекста AI.

Оптимизация токенов

# Подсчет токенов перед отправкой
import tiktoken

encoding = tiktoken.encoding_for_model("gpt-4")
tokens = encoding.encode("Your message here")
print(f"Token count: {len(tokens)}")

# Усечение при необходимости
if len(tokens) > 1000:
    truncated = encoding.decode(tokens[:1000])

Обработка ошибок

try:
    response = client.chat.completions.create(...)
except openai.APIError as e:
    print(f"API error: {e}")
except openai.RateLimitError as e:
    print(f"Rate limit hit: {e}")
    # Реализуйте экспоненциальную задержку
except openai.APIConnectionError as e:
    print(f"Connection error: {e}")
    # Повторите попытку с задержкой

Распространенные паттерны

Суммаризация

response = client.chat.completions.create(
    model="gpt-4",
    messages=[
        {"role": "system", "content": "You are a summarization expert."},
        {"role": "user", "content": f"Summarize this text in 3 bullet points: {long_text}"}
    ],
    temperature=0.3,
    max_tokens=150
)

Классификация

response = client.chat.completions.create(
    model="gpt-4",
    messages=[
        {"role": "system", "content": "Classify the sentiment as positive, negative, or neutral."},
        {"role": "user", "content": "I love this product! It works great."}
    ],
    temperature=0.0,
    max_tokens=10
)

Генерация кода

response = client.chat.completions.create(
    model="gpt-4",
    messages=[
        {"role": "system", "content": "You are a Python expert."},
        {"role": "user", "content": "Write a function to calculate fibonacci numbers"}
    ],
    temperature=0.2,
    max_tokens=500
)

Ограничение скорости

Реализуйте правильное ограничение скорости для избежания ошибок:
import time
from typing import Optional

class RateLimiter:
    def __init__(self, requests_per_minute: int = 60):
        self.requests_per_minute = requests_per_minute
        self.request_times = []

    def wait_if_needed(self):
        now = time.time()
        # Удалить запросы старше 1 минуты
        self.request_times = [t for t in self.request_times if now - t < 60]

        if len(self.request_times) >= self.requests_per_minute:
            sleep_time = 60 - (now - self.request_times[0])
            if sleep_time > 0:
                time.sleep(sleep_time)

        self.request_times.append(now)

# Использование
limiter = RateLimiter(60)

for prompt in prompts:
    limiter.wait_if_needed()
    response = client.chat.completions.create(...)

Следующие шаги