gigachat

0
3 месяца назад
3 месяца назад
3 месяца назад
3 месяца назад
3 месяца назад
3 месяца назад
3 года назад
3 месяца назад
3 месяца назад
3 месяца назад
README.md

GigaChat Python SDK

PyPI version Python versions License CI Downloads

Python SDK for the GigaChat REST API — a large language model.

This library is part of GigaChain and powers langchain-gigachat, the official LangChain integration for GigaChat.

Table of Contents

Features

  • Chat completions — synchronous and asynchronous
  • Streaming responses — real-time token generation
  • Embeddings — text vectorization
  • Function calling — tool use for building agents
  • Vision — image understanding (multimodal)
  • File operations — upload, retrieve, and delete files
  • Token counting — estimate token usage before requests
  • Multiple auth methods — OAuth credentials, password, TLS certificates, access tokens
  • Automatic retry — configurable exponential backoff for transient errors
  • Fully typed — Pydantic V2 models with
    py.typed
    marker for IDE support

Installation

Requirements: Python 3.8 — 3.13

Note: In production, keep TLS verification enabled (default). See SSL Certificates for setup instructions.

Quick Start

Get your GigaChat authorization key

For detailed instructions, see the official documentation.

Configure gigachat package to use TLS certificate

TLS certificate: follow the OS-specific installation steps on Gosuslugi (see SSL Certificates for how to configure

GIGACHAT_CA_BUNDLE_FILE
/
ca_bundle_file
if needed).

Development-only (not recommended):

set

GIGACHAT_VERIFY_SSL_CERTS=false
or pass
verify_ssl_certs=False
to
GigaChat(...)
.

Usage Examples

The examples below assume authentication is configured via environment variables (for example,

GIGACHAT_CREDENTIALS
). See Authentication.

Basic Chat

Streaming

Receive tokens as they are generated:

Async

Use async/await for non-blocking operations:

Embeddings

Generate vector representations of text:

Note: The

model
parameter must be passed directly to the
embeddings()
method (default:
"Embeddings"
). The
model
set in the
GigaChat()
constructor does not affect embeddings.

Function Calling

Enable the model to call functions (tools):

More examples

See the examples/ folder for complete working examples including chat, functions, context variables, AI detection, and vision.

Configuration

Constructor Parameters

ParameterTypeDefaultDescription
credentials
str
None
Authorization key from GigaChat API
scope
str
GIGACHAT_API_PERS
API scope (see below)
model
str
GigaChat
Default model for requests
base_url
str
https://gigachat.devices.sberbank.ru/api/v1
API base URL
auth_url
str
https://ngw.devices.sberbank.ru:9443/api/v2/oauth
OAuth token endpoint
access_token
str
None
Pre-obtained access token (bypasses OAuth)
user
str
None
Username for password authentication
password
str
None
Password for password authentication
verify_ssl_certs
bool
True
Verify SSL certificates
ca_bundle_file
str
None
Path to CA certificate bundle
cert_file
str
None
Path to client certificate (for mTLS)
key_file
str
None
Path to client private key (for mTLS)
key_file_password
str
None
Password for encrypted private key
timeout
float
30.0
Request timeout in seconds
max_connections
int
None
Maximum concurrent connections
max_retries
int
0
Maximum retry attempts for transient errors
retry_backoff_factor
float
0.5
Exponential backoff multiplier
retry_on_status_codes
tuple
(429, 500, 502, 503, 504)
HTTP status codes that trigger retry
profanity_check
bool
None
Enable profanity filtering
flags
list
None
Additional API flags

API Scopes:

ScopeDescription
GIGACHAT_API_PERS
API for individuals (default)
GIGACHAT_API_B2B
API for businesses (prepaid)
GIGACHAT_API_CORP
API for businesses (postpaid)

Environment Variables

All parameters can be configured via environment variables with the

GIGACHAT_
prefix:

Then create a client without any parameters:

Authentication

The library supports four authentication methods:

Authentication priority (when multiple are configured)

If multiple auth inputs are provided at the same time, the SDK applies this priority:

  1. custom_headers_cvar["Authorization"]
    (if set) — overrides any other auth source.
  2. authorization_cvar
    (if set) — overrides any other auth source and disables automatic token fetching/refresh (you manage the header value and its lifecycle).
  3. Explicit
    access_token
    (constructor parameter /
    GIGACHAT_ACCESS_TOKEN
    ) — used as-is. If it fails with 401 and OAuth credentials or user/password are also configured, the SDK will fall back to fetching a new token.
  4. OAuth
    credentials
    (constructor parameter /
    GIGACHAT_CREDENTIALS
    ) — used to obtain/refresh a token.
  5. Username/password (
    user
    +
    password
    ) — used to obtain/refresh a token from the
    /token
    endpoint.

When both OAuth

credentials
and username/password are provided, OAuth credentials take precedence for token refresh.

For detailed instructions, see the official documentation.

The authorization key encodes your API scope. If using the B2B or CORP API, specify the scope explicitly:

2. Username and Password

Authenticate with a username and password:

3. TLS Certificates (mTLS)

Authenticate using client certificates for mutual TLS:

4. Access Token

Use a pre-obtained access token (JWT):

Note: Access tokens expire after 30 minutes. Use this method when you manage token lifecycle externally.

Pre-authentication

