Metadata-Version: 2.5
Name: gpt2giga
Version: 0.3.3a1
Summary: Утилита для проксирования OpenAI, Anthropic и Gemini запросов в GigaChat
Project-URL: Homepage, https://ai-forever.github.io/gpt2giga/
Project-URL: Documentation, https://ai-forever.github.io/gpt2giga/
Project-URL: Repository, https://github.com/ai-forever/gpt2giga
Project-URL: Issues, https://github.com/ai-forever/gpt2giga/issues
Project-URL: Changelog, https://github.com/ai-forever/gpt2giga/blob/main/CHANGELOG_en.md
Author-email: Konstantin Krestnikov <rai220@gmail.com>
License-Expression: MIT
License-File: LICENSE
Requires-Python: <3.16,>=3.10
Requires-Dist: aiohttp<4,>=3.14.5
Requires-Dist: aioitertools<0.14,>=0.13.0
Requires-Dist: anthropic>=0.120.2
Requires-Dist: certifi>=2024.2.2
Requires-Dist: fastapi<1,>=0.140.13
Requires-Dist: gigachat[aiohttp]==0.3.0a1
Requires-Dist: google-genai<3,>=2.14.0
Requires-Dist: httpx<1,>=0.28.1
Requires-Dist: loguru<0.8,>=0.7.3
Requires-Dist: openai<4,>=2.50.0
Requires-Dist: pydantic-settings<3,>=2.14.2
Requires-Dist: python-dotenv<2,>=1.2.2
Requires-Dist: python-multipart<0.1.0,>=0.0.27
Requires-Dist: pyyaml<7,>=6.0.3
Requires-Dist: sse-starlette<4,>=3.4.6
Requires-Dist: starlette<2,>=1.3.1
Requires-Dist: tiktoken<1,>=0.13.0
Requires-Dist: uvicorn<1,>=0.51.0
Provides-Extra: opensearch
Requires-Dist: opensearch-py<3,>=2.8.0; extra == 'opensearch'
Provides-Extra: phoenix
Requires-Dist: arize-phoenix-otel<1,>=0.16.1; extra == 'phoenix'
Requires-Dist: openinference-semantic-conventions<1,>=0.1.30; extra == 'phoenix'
Requires-Dist: opentelemetry-exporter-otlp<2,>=1.44.0; extra == 'phoenix'
Requires-Dist: opentelemetry-sdk<2,>=1.28.0; extra == 'phoenix'
Provides-Extra: postgres
Requires-Dist: alembic<2,>=1.18.5; extra == 'postgres'
Requires-Dist: asyncpg<1,>=0.31.0; extra == 'postgres'
Requires-Dist: sqlalchemy[asyncio]<3,>=2.0.51; extra == 'postgres'
Description-Content-Type: text/markdown

# gpt2giga

