Утилита для проксирования OpenAI и Anthropic запросов в GigaChat
Project description
gpt2giga
gpt2giga — FastAPI-прокси, который принимает OpenAI-совместимые и Anthropic-совместимые запросы и отправляет их в GigaChat. Он нужен, когда клиент, редактор, агентный фреймворк или SDK умеет работать с OpenAI/Anthropic API, а реальный backend должен быть GigaChat.
Локальный адрес по умолчанию: http://localhost:8090.
Зачем Нужен
GigaChat не является drop-in заменой OpenAI или Anthropic API. Прямое подключение существующих SDK часто ломается на формате запросов, streaming-событиях, tool schemas, model discovery, авторизации и optional-параметрах клиентов.
gpt2giga закрывает практические несовместимости:
- переводит OpenAI Chat Completions, OpenAI Responses, OpenAI Embeddings и Anthropic Messages в вызовы GigaChat;
- маппит tools/function calling, structured output, изображения, reasoning flags и SSE streaming там, где GigaChat поддерживает базовую возможность;
- принимает и безопасно игнорирует optional-поля OpenAI/Anthropic, которые SDK присылают, но GigaChat не понимает;
- фильтрует транспортные SDK headers, клиентские API keys, cookies и другие небезопасные метаданные перед upstream;
- отделяет клиентскую API-key авторизацию прокси от GigaChat credentials;
- отдаёт список моделей в OpenAI-, Anthropic- и LiteLLM-совместимом виде;
- держит batch/file routes отключёнными, пока их нельзя выполнить end-to-end через GigaChat SDK/backend.
Подробная матрица поддержки и список реальных ограничений вынесены в API Compatibility.
Быстрый Старт
Создайте .env из шаблона и заполните GigaChat credentials:
cp .env.example .env
Запуск через Docker Compose:
docker compose --env-file .env -f deploy/base.yaml --profile DEV up -d
Или локальный запуск:
uv tool install gpt2giga
gpt2giga
Минимальный OpenAI SDK вызов:
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8090/v1", api_key="<GPT2GIGA_API_KEY>")
response = client.chat.completions.create(
model="GigaChat-2-Max",
messages=[{"role": "user", "content": "Привет"}],
)
print(response.choices[0].message.content)
Минимальный Anthropic SDK вызов:
from anthropic import Anthropic
client = Anthropic(base_url="http://localhost:8090", api_key="<GPT2GIGA_API_KEY>")
response = client.messages.create(
model="GigaChat-2-Max",
max_tokens=256,
messages=[{"role": "user", "content": "Привет"}],
)
print(response.content[0].text)
Больше вариантов запуска — в Quickstart.
Документация
| Тема | Документ |
|---|---|
| Быстрый запуск и первые запросы | docs/quickstart.md |
| Что поддерживается, отключено или намеренно игнорируется | docs/api-compatibility.md |
Совместимость SDK extra_* и параметров клиентов |
docs/client-parameter-compatibility.md |
| Переменные окружения, CLI flags, backend modes | docs/configuration.md |
| Docker Compose, Traefik, Postgres, OpenSearch, Phoenix, production hardening | docs/deployment.md |
| Logs, metrics, traffic logs, admin API, debug translation | docs/operations.md |
| Внутренняя архитектура normalized messages | docs/architecture/normalized-messages.md |
| Checklist для добавления provider/protocol | docs/architecture/how-to-add-provider.md |
| Редакторы, агенты, SDK examples, reverse proxies | docs/integrations.md |
| Runnable-примеры | examples/README.md |
Текущая API-Поверхность
Смонтированные routes доступны в корне и под versioned prefixes. Root routes
используют GPT2GIGA_GIGACHAT_API_MODE, /v1 принудительно выбирает GigaChat
v1 contract, /v2 принудительно выбирает GigaChat v2 contract. Например:
/chat/completions, /v1/chat/completions и /v2/chat/completions.
Поддерживается:
- OpenAI-compatible
GET /models,GET /models/{model},POST /chat/completions,POST /responses,POST /embeddings; - Anthropic-compatible
POST /messages,POST /messages/count_tokens, а также Anthropic-shaped model responses для model-вызовов Anthropic SDK; - LiteLLM-compatible
GET /model/info; - системные endpoints
GET /healthиGET|POST /ping.
Отключено до появления нужных batch methods в GigaChat SDK/backend:
- OpenAI-compatible Files API и Batches API;
- Anthropic Message Batches API.
Сейчас не является целью проекта:
- полная OpenAI parity для audio, image generation/editing, fine-tuning, assistants, threads, runs, vector stores, uploads, moderations, realtime;
- полная Anthropic parity для Files beta, Skills beta, Agents beta, Sessions, Environments или Admin API.
Деплой
Docker Compose manifests лежат в deploy/:
docker compose --env-file .env -f deploy/base.yaml --profile PROD up -d
docker compose --env-file .env -f deploy/base.yaml --profile DEV up -d
Production mode требует API key и отключает /docs, /redoc, /openapi.json и /logs*:
GPT2GIGA_MODE=PROD
GPT2GIGA_ENABLE_API_KEY_AUTH=True
GPT2GIGA_API_KEY="<strong-random-secret>"
GIGACHAT_VERIFY_SSL_CERTS=True
Compose profiles, reverse proxies, TLS и hardening описаны в Deployment.
Структура Репозитория
| Path | Назначение |
|---|---|
gpt2giga/ |
FastAPI app, routers, protocol transforms, config, middleware |
tests/ |
Unit, router, protocol, sink и integration tests |
examples/ |
Runnable OpenAI, Anthropic, embeddings, files/batches, agents examples |
docs/ |
Пользовательская документация и architecture notes |
integrations/ |
Editor/agent/reverse-proxy integration guides |
deploy/ |
Docker Compose deployment manifests |
traefik/ |
Traefik config для deploy/traefik.yaml |
.github/ |
CI, release, Docker publish, PR/issue templates |
Разработка
Установить зависимости:
uv sync --all-extras --dev
Запустить сервис:
uv run gpt2giga
Проверки перед PR:
uv run ruff check .
uv run ruff format --check .
uv run pytest tests/ --cov=. --cov-report=term --cov-fail-under=80
Используйте Conventional Commits (feat:, fix:, docs:, refactor:, test:, ci:) и сверяйтесь с .github/PULL_REQUEST_TEMPLATE.md.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file gpt2giga-0.2.0a1.tar.gz.
File metadata
- Download URL: gpt2giga-0.2.0a1.tar.gz
- Upload date:
- Size: 1.1 MB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.11.20 {"installer":{"name":"uv","version":"0.11.20","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6eaa40ec591ab42d45aacf55e15b654f81f88ebf7a22cb262aa002f1ea8a5eb9
|
|
| MD5 |
495763307f7b8f980186edbb18d6e070
|
|
| BLAKE2b-256 |
ba4a124d00ff25702db62281520308f28715cf68b7c44547ddd24f0ac764cbfe
|
File details
Details for the file gpt2giga-0.2.0a1-py3-none-any.whl.
File metadata
- Download URL: gpt2giga-0.2.0a1-py3-none-any.whl
- Upload date:
- Size: 233.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.11.20 {"installer":{"name":"uv","version":"0.11.20","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a486967f70040e6eb1109c7c261b9d82c0f5c2e51be1754a554b70c7fa500ac8
|
|
| MD5 |
ebcb8fb9608b15c77c05a3abad4a0cdd
|
|
| BLAKE2b-256 |
4dd09c51b6151f554e95841f9368da65a94909f4744eea667a25b06d366d37db
|