GigaChat Python SDK

repository·main·Indexed 41 days ago

https://github.com/ai-forever/gigachat

A Python library for interacting with the GigaChat REST API. It provides high-level interfaces for chat completions, streaming, embeddings, function calling, and multimodal vision tasks. The SDK supports synchronous and asynchronous operations, structured output via Pydantic or JSON schema, and integrated tools such as web search and code interpretation. Version 0.2.3 requires Python 3.8 through 3.13.

Tokens
29K
Snippets
80
Records
110
Agent score
49%

What's inside GigaChat

  1. Chat Completion request styles

    main

    The SDK supports several ways to interact with chat models:

    • Synchronous Chat: Use client.chat.create(...) for standard completions and client.chat.stream(...) for streaming responses.
    • Asynchronous Chat: Use GigaChatAsyncClient with client.achat.create(...) for async completions and client.achat.stream(...) for async SSE (Server-Sent Events) streaming.
    • Model Tuning: You can configure temperature, top_p, and token limits. For v2 chat requests, you can use reasoning.effort to control reasoning capabilities.
    • Thread Management: Reuse storage.thread_id between requests to maintain conversation context.
  2. Use Tools and Function Calling

    main

    The SDK supports tool use and function calling:

    • Function Calling: Provide client functions that the model can call, and handle the follow-up response.
    • Forced Function Call: Use tool_config.mode="forced" to ensure the model calls a specific function.
    • Built-in Tools:
      • web_search: Perform web searches (can be configured via search options or forced via tool_config.tool_name).
      • code_interpreter: Execute code within the model environment.
      • url_content_extraction: Extract content from provided URLs.
      • image_generate: Generate images (returns generated file IDs).
  3. Manage Files and Assistants

    main

    For complex workflows, use the Files and Assistants features:

    • File Input: Upload a file and reference it within your message content to provide context to the model.
    • Assistants: Manage the lifecycle of an assistant (create, use, and delete) to maintain stateful interactions.
  4. Use v2 features: Tool calling and advanced options

    main

    The v2 contract is the recommended target for integrations requiring advanced features. These features are modeled natively in the primary request/response structure.

    Supported v2 features include:

    • Function calling
    • Built-in tools (e.g., web search)
    • Assistant-based stateful conversations
    • Thread storage
    • Richer response metadata

    New explicit request fields in v2:

    • tools
    • tool_config
    • assistant_id
    • storage
    • ranker_options
    • user_info
  5. Track requests with Context Variables

    main

    You can inject custom headers into your GigaChat requests for logging, debugging, or tracing using context variables. These variables allow you to set identifiers that will be sent as HTTP headers in subsequent API calls made by the client.

    Header Precedence:

    1. custom_headers_cvar (Highest - overrides everything)
    2. authorization_cvar (Overrides explicit access_token)
    3. Explicit access_token (Lowest)

    Available context variables:

    VariableHeaderDescription
    session_id_cvarX-Session-IDSession identifier for grouping requests
    request_id_cvarX-Request-IDUnique request identifier
    client_id_cvarX-Client-IDClient identifier
    service_id_cvarX-Service-IDService identifier
    operation_id_cvarX-Operation-IDOperation identifier
    trace_id_cvarX-Trace-IDProcess instance identifier (main operation)
    agent_id_cvarX-Agent-IDAgent identifier
    custom_headers_cvar(various)Dictionary of additional headers
    from gigachat import GigaChat, session_id_cvar, request_id_cvar, custom_headers_cvar
    import uuid
    
    # Set session and request identifiers
    session_id_cvar.set("user-session-12345")
    request_id_cvar.set(str(uuid.uuid4()))
    
    # Or add custom headers
    custom_headers_cvar.set({"X-Custom-Header": "custom-value"})
    
    with GigaChat() as client:
        response = client.chat.create("Hello!")
  6. How the GigaChat chat API surface works (Migration Guide)

    main

    The SDK has transitioned to a new primary chat/completions surface. While old root compatibility methods (shims) still work without warnings, it is recommended to use the new structured API.

    New Primary Surface

    • Synchronous: client.chat.create(...), client.chat.stream(...), client.chat.parse(...)
    • Asynchronous: await client.achat.create(...), client.achat.stream(...), await client.achat.parse(...)

    Legacy Compatibility Shims

    • Synchronous: client.chat(...), client.stream(...), client.chat_parse(...)
    • Asynchronous: await client.achat(...), client.astream(...), await client.achat_parse(...)

    Model Migration

    When migrating, replace legacy imports like gigachat.models.Chat* with the new primary models: ChatCompletionRequest, ChatCompletionResponse, ChatMessage, and related Chat* models.

    # New primary way to create a chat completion
    response = client.chat.create("Hello!")
    
    # New primary way to stream
    for chunk in client.chat.stream("Hello!"): ...
    
    # New primary way to parse structured output
    completion, parsed = client.chat.parse("Solve 2+2", response_format=MySchema)
  7. Authenticate with GigaChat

    main

    The SDK supports four authentication methods. If multiple are provided, they follow this priority:

    1. custom_headers_cvar["Authorization"] (overrides everything)
    2. authorization_cvar (overrides others and disables automatic token refresh)
    3. Explicit access_token (if it fails with 401, SDK falls back to OAuth or User/Pass)
    4. OAuth credentials (used to obtain/refresh token)
    5. Username/password (used to obtain/refresh token)

    Use your authorization key. Specify the scope if using B2B or CORP.

    2. Username and Password

    Requires an explicit base_url that supports the /token endpoint (e.g., https://gigachat.devices.sberbank.ru/api/v1).

    3. TLS Certificates (mTLS)

    Use client certificates for mutual TLS.

    4. Access Token

    Use a pre-obtained JWT. Note that access tokens expire after 30 minutes; use this if you manage the lifecycle externally.

    # 1. Authorization Key
    client = GigaChat(credentials="<your_authorization_key>", scope="GIGACHAT_API_B2B")
    
    # 2. Username and Password
    client = GigaChat(base_url="https://gigachat.devices.sberbank.ru/api/v1", user="<username>", password="<password>")
    
    # 3. TLS Certificates (mTLS)
    client = GigaChat(base_url="https://gigachat.devices.sberbank.ru/api/v1", cert_file="certs/client.pem", key_file="certs/client.key")
    
    # 4. Access Token
    client = GigaChat(access_token="<your_access_token>")
  8. Generate structured output

    main

    You can constrain the model's output to specific formats using the response_format parameter:

    • Pydantic Parsing: Use client.chat.parse(...) with a Pydantic model to automatically parse the response into a structured object.
    • JSON Schema: Set response_format.type="json_schema" to enforce a specific JSON structure.
    • Regex Format: Set response_format.type="regex" to constrain the output to a specific regular expression pattern.
  9. Stay on the previous contract (Compatibility Mode)

    main

    If you are not ready to migrate your request/response handling, you can continue using the root compatibility methods. This is useful if your code relies heavily on the choices[0].message.content structure or if you have many downstream consumers expecting the old chunk shapes.

    Compatibility methods:

    • Sync: client.chat(payload), client.stream(payload), client.chat_parse(payload, ...)
    • Async: client.achat(payload), client.astream(payload), client.achat_parse(payload, ...)
    # Staying on the previous contract
    response = client.chat(payload)
    
    for chunk in client.stream(payload):
        ...
    
    completion, parsed = client.chat_parse(
        payload,
        response_format=MathAnswer,
    )
  10. Configure GigaChat environment variables

    main

    The GigaChat SDK uses load_dotenv() to load configuration. You can provide settings via environment variables or an .env file. Two settings are required for the examples to run:

    1. Credentials: Use either GIGACHAT_CREDENTIALS or GIGACHAT_ACCESS_TOKEN.
    2. Model: Set GIGACHAT_MODEL. The SDK does not have a default model; if you do not specify a model in your code and this variable is missing, the SDK will raise a ModelNotSpecifiedError. You can use client.get_models() to list available models.
    # Example .env content
    GIGACHAT_CREDENTIALS="your_credentials"
    GIGACHAT_MODEL="your_model_name"