[![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/ai-forever/gpt2giga/ci.yaml?&style=flat-square)](https://github.com/ai-forever/gpt2giga/actions/workflows/ci.yaml)
[![PyPI](https://img.shields.io/pypi/v/gpt2giga?style=flat-square&label=PyPI)](https://pypi.org/project/gpt2giga/)
[![Python](https://img.shields.io/pypi/pyversions/gpt2giga?style=flat-square)](https://pypi.org/project/gpt2giga/)
[![GitHub License](https://img.shields.io/github/license/ai-forever/gpt2giga?style=flat-square)](https://opensource.org/licenses/MIT)
[![PyPI Downloads](https://img.shields.io/pypi/dm/gpt2giga?style=flat-square)](https://pypistats.org/packages/gpt2giga)
[![GitHub Repo stars](https://img.shields.io/github/stars/ai-forever/gpt2giga?style=flat-square)](https://star-history.com/#ai-forever/gpt2giga)
[![GitHub Open Issues](https://img.shields.io/github/issues-raw/ai-forever/gpt2giga?style=flat-square)](https://github.com/ai-forever/gpt2giga/issues)
[![Docs](https://img.shields.io/badge/docs-GitHub%20Pages-111827?style=flat-square)](https://ai-forever.github.io/gpt2giga/)

![Gateway coverage](https://raw.githubusercontent.com/ai-forever/gpt2giga/main/badges/coverage.svg)

`gpt2giga` — FastAPI-прокси, который принимает OpenAI-, Anthropic- и
Gemini-like запросы и отправляет их в GigaChat либо в проверенный
OpenAI-compatible Chat Completions backend. Он нужен, когда клиент, редактор,
агентный фреймворк или SDK говорит на одном API, а реальный backend предоставляет
другой совместимый контракт.

Локальный адрес по умолчанию: `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 и Gemini GenerateContent в вызовы 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-, Gemini- и LiteLLM-совместимом виде;
- поддерживает Files/Batches OpenAI, Anthropic и Gemini в документированном подмножестве.

Подробная матрица поддержки и список реальных ограничений вынесены в [API Compatibility](https://ai-forever.github.io/gpt2giga/api-compatibility).

## Быстрый Старт

Кандидат 0.3.3a1 требует `gigachat[aiohttp]==0.3.0a1`. SDK опубликован в PyPI и устанавливается
автоматически вместе со шлюзом через `uv`, pip или при сборке Docker.

Из корня репозитория создайте `.env` из шаблона и заполните GigaChat credentials:

```sh
cp .env.example .env
```

Соберите и запустите текущий checkout через Docker Compose:

```sh
docker compose --env-file .env -f deploy/base.yaml --profile DEV up -d --build --pull never
```

Или запустите его локально:

```sh
uv sync --all-extras --dev
uv run gpt2giga
```

Для установки этого checkout через pip в существующее окружение:

```sh
python -m pip install .
```

Установка из индекса выбирает опубликованный стабильный релиз, который может
ещё не включать возможности текущего checkout:

```sh
uv tool install gpt2giga
gpt2giga --help
```

Для установки опубликованного релиза в существующее окружение:

```sh
python -m pip install gpt2giga
```

Поддерживается Python 3.10–3.15. Стабильный Python 3.15 входит в обязательные
CI-проверки тестов и установленного пакета. Для Postgres, OpenSearch или Phoenix добавьте
соответствующую extra-зависимость. Например, для опубликованного релиза:

```sh
python -m pip install "gpt2giga[postgres]"
```

При установке из текущего checkout используйте `python -m pip install ".[postgres]"`.

Preview-образы Python 3.15 публикуются для `linux/amd64` и `linux/arm64`:

```sh
docker pull gigateam/gpt2giga:0.3.1-preview
docker pull ghcr.io/ai-forever/gpt2giga:0.3.1-preview
```

Тег `preview` отслеживает текущую preview-сборку. Теги `latest` и `0.3.1`
используют Python 3.13. Для локальной сборки preview:
`docker build --build-arg PYTHON_VERSION=3.15 -t gpt2giga:preview .`.


Минимальный OpenAI SDK вызов:

```python
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 вызов:

```python
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](https://ai-forever.github.io/gpt2giga/quickstart).

## Документация

Полная документация публикуется на [GitHub Pages](https://ai-forever.github.io/gpt2giga/).

Локально проверить docs можно через Docusaurus wrapper в `docs-site/`:

```sh
make docs-install
make docs
```

После `make docs` сайт доступен на `http://127.0.0.1:3000/` и включает локали `en`/`ru`.
Для быстрой разработки с hot reload:

```sh
make docs-dev
```

Docusaurus dev server обслуживает одну локаль за запуск. Для русского dev preview:

```sh
make docs-dev-ru
```

Чтобы проверить переключатель языков между `en` и `ru`, используйте full preview через `make docs` или `make docs-preview`.

| Тема | Документ |
|---|---|
| Быстрый запуск и первые запросы | [Quickstart](https://ai-forever.github.io/gpt2giga/quickstart) |
| Codex, Claude Code и Gemini CLI через `/v1/chat/completions` | [Chat Completions bridge](https://ai-forever.github.io/gpt2giga/chat-completions-bridge) |
| Что поддерживается, отключено или намеренно игнорируется | [API compatibility](https://ai-forever.github.io/gpt2giga/api-compatibility) |
| Совместимость SDK `extra_*` и параметров клиентов | [Client parameter compatibility](https://ai-forever.github.io/gpt2giga/client-parameter-compatibility) |
| Встроенные инструменты GigaChat и маппинг OpenAI/Anthropic/Gemini | [Built-in tools](https://ai-forever.github.io/gpt2giga/builtin-tools) |
| Переменные окружения, CLI flags, backend modes | [Configuration](https://ai-forever.github.io/gpt2giga/configuration) |
| Docker Compose, Traefik, Postgres, OpenSearch, Phoenix, production hardening | [Deployment](https://ai-forever.github.io/gpt2giga/deployment) |
| Logs, metrics, traffic logs, admin API, debug translation | [Operations](https://ai-forever.github.io/gpt2giga/operations) |
| Live GigaChat integration tests | [Live integration tests](https://ai-forever.github.io/gpt2giga/live-integration-tests) |
| Внутренняя архитектура normalized messages | [Normalized messages](https://ai-forever.github.io/gpt2giga/architecture/normalized-messages) |
| Checklist для добавления provider/protocol | [How to add a provider](https://ai-forever.github.io/gpt2giga/architecture/how-to-add-provider) |
| Редакторы, агенты, SDK examples, reverse proxies | [Integrations](https://ai-forever.github.io/gpt2giga/integrations) |
| Runnable-примеры | [Examples](https://github.com/ai-forever/gpt2giga/tree/main/examples) |
| История изменений gateway | [RU](https://github.com/ai-forever/gpt2giga/blob/main/CHANGELOG.md) · [EN](https://github.com/ai-forever/gpt2giga/blob/main/CHANGELOG_en.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;
- Gemini-compatible `/v1beta/models/{model}:generateContent`, `:streamGenerateContent`, `:countTokens`, `:embedContent`, `:batchEmbedContents`, а также `/v1beta/models`;
- LiteLLM-compatible `GET /model/info`;
- системные endpoints `GET /health` и `GET|POST /ping`.

Дополнительно подключены Files/Batches трёх протоколов, Responses input_tokens,
узкий Images generations и native utilities. Cancel/delete batch не поддерживаются.
Для batch срок 24h означает срок принятия результатов шлюзом: без poll до срока
даже завершённая native job может быть признана expired; upstream job может
продолжиться и тарифицироваться. Полной vendor batch parity нет.
Responses snapshots и Conversations доступны opt-in через
`GPT2GIGA_RESPONSES_STORAGE_MODE=gateway`; default `native` сохраняет thread continuation.
См. [API compatibility](https://ai-forever.github.io/gpt2giga/api-compatibility).

Сейчас не является целью проекта:

- полная 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;
- полная Gemini parity для Files, batchGenerateContent, cached content, Vertex/RAG tools и non-text embeddings content.

## Деплой

Docker Compose manifests лежат в [deploy/](https://github.com/ai-forever/gpt2giga/tree/main/deploy).
Для запуска опубликованного образа `latest`:

```sh
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*`:

```dotenv
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](https://ai-forever.github.io/gpt2giga/deployment).

Для GigaChat встроен публичный Russian Trusted Root CA: при
`GIGACHAT_VERIFY_SSL_CERTS=True` вручную устанавливать его не нужно.
Явный CA bundle или SSL context имеет приоритет; отключить добавление можно через
`GIGACHAT_USE_BUNDLED_CA=False`. Для клиентов с union-схемами инструментов
(например, Hermes Agent) доступна опция `GPT2GIGA_NORMALIZE_TOOL_SCHEMAS=True`.
Она применяется только к моделям GigaChat-2 на `https://api.giga.chat/v1`
и преобразует схемы с потерей части ограничений; по умолчанию выключена.
На других адресах, включая `staging.example.com` и
`gateway.example.com`, а также для GigaChat-3 схемы не меняются.
Подробнее — [Configuration](https://ai-forever.github.io/gpt2giga/configuration).

## Структура Репозитория

| Path | Назначение |
|---|---|
| `src/gpt2giga/` | FastAPI app, routers, protocol transforms, config, middleware |
| `tests/` | Unit, router, protocol, sink и integration tests |
| `examples/` | Runnable OpenAI, Anthropic, Gemini, embeddings and agents examples; documented Files/Batches subsets use real backend execution |
| `docs/` | Markdown-контент пользовательской документации и architecture notes |
| `docs-site/` | Docusaurus wrapper, sidebar/theme config и npm tooling для GitHub Pages |
| `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 |

## Разработка

Установить зависимости:

```sh
uv sync --all-extras --dev
```

Запустить сервис:

```sh
uv run gpt2giga
```

Сборка дистрибутива выполняется явно:

```sh
uv build
```

Проверки перед PR:

```sh
uv run ruff check .
uv run ruff format --check .
uv run pytest tests/ --cov=. --cov-report=term --cov-fail-under=80
```

Live-тесты с реальными вызовами GigaChat запускаются отдельно и требуют
локальных секретов: см. [Live GigaChat Integration Tests](https://ai-forever.github.io/gpt2giga/live-integration-tests).

Используйте Conventional Commits (`feat:`, `fix:`, `docs:`, `refactor:`, `test:`, `ci:`) и сверяйтесь с [PR template](https://github.com/ai-forever/gpt2giga/blob/main/.github/PULL_REQUEST_TEMPLATE.md).

## Проверка кандидата 0.3.3a1

Кандидат из checkout не объявляется опубликованным релизом. Для проверки wheel:

```sh
uv build --no-sources
uv venv /tmp/gpt2giga-candidate
uv pip install --python /tmp/gpt2giga-candidate/bin/python dist/gpt2giga-0.3.3a1-py3-none-any.whl
/tmp/gpt2giga-candidate/bin/gpt2giga --help
```

SDK использует native HTTPX2 по умолчанию. `GIGACHAT_ASYNC_BACKEND=aiohttp`
включает альтернативный backend; GigaChat v1 остаётся default, v2 — opt-in.
Alpha-образы получают versioned/preview теги, не обновляя `latest` или стабильные
Python aliases. Публикация кандидата — отдельный шаг.
