### Minimal Docstring Example Source: https://github.com/ai-forever/gigachat/blob/main/CONTRIBUTING.md Example of a function using a minimal, one-line docstring for its summary. This style is common for most functions where type hints provide parameter details. ```python def chat_sync( client: httpx.Client, *, chat: Chat, access_token: Optional[str] = None, ) -> ChatCompletion: """Return a model response based on the provided messages.""" # Implementation here ``` -------------------------------- ### Python Type Hinting Example Source: https://github.com/ai-forever/gigachat/blob/main/CONTRIBUTING.md Example demonstrating the use of type hints for function parameters and return values, adhering to PEP 8 and Python 3.8+ conventions. Type hints are required for all functions and methods. ```python from typing import Optional, List def process_messages( messages: List[str], max_tokens: Optional[int] = None, ) -> List[str]: """Process a list of messages.""" return [msg.strip() for msg in messages] ``` -------------------------------- ### Extended Docstring Example for Complex APIs Source: https://github.com/ai-forever/gigachat/blob/main/CONTRIBUTING.md Example of an extended docstring for complex methods, including an 'Args:' section to describe parameters. This is optional and typically used when more detailed explanations are necessary. ```python def complex_method( self, param1: str, param2: Optional[int] = None, ) -> Result: """Perform a complex operation. Args: param1: Description of first parameter. param2: Description of optional parameter. """ # Implementation ``` -------------------------------- ### Embeddings Function Docstring Example Source: https://github.com/ai-forever/gigachat/blob/main/CONTRIBUTING.md Example of a function docstring for generating embeddings. It follows the convention of a concise one-line summary, relying on type hints for parameter information. ```python def get_embeddings( texts: List[str], model: str = "GigaChat-Embeddings", ) -> List[List[float]]: """Generate embeddings for a list of texts.""" # Implementation here ``` -------------------------------- ### Run All Unit Tests Source: https://github.com/ai-forever/gigachat/blob/main/CONTRIBUTING.md Execute all unit tests, including coverage checks. This is the default test command. ```bash make test ``` -------------------------------- ### Run Integration Tests Source: https://github.com/ai-forever/gigachat/blob/main/CONTRIBUTING.md Execute integration tests. This command requires credentials or will use committed VCR cassettes for replay. ```bash make test-integration ``` -------------------------------- ### Set GigaChat Credentials and Scope Source: https://github.com/ai-forever/gigachat/blob/main/examples/example_contextvars.ipynb Sets up GigaChat credentials and scope from environment variables, prompting the user if they are not set. ```python if "GIGACHAT_CREDENTIALS" not in os.environ: os.environ["GIGACHAT_CREDENTIALS"] = getpass.getpass("GigaChat Credentials: ") if "GIGACHAT_SCOPE" not in os.environ: os.environ["GIGACHAT_SCOPE"] = getpass.getpass("GigaChat Scope: ") ``` -------------------------------- ### Run Code Formatting and Linting Source: https://github.com/ai-forever/gigachat/blob/main/CONTRIBUTING.md Automatically format code according to project standards and check for style issues using Ruff. These commands help maintain code consistency and quality. ```bash make fmt # Auto-format code make lint # Check for style issues ``` -------------------------------- ### Configure GigaChat with CA Bundle File Argument Source: https://github.com/ai-forever/gigachat/blob/main/README.md Initialize the GigaChat client and specify the path to the root CA certificate file using the `ca_bundle_file` argument. This is an alternative to setting the environment variable for SSL certificate configuration. ```python from gigachat import GigaChat with GigaChat(ca_bundle_file="") as client: response = client.chat("Hello!") print(response.choices[0].message.content) ``` -------------------------------- ### Run Tests with Verbose Output Source: https://github.com/ai-forever/gigachat/blob/main/CONTRIBUTING.md Execute tests and display detailed output for each test case. Helpful for understanding test execution flow. ```bash uv run pytest -v ``` -------------------------------- ### Run Pre-commit Hooks Source: https://github.com/ai-forever/gigachat/blob/main/CONTRIBUTING.md Manually run pre-commit hooks on all files to ensure code quality before committing. This is useful for checking formatting, linting, and type checking. ```bash make pre # Or: pre-commit run --all-files ``` -------------------------------- ### View Changes Before Submitting Source: https://github.com/ai-forever/gigachat/blob/main/CONTRIBUTING.md Review the differences between your current branch and the main branch. This helps in understanding the scope of changes and identifying potential conflicts. ```bash git diff main...your-branch ``` -------------------------------- ### Initialize GigaChat with Access Token Source: https://github.com/ai-forever/gigachat/blob/main/README.md Instantiate the GigaChat client using a pre-obtained JWT access token. Access tokens expire after 30 minutes, so this method is suitable when managing the token lifecycle externally. ```python from gigachat import GigaChat client = GigaChat(access_token="") ``` -------------------------------- ### Pre-authenticate GigaChat with Credentials Source: https://github.com/ai-forever/gigachat/blob/main/README.md Initialize the GigaChat client with authorization credentials to obtain an access token immediately. This is useful for authenticating upfront before the first API request. ```python from gigachat import GigaChat client = GigaChat(credentials="") token = client.get_token() # Authenticate now print(f"Token expires at: {token.expires_at}") ``` -------------------------------- ### Test Chat Completion (Integration) Source: https://github.com/ai-forever/gigachat/blob/main/CONTRIBUTING.md Integration test for chat completion using real API interactions recorded with VCR. Requires valid credentials or uses existing cassettes. ```python import pytest from gigachat import GigaChat, ChatCompletion @pytest.mark.integration @pytest.mark.vcr def test_chat_integration(gigachat_client: GigaChat) -> None: """Test chat completion with real API.""" result = gigachat_client.chat("Say hello") assert isinstance(result, ChatCompletion) assert result.choices is not None assert len(result.choices) > 0 ``` -------------------------------- ### Import Libraries for GigaChat Context Source: https://github.com/ai-forever/gigachat/blob/main/examples/example_contextvars.ipynb Import necessary libraries for asynchronous operations, environment variables, and the GigaChat client, including its context module. ```python import asyncio import os import getpass import gigachat.context from gigachat import GigaChat ``` -------------------------------- ### Run All Quality Checks Source: https://github.com/ai-forever/gigachat/blob/main/CONTRIBUTING.md Execute all quality assurance checks, including linting, type checking, and tests. This command ensures the code adheres to project standards before submission. ```bash make all ``` -------------------------------- ### Update to Latest GigaChat Version Source: https://github.com/ai-forever/gigachat/blob/main/CONTRIBUTING.md Ensure you are testing with the most recent version of the GigaChat library. This is a preliminary step to verify if an issue persists in the latest release. ```bash pip install --upgrade gigachat ``` -------------------------------- ### Run All Automated Checks Source: https://github.com/ai-forever/gigachat/blob/main/CONTRIBUTING.md Execute all automated checks, including formatting, linting, type checking, and unit tests, with a single command. This ensures the entire codebase meets quality standards. ```bash make all # Run all checks together ``` -------------------------------- ### Push Branch to Fork Source: https://github.com/ai-forever/gigachat/blob/main/CONTRIBUTING.md Push your feature branch to your personal fork on GitHub to prepare for opening a pull request. ```bash git push origin feature/your-feature-name ``` -------------------------------- ### Set Context Variables for Sync Client Source: https://github.com/ai-forever/gigachat/blob/main/examples/example_contextvars.ipynb Configures context variables for GigaChat requests, including session, request, service, operation, trace, agent IDs, and custom headers, within a synchronous client context. ```python headers = { "X-Session-ID": "8324244b-7133-4d30-a328-31d8466e5502", "X-Request-ID": "8324244b-7133-4d30-a328-31d8466e5502", "X-Service-ID": "my_custom_service", "X-Operation-ID": "my_custom_qna", "X-Trace-ID": "trace-id-1234567890", "X-Agent-ID": "agent-id-1234567890", } # Setting context variables for the client with GigaChat(verify_ssl_certs=False) as giga: gigachat.context.session_id_cvar.set(headers.get("X-Session-ID")) gigachat.context.request_id_cvar.set(headers.get("X-Request-ID")) gigachat.context.service_id_cvar.set(headers.get("X-Service-ID")) gigachat.context.operation_id_cvar.set(headers.get("X-Operation-ID")) gigachat.context.trace_id_cvar.set(headers.get("X-Trace-ID")) gigachat.context.agent_id_cvar.set(headers.get("X-Agent-ID")) gigachat.context.custom_headers_cvar.set({"X-Custom-Header": "CustomValue"}) response = giga.chat("Who are you?") print(response) ``` -------------------------------- ### Run Individual Automated Checks Source: https://github.com/ai-forever/gigachat/blob/main/CONTRIBUTING.md Run specific automated checks individually, such as formatting with Ruff, linting, type checking with mypy, and unit tests. This allows for targeted quality assurance. ```bash make fmt # Auto-format with Ruff make lint # Ruff linting make mypy # Type checking make test # Unit tests ``` -------------------------------- ### Run Specific Test File Source: https://github.com/ai-forever/gigachat/blob/main/CONTRIBUTING.md Execute tests within a specific file. Useful for focusing on a particular module. ```bash uv run pytest tests/unit/gigachat/test_client_chat.py ``` -------------------------------- ### Run Tests Matching a Pattern Source: https://github.com/ai-forever/gigachat/blob/main/CONTRIBUTING.md Execute tests whose names match a given pattern. Useful for running a subset of tests related to a specific feature or bug. ```bash uv run pytest -k "test_retry" ``` -------------------------------- ### Address Review Feedback Source: https://github.com/ai-forever/gigachat/blob/main/CONTRIBUTING.md Make requested changes during a review by adding new commits. Avoid force-pushing during an active review to allow maintainers to see the evolution of changes. ```bash # Make changes git add . git commit -m "address review feedback" git push origin feature/your-feature-name ``` -------------------------------- ### Handle GigaChat SDK Exceptions Source: https://github.com/ai-forever/gigachat/blob/main/README.md Implement a try-except block to catch and handle various GigaChat-specific exceptions, such as authentication errors, rate limits, bad requests, and server errors. This allows for graceful error management in your application. ```python from gigachat import GigaChat from gigachat.exceptions import ( GigaChatException, AuthenticationError, RateLimitError, BadRequestError, ForbiddenError, NotFoundError, RequestEntityTooLargeError, UnprocessableEntityError, ServerError, ) try: with GigaChat() as client: response = client.chat("Hello!") print(response.choices[0].message.content) except AuthenticationError as e: print(f"Authentication failed: {e}") except RateLimitError as e: print(f"Rate limited. Retry after {e.retry_after} seconds") except BadRequestError as e: print(f"Invalid request: {e}") except ForbiddenError as e: print(f"Access denied: {e}") except NotFoundError as e: print(f"Resource not found: {e}") except RequestEntityTooLargeError as e: print(f"Request payload too large: {e}") except UnprocessableEntityError as e: print(f"Request validation failed: {e}") except ServerError as e: print(f"Server error: {e}") except GigaChatException as e: print(f"GigaChat error: {e}") ``` -------------------------------- ### Test Basic Chat Completion (Sync) Source: https://github.com/ai-forever/gigachat/blob/main/CONTRIBUTING.md Unit test for the synchronous chat completion method. Mocks HTTP responses using `pytest-httpx` to verify logic and model parsing. ```python import pytest from pytest_httpx import HTTPXMock from gigachat import GigaChat from gigachat.models import ChatCompletion def test_chat_completion(httpx_mock: HTTPXMock) -> None: """Test basic chat completion.""" # Mock the response httpx_mock.add_response( method="POST", url="https://gigachat.devices.sberbank.ru/api/v1/chat/completions", json={ "choices": [ { "message": {"role": "assistant", "content": "Hello!"}, "index": 0, "finish_reason": "stop", } ], "model": "GigaChat", "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}, }, ) # Test the method with GigaChat(credentials="test", verify_ssl_certs=False) as client: result = client.chat("Hello") assert isinstance(result, ChatCompletion) assert result.choices[0].message.content == "Hello!" ``` -------------------------------- ### Run Specific Test Function Source: https://github.com/ai-forever/gigachat/blob/main/CONTRIBUTING.md Execute a single test function within a file. Ideal for debugging or testing a specific scenario. ```bash uv run pytest tests/unit/gigachat/test_client_chat.py::test_chat_completion ``` -------------------------------- ### Disable SSL Certificate Verification in GigaChat Source: https://github.com/ai-forever/gigachat/blob/main/README.md Instantiate the GigaChat client with `verify_ssl_certs=False` to disable TLS certificate verification. This is not recommended for production environments due to security implications. ```python from gigachat import GigaChat client = GigaChat(verify_ssl_certs=False) ``` -------------------------------- ### Update Fork with Upstream Changes Source: https://github.com/ai-forever/gigachat/blob/main/CONTRIBUTING.md Synchronize your local fork with the upstream repository to incorporate the latest changes. This involves adding the upstream remote if not already present, fetching changes, and merging them into your main branch. ```bash # Add upstream remote (one-time setup) git remote add upstream https://github.com/ai-forever/gigachat.git # Fetch and merge upstream changes git fetch upstream git checkout main git merge upstream/main # Push to your fork git push origin main ``` -------------------------------- ### Set Context Variables for GigaChat Requests Source: https://github.com/ai-forever/gigachat/blob/main/README.md Utilize context variables like `session_id_cvar`, `request_id_cvar`, and `custom_headers_cvar` to set custom headers for requests, aiding in logging and debugging. This allows for tracking requests with unique identifiers. ```python 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())) ``` -------------------------------- ### Run Mypy Type Checking Source: https://github.com/ai-forever/gigachat/blob/main/CONTRIBUTING.md Execute mypy in strict mode to perform static type checking on the codebase. This ensures that type hints are correctly used and that the code adheres to type safety standards. ```bash make mypy ``` -------------------------------- ### Test Async Chat Completion Source: https://github.com/ai-forever/gigachat/blob/main/CONTRIBUTING.md Unit test for the asynchronous chat completion method. Mocks HTTP responses to verify asynchronous operation and response handling. ```python async def test_achat_completion(httpx_mock: HTTPXMock) -> None: """Test async chat completion.""" httpx_mock.add_response( method="POST", url="https://gigachat.devices.sberbank.ru/api/v1/chat/completions", json={"choices": [{"message": {"role": "assistant", "content": "Hi!"}}]} ) async with GigaChat(credentials="test", verify_ssl_certs=False) as client: result = await client.achat("Hello") assert result.choices[0].message.content == "Hi!" ``` -------------------------------- ### Rebase on Latest Main Branch Source: https://github.com/ai-forever/gigachat/blob/main/CONTRIBUTING.md Update your local branch with the latest changes from the upstream main branch. This is crucial to avoid merge conflicts and ensure your changes are based on the most recent code. ```bash git fetch upstream git rebase upstream/main ``` -------------------------------- ### Delete Local and Remote Branch Source: https://github.com/ai-forever/gigachat/blob/main/CONTRIBUTING.md Remove your feature branch locally and from the remote repository after it has been merged. This helps keep the repository clean. ```bash git branch -d feature/your-feature-name git push origin --delete feature/your-feature-name ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.