### Example Output Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/generate_image.ipynb This is an example of the expected output format when displaying the image caption. ```text Result:\n'Сообщение к изображению: " вот так выглядит котик."' ``` -------------------------------- ### Quick Start: Initialize GigaChat Client Source: https://github.com/ai-forever/gigachat-js/blob/master/README.md Initialize the GigaChat client with your API authorization key. This example demonstrates basic setup for making a chat request. Ensure you have obtained your API key from the Studio. ```typescript import GigaChat from 'gigachat'; import { Agent } from 'node:https'; const httpsAgent = new Agent({ rejectUnauthorized: false, // Отключает проверку корневого сертификата // Читайте ниже как можно включить проверку сертификата Мин. Цифры }); const client = new GigaChat({ timeout: 600, model: 'GigaChat', credentials: 'ваш_ключ_авторизации', httpsAgent: httpsAgent, }); client .chat({ messages: [{ role: 'user', content: 'Привет, как дела?' }], }) .then((resp) => { console.log(resp.choices[0]?.message.content); }); ``` -------------------------------- ### Install GigaChat SDK Source: https://github.com/ai-forever/gigachat-js/blob/master/README.md Use npm to install the GigaChat SDK. This is the first step to integrate GigaChat functionality into your project. ```sh npm install gigachat ``` -------------------------------- ### Update Token Example Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/vision.ipynb Placeholder for token update operations. ```text UPDATE TOKEN ``` -------------------------------- ### GigaChat Vision Response Example Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/vision.ipynb Example output from GigaChat Vision indicating the color of a kitten in an image. ```text Result: "У котенка на фото черно-белый окрас с пятнами." ``` -------------------------------- ### Image Caption Example Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/generate_image.ipynb This snippet shows how to construct a caption for the generated image using the extracted postfix information. ```typescript `Сообщение к изображению: "${detectedImage.postfix}" ``` -------------------------------- ### Environment Variables Configuration Source: https://context7.com/ai-forever/gigachat-js/llms.txt Configure GigaChat client settings using environment variables for simplified setup without hardcoding secrets. Ensure a .env file is present and variables are correctly set. ```bash # .env файл GIGACHAT_CREDENTIALS=ваш_ключ_авторизации GIGACHAT_SCOPE=GIGACHAT_API_PERS GIGACHAT_BASE_URL=https://gigachat.devices.sberbank.ru/api/v1/ GIGACHAT_MODEL=GigaChat GIGACHAT_TIMEOUT=600 ``` ```typescript import GigaChat from 'gigachat'; import * as dotenv from 'dotenv'; import { Agent } from 'node:https'; dotenv.config(); const httpsAgent = new Agent({ rejectUnauthorized: false }); // Клиент автоматически подтянет настройки из переменных окружения const client = new GigaChat({ httpsAgent: httpsAgent, }); ``` -------------------------------- ### Get List of Available Files Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/working_with_files.ipynb Retrieves a list of all files associated with the current GigaChat client. The result contains metadata for each file, and the count is available in `files.data.length`. ```javascript const files = await client.getFiles() files.data.length ``` -------------------------------- ### Pre-authorization: Get Token Source: https://github.com/ai-forever/gigachat-js/blob/master/README.md Manually obtain and update the access token before making API requests. This is useful if you need to authenticate prior to the first request. ```typescript const client = new GigaChat({ credentials: 'креды', scope: 'GIGACHAT_API_PERS / GIGACHAT_API_B2B / GIGACHAT_API_CORP', }); await giga.updateToken(); ``` -------------------------------- ### Get Models API Source: https://context7.com/ai-forever/gigachat-js/llms.txt Retrieves a list of all available GigaChat models along with their characteristics. ```APIDOC ## GET /models ### Description Fetches a list of all available models supported by GigaChat. ### Method GET ### Endpoint /models ### Response #### Success Response (200) - **data** (object[]) - An array of model objects. - **id** (string) - The unique identifier of the model. - **object** (string) - The type of the object (e.g., 'model'). #### Response Example ```json { "data": [ { "id": "GigaChat", "object": "model" }, { "id": "GigaChat-Plus", "object": "model" }, { "id": "GigaChat-Pro", "object": "model" }, { "id": "GigaChat-Max", "object": "model" } ] } ``` ``` -------------------------------- ### Batch Request Processing Source: https://context7.com/ai-forever/gigachat-js/llms.txt Utilize the Batch API for efficient asynchronous processing of multiple requests. This example demonstrates creating, sending, monitoring, and retrieving results from a batch request, followed by cleanup. ```typescript import GigaChat from 'gigachat'; import { Agent } from 'node:https'; import { BATCH_FILE_STATUS, BatchRequest, ChatCompletion } from 'gigachat/interfaces'; const httpsAgent = new Agent({ rejectUnauthorized: false }); const client = new GigaChat({ timeout: 600, model: 'GigaChat', httpsAgent: httpsAgent, }); async function main() { // Создание пакета запросов const tasks: Record = { '1': '1 + 3', '2': '8 - 16', '3': '12 * 2', }; const chats: BatchRequest[] = Object.keys(tasks).map((key) => ({ id: key, request: { messages: [ { role: 'user', content: `Вычисли: ${tasks[key]}. Ответь только числом.` }, ], }, })); // Отправка пакета const batch = await client.chatsBatch(chats); console.log(`Пакет создан: ${batch.id}, запросов: ${batch.request_counts.total}`); // Ожидание выполнения let fileId = ''; while (true) { const status = await client.getBatchStatus(batch.id); console.log(`Статус: ${status.status}, выполнено: ${status.request_counts.completed}/${status.request_counts.total}`); if (status.status === BATCH_FILE_STATUS.completed && status.output_file_id) { fileId = status.output_file_id; break; } await new Promise(resolve => setTimeout(resolve, 1000)); } // Получение результатов const results = await client.getBatch(fileId); results.content.forEach(item => { console.log(`${tasks[item.id]} = ${item.result.choices[0]?.message.content}`); }); // Вывод: // 1 + 3 = 4 // 8 - 16 = -8 // 12 * 2 = 24 // Удаление файла результатов await client.deleteFile(fileId); } main(); ``` -------------------------------- ### Get Available Models with GigaChat API Source: https://context7.com/ai-forever/gigachat-js/llms.txt Retrieve a list of all available GigaChat models and their characteristics using the `getModels()` method. Requires initializing the GigaChat client with timeout and httpsAgent. ```typescript import GigaChat from 'gigachat'; import { Agent } from 'node:https'; const httpsAgent = new Agent({ rejectUnauthorized: false }); const client = new GigaChat({ timeout: 600, httpsAgent: httpsAgent, }); async function main() { const models = await client.getModels(); console.log('Доступные модели:'); models.data.forEach(model => { console.log(`- ${model.id}: ${model.object}`); }); // Вывод: // - GigaChat: model // - GigaChat-Plus: model // - GigaChat-Pro: model // - GigaChat-Max: model } main(); ``` -------------------------------- ### Stream Chat Response Source: https://context7.com/ai-forever/gigachat-js/llms.txt Utilize the stream() method for real-time, token-by-token responses from the model, ideal for interactive chat interfaces. This example uses an async iterator to process chunks. ```typescript import GigaChat from 'gigachat'; import { Agent } from 'node:https'; const httpsAgent = new Agent({ rejectUnauthorized: false }); const client = new GigaChat({ profanityCheck: false, timeout: 600, model: 'GigaChat-Pro', httpsAgent: httpsAgent, }); async function main() { // Потоковая генерация с async iterator for await (const chunk of client.stream('Напиши отчет на тему ипотечного кризиса')) { process.stdout.write(chunk.choices[0]?.delta.content || ''); } // Вывод: текст генерируется посимвольно в реальном времени } main(); ``` -------------------------------- ### Retrieve Token Balance Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/get_balance.ipynb Call the balance() method on the initialized GigaChat client to get the current token usage across different models. The result includes detailed usage values and x-headers. ```typescript console.log(await client.balance()); ``` -------------------------------- ### Error Handling with GigaChat Exceptions Source: https://context7.com/ai-forever/gigachat-js/llms.txt Implement robust error handling for GigaChat API interactions using provided exception types like `AuthenticationError`, `ResponseError`, and `GigaChatException`. This example shows how to catch and differentiate between various error scenarios. ```typescript import GigaChat from 'gigachat'; import { AuthenticationError, ResponseError, GigaChatException } from 'gigachat/exceptions'; import { Agent } from 'node:https'; const httpsAgent = new Agent({ rejectUnauthorized: false }); const client = new GigaChat({ credentials: 'неверный_ключ', timeout: 600, httpsAgent: httpsAgent, }); async function main() { try { const response = await client.chat({ messages: [{ role: 'user', content: 'Привет!' }], }); console.log(response.choices[0]?.message.content); } catch (error) { if (error instanceof AuthenticationError) { console.error('Ошибка авторизации:', error.response.status); console.error('Проверьте credentials или токен доступа'); } else if (error instanceof ResponseError) { console.error('Ошибка API:', error.response.status, error.response.data); } else if (error instanceof GigaChatException) { console.error('Общая ошибка GigaChat:', error.message); } else { console.error('Неизвестная ошибка:', error); } } } main(); ``` -------------------------------- ### Define System Message and Available Functions Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/chat_bot_with_functions.ipynb Sets up the initial system message for the bot, defining its role and the available functions (get_products, get_product_info). The system prompt also instructs the bot on how to use these functions. ```typescript import { Message } from 'gigachat/interfaces'; const messages: Message[] = [ { role: 'system', content: `Ты бот-консультант продуктового магазина. Помни, что у тебя есть следующие функции: get_products: Получает текущие позиции в магазине get_product_info: Получает информацию о продукте (цена, количество) Помни, что ты можешь вызывать функции последовательно `, }, ]; ``` -------------------------------- ### Initialize GigaChat Client Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/tokens_count.ipynb Set up the GigaChat client with necessary configurations like timeout, model, and an HTTPS agent. Ensure environment variables are loaded for authentication. ```typescript import GigaChat from 'gigachat'; import * as dotenv from 'dotenv'; import { Agent } from 'node:https'; const httpsAgent = new Agent({ rejectUnauthorized: false, }); dotenv.config(); const client = new GigaChat({ timeout: 600, model: 'GigaChat', httpsAgent: httpsAgent, }); ``` -------------------------------- ### Initialize GigaChat Client with Credentials Source: https://context7.com/ai-forever/gigachat-js/llms.txt Create a GigaChat client instance using authorization credentials. Ensure your authorization key is obtained from the GigaChat Studio personal account. ```typescript import GigaChat from 'gigachat'; import { Agent } from 'node:https'; // Настройка HTTPS агента (отключение проверки сертификата для разработки) const httpsAgent = new Agent({ rejectUnauthorized: false, }); // Создание клиента с credentials const client = new GigaChat({ credentials: 'ваш_ключ_авторизации', scope: 'GIGACHAT_API_PERS', // или GIGACHAT_API_B2B, GIGACHAT_API_CORP model: 'GigaChat', timeout: 600, // таймаут в секундах httpsAgent: httpsAgent, }); ``` -------------------------------- ### Define Product Database Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/chat_bot_with_functions.ipynb Creates a mock product database with product details including name, price, quantity, and ID. This can be replaced with actual database access. ```typescript const PRODUCTS_DB = [ { name: 'Молоко', price: 100, quantity: 10, id: 0, }, { name: 'Хлеб', price: 70, quantity: 0, id: 1, }, { name: 'Сыр', price: 200, quantity: 20, id: 3, }, { name: 'Масло', price: 170, quantity: 20, id: 4, }, ]; ``` -------------------------------- ### Initialize GigaChat Client Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/chat_bot.ipynb Initializes the GigaChat client with configuration options including timeout, model, and an HTTPS agent. Ensure environment variables are configured for authentication. ```javascript import GigaChat from 'gigachat'; import * as dotenv from 'dotenv'; import { Agent } from 'node:https'; dotenv.config(); const httpsAgent = new Agent({ rejectUnauthorized: false, }); const client = new GigaChat({ timeout: 600, model: 'GigaChat', httpsAgent: httpsAgent, }); ``` -------------------------------- ### Implement Product Functions Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/chat_bot_with_functions.ipynb Defines the `get_products` and `get_product_info` functions that the GigaChat bot can call. `get_products` returns a list of product names and IDs, while `get_product_info` returns details for specified product IDs. ```typescript function get_products(): any { console.log('Вызов функции: get_products'); return PRODUCTS_DB.map((product) => { return { name: product.name, id: product.id }; }); } function get_product_info(args: any) { console.log('Вызов функции: get_products_info'); console.log(`С параметрами: ${JSON.stringify(args)}`); return PRODUCTS_DB.filter((product) => args.ids.includes(product.id)); } ``` -------------------------------- ### Count Tokens in Text Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/tokens_count.ipynb Use the client.tokensCount method to get the token and character count for an array of text strings. The response includes token details and request headers. ```typescript const resp = await client.tokensCount(['Привет, как дела?', 'Как дела, как дела']); resp ``` -------------------------------- ### Initialize GigaChat Client Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/vision.ipynb Initializes the GigaChat client with specified model and timeout. Requires dotenv for environment variables and node:https for agent configuration. ```python import GigaChat from 'gigachat'; import * as dotenv from 'dotenv'; import * as path from 'node:path'; import { Agent } from 'node:https'; import fs from 'node:fs'; dotenv.config(); const httpsAgent = new Agent({ rejectUnauthorized: false, }); const client = new GigaChat({ timeout: 600, model: 'GigaChat-Pro', httpsAgent: httpsAgent, }); ``` -------------------------------- ### Initialize GigaChat Client Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/stream_events.ipynb Initializes the GigaChat client with specified options, including API key, model, and network configurations. Ensure environment variables are set for API keys. ```typescript import GigaChat from 'gigachat'; import * as dotenv from 'dotenv'; import { Agent } from 'node:https'; dotenv.config(); const httpsAgent = new Agent({ rejectUnauthorized: false, }); const client = new GigaChat({ profanityCheck: false, timeout: 600, model: 'GigaChat', httpsAgent: httpsAgent, dangerouslyAllowBrowser: true, }); ``` -------------------------------- ### Initialize GigaChat Client Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/get_models.ipynb Initializes the GigaChat client with necessary configurations like timeout, model, and an HTTPS agent. Ensure you have dotenv configured for environment variables. ```typescript import GigaChat from 'gigachat'; import * as dotenv from 'dotenv'; import { Agent } from 'node:https'; const httpsAgent = new Agent({ rejectUnauthorized: false, }); dotenv.config(); const client = new GigaChat({ timeout: 600, model: 'GigaChat', httpsAgent: httpsAgent, }); ``` -------------------------------- ### Authorization with Access Token Source: https://github.com/ai-forever/gigachat-js/blob/master/README.md Initialize the GigaChat client using a pre-obtained access token. Note that the token is valid for 30 minutes. ```typescript const client = new GigaChat({ baseUrl: 'BASE URL апи', accessToken: 'токен', }); ``` -------------------------------- ### Initialize GigaChat Client in Browser Source: https://github.com/ai-forever/gigachat-js/blob/master/README.md Initialize the GigaChat client in a browser environment by enabling `dangerouslyAllowBrowser`. This configuration is necessary to prevent exceptions when using the library in the browser. ```typescript const client = new GigaChat({ timeout: 600, model: 'GigaChat', credentials: 'ваш_ключ_авторизации', dangerouslyAllowBrowser: true, }); ``` -------------------------------- ### Display Image with Deno Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/vision.ipynb Use this to display an image within a Deno environment. ```python Deno.jupyter.image('./media/cat.jpg') ``` -------------------------------- ### Authorization with Username and Password Source: https://github.com/ai-forever/gigachat-js/blob/master/README.md Initialize the GigaChat client using a base URL, username, and password for authentication. ```typescript const client = new GigaChat({ baseUrl: 'BASE URL апи', user: 'юзернейм', password: 'пароль', }); ``` -------------------------------- ### Initialize GigaChat Client with Access Token Source: https://context7.com/ai-forever/gigachat-js/llms.txt Configure the GigaChat client using an access token for authentication. The baseUrl is set to the API endpoint. ```typescript import GigaChat from 'gigachat'; import { Agent } from 'node:https'; const httpsAgent = new Agent({ rejectUnauthorized: false, }); // Альтернатива: авторизация через токен доступа const clientWithToken = new GigaChat({ baseUrl: 'https://gigachat.devices.sberbank.ru/api/v1/', accessToken: 'ваш_токен_доступа', timeout: 600, httpsAgent: httpsAgent, }); ``` -------------------------------- ### Authorization with Credentials Source: https://github.com/ai-forever/gigachat-js/blob/master/README.md Initialize the GigaChat client using credentials and specifying the desired scope for API access. ```typescript const client = new GigaChat({ credentials: 'креды', scope: 'GIGACHAT_API_PERS / GIGACHAT_API_B2B / GIGACHAT_API_CORP', }); ``` -------------------------------- ### File Upload API Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/working_with_files.ipynb This section details how to upload a file using the GigaChat client. It includes the necessary imports, client initialization, file preparation, and the upload process. The output shows the details of the uploaded file. ```APIDOC ## POST /files ### Description Uploads a file to be used with the GigaChat API. ### Method POST ### Endpoint /files ### Parameters #### Request Body - **file** (File) - Required - The file to upload. ### Request Example ```javascript import 'dotenv'; import { GigaChat } from 'gigachat'; import * as dotenv from 'dotenv'; import { Agent } from 'node:https'; import * as path from 'node:path'; import fs from 'node:fs'; const httpsAgent = new Agent({ rejectUnauthorized: false, }); dotenv.config(); const client = new GigaChat({ timeout: 600, model: 'GigaChat', httpsAgent: httpsAgent, }); const filePath = path.resolve('./media/cat.jpg'); const buffer = fs.readFileSync(filePath); const file = new File([buffer], 'cat.jpg', { type: 'image/jpeg' }); const uploadedFile = await client.uploadFile(file); ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the uploaded file. - **object** (string) - The type of object, which is 'file'. - **bytes** (integer) - The size of the file in bytes. - **access_policy** (string) - The access policy for the file ('private'). - **created_at** (integer) - The timestamp when the file was created. - **filename** (string) - The name of the file. - **purpose** (string) - The purpose of the file ('general'). - **xHeaders** (object) - Additional request headers. - **xRequestID** (string) - The request ID. - **xSessionID** (string) - The session ID. - **xClientID** (string) - The client ID (may be undefined). #### Response Example ```json { "id": "59af540e-321d-434a-8b46-4d5adb3c92ff", "object": "file", "bytes": 133107, "access_policy": "private", "created_at": 1742999340, "filename": "cat.jpg", "purpose": "general", "xHeaders": { "xRequestID": "67c5950a-246b-4522-9d41-d7dfd1e679b5", "xSessionID": "c694cf71-a919-4e48-baef-b6c3d728660c", "xClientID": null } } ``` ``` -------------------------------- ### Retrieve Product Information Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/chat_bot_with_functions.ipynb Call the get_products_info function with specific product IDs to retrieve their details. Ensure the product IDs are provided in an array. ```javascript get_products_info({"ids":[4]}) ``` -------------------------------- ### Upload a File to GigaChat Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/working_with_files.ipynb Reads a local file into a buffer, creates a File object, and uploads it using the GigaChat client. The uploaded file can then be referenced by its ID. ```javascript import * as path from 'node:path'; import fs from 'node:fs'; const filePath = path.resolve('./media/cat.jpg'); const buffer = fs.readFileSync(filePath); const file = new File([buffer], 'cat.jpg', { type: 'image/jpeg' }); const uploadedFile = await client.uploadFile(file); uploadedFile ``` -------------------------------- ### List Files API Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/working_with_files.ipynb Retrieves a list of all files associated with the account. The output shows the count of files and the details of the first file in the list. ```APIDOC ## GET /files ### Description Retrieves a list of all files uploaded to the GigaChat account. ### Method GET ### Endpoint /files ### Response #### Success Response (200) - **data** (array) - An array of file objects. - Each file object contains: - **id** (string) - The unique identifier for the file. - **object** (string) - The type of object, which is 'file'. - **bytes** (integer) - The size of the file in bytes. - **access_policy** (string) - The access policy for the file ('private'). - **created_at** (integer) - The timestamp when the file was created. - **filename** (string) - The name of the file. - **purpose** (string) - The purpose of the file ('general'). ### Request Example ```javascript const files = await client.getFiles() ``` ### Response Example ```json { "data": [ { "id": "59af540e-321d-434a-8b46-4d5adb3c92ff", "object": "file", "bytes": 133107, "access_policy": "private", "created_at": 1742999340, "filename": "cat.jpg", "purpose": "general" } ] } ``` ``` -------------------------------- ### GigaChat Initialization Parameters Source: https://github.com/ai-forever/gigachat-js/blob/master/README.md Parameters that can be passed during the GigaChat object initialization. ```APIDOC ## GigaChat Initialization Parameters This section describes the parameters that can be passed when initializing the GigaChat object. ### Parameters - **credentials** (string) - Required - Authorization key for exchanging messages with the GigaChat API. The authorization key contains information about the API version to which requests are made. If you are using the API version for sole proprietors or legal entities, specify this explicitly in the `scope` parameter. - **scope** (string) - Optional - The API version to which the request will be made. By default, requests are sent to the version for individuals. Possible values: - `GIGACHAT_API_PERS` - API version for individuals; - `GIGACHAT_API_B2B` - API version for sole proprietors and legal entities when working on a prepayment basis. - `GIGACHAT_API_CORP` - API version for sole proprietors and legal entities when working on a post-payment basis. - **model** (string) - Optional - Allows you to explicitly specify the GigaChat model. You can view the list of available models using the `get_models()` method, which executes the `GET /models` request. The cost of requests to different models varies. Detailed information about the cost of requests to a particular model can be found in the official documentation. - **baseUrl** (string) - Optional - The API address. By default, requests are sent to `https://gigachat.devices.sberbank.ru/api/v1/`, but if you want to use early access models, specify the address `https://gigachat-preview.devices.sberbank.ru/api/v1`. - **httpsAgent** (object) - Optional - HTTPS settings that are added when connecting to the API server (connecting by certificate, disabling root certificate verification, etc.). **Not supported in the browser!** - **dangerouslyAllowBrowser** (boolean) - Optional - Flag to enable the library in the browser. By default, this library does not work in the browser, as this can expose your GigaChat token. ``` -------------------------------- ### View File Details by ID Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/working_with_files.ipynb Fetches detailed information about a specific file using its ID. This includes file metadata such as ID, size, creation date, and filename. ```javascript await client.getFile(uploadedFile.id) ``` -------------------------------- ### Authorization with TLS Certificates (mTLS) Source: https://github.com/ai-forever/gigachat-js/blob/master/README.md Initialize the GigaChat client using TLS certificates for mutual authentication. This requires providing CA, client certificate, and private key paths, along with the private key's passphrase. ```typescript import GigaChat from 'gigachat'; import { Agent } from 'node:https'; import fs from 'node:fs'; const httpsAgent = new Agent({ ca: fs.readFileSync('certs/ca.pem'), cert: fs.readFileSync('certs/tls.pem'), key: fs.readFileSync('certs/tls.key'), passphrase: 'пароль от приватного ключа', }); const client = new GigaChat({ baseUrl: 'BASE URL апи', httpsAgent: httpsAgent, }); ``` -------------------------------- ### Upload File and Chat with Image Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/vision.ipynb Reads an image file, uploads it, and sends it as an attachment in a chat message to GigaChat Vision. The response contains the analysis of the image. ```python const filePath = path.resolve('./media/cat.jpg'); const buffer = fs.readFileSync(filePath); const file = new File([buffer], 'image.jpg', { type: 'image/jpeg' }); const uploadedFile = await client.uploadFile(file); const response = await client.chat({ messages: [ { role: 'user', content: 'Какой окрас у котенка на фото?', attachments: [uploadedFile.id], }, ], temperature: 0.1, }); response.choices[0]?.message.content ``` -------------------------------- ### Check Account Balance Source: https://context7.com/ai-forever/gigachat-js/llms.txt Use the `balance()` method to retrieve the current token balance of your account. Ensure the GigaChat client is initialized with appropriate credentials. ```typescript import GigaChat from 'gigachat'; import { Agent } from 'node:https'; const httpsAgent = new Agent({ rejectUnauthorized: false }); const client = new GigaChat({ timeout: 600, httpsAgent: httpsAgent, }); async function main() { const balance = await client.balance(); console.log('Баланс аккаунта:', balance); // Вывод: { balance: [...токены...] } } main(); ``` -------------------------------- ### Define Function Schemas for GigaChat Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/chat_bot_with_functions.ipynb Defines the schemas for the `get_products` and `get_product_info` functions, including their parameters and return types. This allows GigaChat to understand how to call these functions and what to expect in return. ```typescript const functions = [ { name: 'get_products', description: 'Получает какие продукты есть в магазине', parameters: { type: 'object', properties: { arg: { type: 'string', }, }, }, return_parameters: { type: 'object', properties: { name: { type: 'string', description: 'Название позиции', }, id: { type: 'string', description: 'ID позиции', }, }, }, }, { name: 'get_product_info', description: 'Получает информацию об определенном продукте в магазине', parameters: { type: 'object', properties: { ids: { type: 'array', items: { type: 'number', description: 'ID продуктов', }, }, }, }, return_parameters: { type: 'object', properties: { products: { type: 'array', items: { type: 'object', properties: { name: { type: 'string', description: 'Название позиции', }, id: { type: 'string', description: 'ID позиции', }, quantity: { type: 'string', description: 'Количество', }, price: { type: 'string', description: 'Цена', }, }, }, }, }, }, }, ] ``` -------------------------------- ### Convert AI Intervals to Console Arguments Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/ai_check.ipynb This utility function formats the original text and AI intervals into arguments suitable for `console.log`, using '%c' for styling to highlight AI-written parts in red. ```javascript function aiIntervalsToArgs(text, aiIntervals) { if (!aiIntervals.length) return [text]; let output = ""; const colors = []; if (aiIntervals[0][0] > 0) { output += "%c" + text.substr(0, aiIntervals[0][0]); colors.push("color: black"); } for (let i = 0; i < aiIntervals.length; i++) { const interval = aiIntervals[i]; if (i > 0 && aiIntervals[i][0] - aiIntervals[i-1][1] > 1) { output += "%c" + text.substr(aiIntervals[i-1][1], aiIntervals[i][0] - aiIntervals[i - 1][1]); colors.push("color: black"); } output += "%c" + text.substr(aiIntervals[i][0], aiIntervals[i][1] - aiIntervals[i][0]); colors.push("color: red"); } if (aiIntervals[aiIntervals.length - 1][1] < text.length) { output += "%c" + text.substr(aiIntervals[aiIntervals.length - 1][1], text.length); colors.push("color: black"); } return [output, ...colors] } ``` -------------------------------- ### Check Account Balance Source: https://context7.com/ai-forever/gigachat-js/llms.txt Use the `balance()` method to retrieve the current token balance of your account. ```APIDOC ## GET /balance ### Description Retrieves the current token balance for the authenticated account. ### Method GET ### Endpoint /balance ### Parameters None ### Request Example ```typescript import GigaChat from 'gigachat'; import { Agent } from 'node:https'; const httpsAgent = new Agent({ rejectUnauthorized: false }); const client = new GigaChat({ timeout: 600, httpsAgent: httpsAgent, }); async function main() { const balance = await client.balance(); console.log('Баланс аккаунта:', balance); } main(); ``` ### Response #### Success Response (200) - **balance** (object) - An object containing token balance information. #### Response Example ```json { "balance": "...tokens..." } ``` ``` -------------------------------- ### Catch and Handle ResponseError Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/exception_handling.ipynb Demonstrates how to use a try-catch block to capture `gigachat/exceptions/ResponseError`. It checks the error type and logs specific details from the error response, such as status, message, and request ID. ```javascript import {ResponseError} from "gigachat/exceptions" try { await client.chat({ messages: [{ role: 'user', content: 'Привет, как дела?' }], functions: [{name: 'not_valid_function'}] }); } catch (exc) { if (!(exc instanceof ResponseError)) { throw exc; } else { console.error(`Response Status: ${exc.response.status}`); console.error(`Response Message: ${exc.response.data.message}`); console.error(`Response Request ID: ${exc.response.headers['x-request-id']}`) } } ``` -------------------------------- ### File Management API Source: https://context7.com/ai-forever/gigachat-js/llms.txt Provides methods for uploading, retrieving information about, and deleting files on the GigaChat server. ```APIDOC ## File Operations ### Description Manage files on the GigaChat server, including uploading, retrieving details, and deleting. ### Methods #### Upload File ##### Method POST ##### Endpoint /files ##### Parameters - **file** (File) - The file to upload. - **purpose** (string) - The purpose of the file (e.g., 'general'). ##### Request Example ```typescript import GigaChat from 'gigachat'; import { Agent } from 'node:https'; import fs from 'node:fs'; const httpsAgent = new Agent({ rejectUnauthorized: false }); const client = new GigaChat({ timeout: 600, httpsAgent: httpsAgent, }); async function main() { const buffer = fs.readFileSync('./document.pdf'); const file = new File([buffer], 'document.pdf', { type: 'application/pdf' }); const uploaded = await client.uploadFile(file, 'general'); console.log('Загружен файл:', uploaded.id); } main(); ``` #### Get File Information ##### Method GET ##### Endpoint /files/{file_id} ##### Parameters - **file_id** (string) - Required - The ID of the file to retrieve information for. ##### Request Example ```typescript // ... (client initialization as above) async function main() { // ... (upload file first to get an ID) const fileInfo = await client.getFile(uploaded.id); console.log('Информация о файле:', fileInfo); } main(); ``` #### List All Files ##### Method GET ##### Endpoint /files ##### Parameters None ##### Request Example ```typescript // ... (client initialization as above) async function main() { // ... (upload file first) const allFiles = await client.getFiles(); console.log('Все файлы:', allFiles.data.map(f => f.id)); } main(); ``` #### Delete File ##### Method DELETE ##### Endpoint /files/{file_id} ##### Parameters - **file_id** (string) - Required - The ID of the file to delete. ##### Request Example ```typescript // ... (client initialization as above) async function main() { // ... (upload file first) const deleted = await client.deleteFile(uploaded.id); console.log('Файл удалён:', deleted); } main(); ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the file. - **filename** (string) - The name of the file. - **purpose** (string) - The purpose assigned to the file. - **bytes** (integer) - The size of the file in bytes. - **created_at** (string) - The timestamp when the file was created. #### Response Example (Get File Info) ```json { "id": "file_id", "filename": "document.pdf", "purpose": "general", "bytes": 1024, "created_at": "2023-10-27T10:00:00Z" } ``` #### Response Example (Delete File) ```json { "id": "file_id", "deleted": true } ``` ``` -------------------------------- ### Browser Usage with GigaChat SDK Source: https://context7.com/ai-forever/gigachat-js/llms.txt Enables GigaChat SDK usage in a browser environment. Use with caution due to security risks associated with exposing API keys in client-side code. The `dangerouslyAllowBrowser` flag must be set to `true`. ```typescript import GigaChat from 'gigachat'; // Включение работы в браузере (используйте с осторожностью!) const client = new GigaChat({ credentials: 'ваш_ключ', // Внимание: ключ будет виден в браузере! model: 'GigaChat', timeout: 600, dangerouslyAllowBrowser: true, // Обязательный флаг для браузера }); async function sendMessage(userInput: string) { const response = await client.chat({ messages: [{ role: 'user', content: userInput }], }); return response.choices[0]?.message.content; } ``` -------------------------------- ### Fetch Available Models Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/get_models.ipynb Calls the getModels() method on the initialized GigaChat client to retrieve a list of all available models. ```typescript await client.getModels() ``` -------------------------------- ### Analyze Images with GigaChat Vision Source: https://context7.com/ai-forever/gigachat-js/llms.txt Analyze image content and answer questions about it using GigaChat Vision. Images are uploaded via the API and attached to messages. Requires reading a file into a buffer and creating a File object. ```typescript import GigaChat from 'gigachat'; import { Agent } from 'node:https'; import fs from 'node:fs'; import path from 'node:path'; const httpsAgent = new Agent({ rejectUnauthorized: false }); const client = new GigaChat({ timeout: 600, model: 'GigaChat-Pro', httpsAgent: httpsAgent, }); async function main() { // Загрузка изображения const filePath = path.resolve(__dirname, './photo.jpg'); const buffer = fs.readFileSync(filePath); const file = new File([buffer], 'image.jpg', { type: 'image/jpeg' }); // Загрузка файла на сервер GigaChat const uploadedFile = await client.uploadFile(file); console.log('Файл загружен, ID:', uploadedFile.id); // Анализ изображения const response = await client.chat({ messages: [ { role: 'user', content: 'Опиши что изображено на фотографии', attachments: [uploadedFile.id], }, ], temperature: 0.1, }); console.log(response.choices[0]?.message.content); // Вывод: "На фотографии изображён рыжий котёнок..." } main(); ``` -------------------------------- ### File Management Operations Source: https://context7.com/ai-forever/gigachat-js/llms.txt Perform file operations such as uploading, retrieving file information, listing all files, and deleting files from the GigaChat server. Ensure the file is correctly formatted and typed. ```typescript import GigaChat from 'gigachat'; import { Agent } from 'node:https'; import fs from 'node:fs'; const httpsAgent = new Agent({ rejectUnauthorized: false }); const client = new GigaChat({ timeout: 600, httpsAgent: httpsAgent, }); async function main() { // Загрузка файла const buffer = fs.readFileSync('./document.pdf'); const file = new File([buffer], 'document.pdf', { type: 'application/pdf' }); const uploaded = await client.uploadFile(file, 'general'); console.log('Загружен файл:', uploaded.id); // Получение информации о файле const fileInfo = await client.getFile(uploaded.id); console.log('Информация о файле:', fileInfo); // Получение списка всех файлов const allFiles = await client.getFiles(); console.log('Все файлы:', allFiles.data.map(f => f.id)); // Удаление файла const deleted = await client.deleteFile(uploaded.id); console.log('Файл удалён:', deleted); } main(); ``` -------------------------------- ### Function Calling with GigaChat Source: https://context7.com/ai-forever/gigachat-js/llms.txt Implement function calling to allow the model to interact with external systems. Define functions, their parameters, and return types. The model determines when to call a function and provides arguments. ```typescript import GigaChat from 'gigachat'; import { Message } from 'gigachat/interfaces'; import { Agent } from 'node:https'; const httpsAgent = new Agent({ rejectUnauthorized: false }); const client = new GigaChat({ timeout: 600, model: 'GigaChat-Max', httpsAgent: httpsAgent, }); // База данных продуктов const PRODUCTS_DB = [ { name: 'Молоко', price: 100, quantity: 10, id: 0 }, { name: 'Хлеб', price: 70, quantity: 0, id: 1 }, { name: 'Сыр', price: 200, quantity: 20, id: 2 }, ]; // Определение функций const functions = [ { name: 'get_products', description: 'Получает какие продукты есть в магазине', parameters: { type: 'object', properties: {}, }, return_parameters: { type: 'object', properties: { name: { type: 'string', description: 'Название позиции' }, id: { type: 'string', description: 'ID позиции' }, }, }, }, { name: 'get_product_info', description: 'Получает информацию об определенном продукте', parameters: { type: 'object', properties: { ids: { type: 'array', items: { type: 'number', description: 'ID продуктов' }, }, }, }, }, ]; // Реализация функций function get_products() { return PRODUCTS_DB.map(p => ({ name: p.name, id: p.id })); } function get_product_info(args: { ids: number[] }) { return PRODUCTS_DB.filter(p => args.ids.includes(p.id)); } async function main() { const messages: Message[] = [ { role: 'system', content: 'Ты бот-консультант продуктового магазина.', }, { role: 'user', content: 'Какие товары у вас есть и сколько стоит сыр?', }, ]; let response = await client.chat({ functions, messages, function_call: 'auto', }); // Обработка вызова функции if (response.choices[0]?.message.function_call) { const funcCall = response.choices[0].message.function_call; messages.push(response.choices[0].message); let result: any; if (funcCall.name === 'get_products') { result = get_products(); } else if (funcCall.name === 'get_product_info') { result = get_product_info(funcCall.arguments as { ids: number[] }); } messages.push({ role: 'function', content: JSON.stringify(result) }); response = await client.chat({ functions, messages }); } console.log('AI:', response.choices[0]?.message.content); // Вывод: "У нас есть: Молоко, Хлеб, Сыр. Сыр стоит 200 рублей." } main(); ``` -------------------------------- ### GigaChat Interaction Loop with Function Calls Source: https://github.com/ai-forever/gigachat-js/blob/master/examples/chat_bot_with_functions.ipynb This loop continuously prompts the user for input, sends it to GigaChat, and handles function calls if the AI response indicates one. It pushes both user and AI messages, along with function call results, back into the message history for context. ```typescript let question = prompt('Q: '); while (question) { console.log(`Q: ${question}`) messages.push({ role: 'user', content: question, }); let response = await client.chat({ functions: functions, messages, function_call: "auto" }); if (response.choices[0]?.message) messages.push(response.choices[0].message); if (response.choices[0]?.message.function_call) { let function_result: any = {}; switch (response.choices[0].message.function_call.name) { case 'get_products': function_result = get_products(); break; case 'get_product_info': function_result = get_product_info(response.choices[0].message.function_call.arguments); break; } messages.push({ role: 'function', content: JSON.stringify(function_result), }); response = await client.chat({ functions, messages, }); } console.log(`AI: ${response.choices[0]?.message.content}`) question = prompt('Q: '); } ```