By default, the library obtains an access token on the first API request. To authenticate immediately:

SSL Certificates

GigaChat endpoints use a certificate chain issued by the Russian Ministry of Digital Development. This section explains how to configure the GigaChat SDK to use the required certificates.

Quick Reference

  • What you need: The "Russian Trusted Root CA" certificate file from Gosuslugi
  • How to configure: Set
    GIGACHAT_CA_BUNDLE_FILE
    environment variable or pass
    ca_bundle_file
    argument to
    GigaChat()
  • Why: Python HTTP clients typically use their own CA bundle (e.g.,
    certifi
    ) instead of the OS trust store

Configuration

Environment variable (recommended):

Or as argument:

OS-Specific Notes

Download the "Russian Trusted Root CA" certificate from Gosuslugi and configure

GIGACHAT_CA_BUNDLE_FILE
to point to the downloaded file:

  • Windows: Downloaded as
    .cer
    file (e.g.,
    Russian Trusted Root CA.cer
    )
  • macOS/Linux: Downloaded as
    .crt
    file (e.g.,
    Russian_Trusted_Root_CA.crt
    )

Example paths:

  • Environment variable:
    GIGACHAT_VERIFY_SSL_CERTS=false
  • Or pass
    verify_ssl_certs=False
    to
    GigaChat(...)

⚠️ Warning: Disabling certificate verification reduces security and is not recommended for production environments.

Error Handling

The library raises specific exceptions for different error conditions:

Exception Reference

ExceptionHTTP StatusDescription
GigaChatException
Base exception for all library errors
ResponseError
Base exception for HTTP response errors
AuthenticationError
401Invalid or expired credentials
BadRequestError
400Malformed request or invalid parameters
ForbiddenError
403Access denied (insufficient permissions)
NotFoundError
404Requested resource not found
RequestEntityTooLargeError
413Request payload too large
RateLimitError
429Too many requests (use
e.retry_after
)
ServerError
5xxServer-side error

Advanced Features

Context Variables

Track requests with custom headers for logging and debugging:

Available context variables:

VariableHeaderDescription
session_id_cvar
X-Session-ID
Session identifier for grouping requests
request_id_cvar
X-Request-ID
Unique request identifier
client_id_cvar
X-Client-ID
Client identifier
custom_headers_cvar
(various)Dictionary of additional headers

Header precedence (when multiple sources set the same header):

  • Explicit
    access_token
    passed by the SDK (or your code) sets
    Authorization: Bearer ...
    first.
  • authorization_cvar
    overrides that
    Authorization
    header if it is set.
  • custom_headers_cvar
    is applied last and overrides both (including
    Authorization
    ), as well as any other header.

Retry Configuration

Configure automatic retry with exponential backoff for transient errors:

Avoid “double retry” (important): If you use

gigachat
through a higher-level library that also retries (for example,
langchain-gigachat
/ LangChain), enable retries in only one layer. Otherwise, the effective number of attempts multiplies (e.g., 3 SDK retries × 3 framework retries).

Recommended defaults:

  • Keep
    gigachat
    retries disabled (default
    max_retries=0
    ) when the outer framework retries.
  • Or disable retries in the outer framework and configure retries here (recommended if you want one consistent retry policy).

Deprecations

  • Messages.data_for_context
    : deprecated by the upstream API. Do not use it in new code.
    • Use instead: include the relevant information directly in the message
      content
      , or attach files via
      attachments
      (file IDs) when you need to provide additional context.
    • Timeline: the SDK will keep accepting
      data_for_context
      through the
      0.x
      line, but it may be removed in
      1.0.0
      (or earlier if the upstream API removes it).

Token Counting

Estimate token usage before sending requests:

Available Models

List available models and their capabilities:

File Operations

Upload and manage files:

Balance Check

Check your remaining token balance (prepaid accounts only):

API Reference

  • GigaChain — A set of solutions for developing Russian-language LLM applications and multi-agent systems, with support for LangChain, LangGraph, LangChain4j, as well as GigaChat and other available LLMs. GigaChain covers the full development lifecycle: from prototyping and research to production deployment and ongoing support.
  • langchain-gigachat — Official LangChain integration package for GigaChat

Versioning and stability

This project follows SemVer with additional clarity for pre-

1.0.0
releases:

  • Patch releases (
    0.x.Y
    )
    : Backwards compatible bug fixes and internal changes.
  • Minor releases (
    0.X.0
    )
    : May include backwards-incompatible changes. Any breaking changes must be called out in the GitHub Release notes.

Stable release gate

To ship a release marked Production/Stable, the following must be true:

  • CI is green on
    main
    (lint, mypy, unit tests, integration replay).
  • Local checks are green (
    make all
    ).
  • Packaging is sane: sdist+wheel build and install from artifacts works (no missing files).
  • Integration cassettes are current: re-recorded with real credentials and reviewed for scrubbing.

Contributing

We welcome contributions of all kinds — bug reports, feature requests, documentation improvements, and code contributions!

Quick Start:

For detailed contributing guidelines, please see CONTRIBUTING.md.

This guide covers:

  • Development setup and workflow
  • Code quality standards and testing
  • Commit message guidelines
  • Pull request process
  • Issue reporting guidelines
  • Project architecture

All contributions are licensed under the MIT License.

License

This project is licensed under the MIT License.

Copyright © 2026 GigaChain