### Install Dependencies Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/js/extraction.ipynb Install the necessary Langchain and Gigachat libraries using npm. Ensure you have Node.js and npm installed. ```bash npm install --save langchain langchain-gigachat zod ``` -------------------------------- ### Few-Shot Structured Output with Tool Calls Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/structured_output/structured_output.ipynb Use example tool calls within a prompt to guide the model in generating structured output. This method is effective when the model needs to understand specific tool usage patterns. ```python from langchain_core.messages import AIMessage, HumanMessage, ToolMessage examples = [ HumanMessage("Мне нужна книга 'Война и мир'", name="example_user"), AIMessage( "", name="example_assistant", tool_calls=[ { "name": "book", "args": { "title": "Война и мир", "author": "неизвестен", "language": "любой" }, "id": "1", } ], ), # Большинство моделей, поддерживающих работу с инструментами (функциями), ожидают получение сообщений типа ToolMessage после сообщения типа AIMessage с вызовами инструментов. ToolMessage("", tool_call_id="1"), HumanMessage("Нужна сказка 'Маленький принц' Антуана де Сент-Экзюпери на французском.", name="example_user"), AIMessage( "", name="example_assistant", tool_calls=[ { "name": "joke", "args": { "title": "Маленький принц", "author": "Антуан де Сент-Экзюпери", "language": "французский" }, "id": "2", } ], ), ToolMessage("", tool_call_id="2"), HumanMessage("Хочу прочитать 'Сто лет одиночества' Габриэля Гарсиа Маркеса", name="example_user"), AIMessage( "", tool_calls=[ { "name": "joke", "args": { "title": "Сто лет одиночества", "author": "Габриэля Гарсиа Маркес", "language": "любой" }, "id": "3", } ], ), ToolMessage("", tool_call_id="3"), ] system = "" prompt = ChatPromptTemplate.from_messages( [("system", system), ("placeholder", "{examples}"), ("human", "{input}")] ) few_shot_structured_llm = prompt | structured_llm few_shot_structured_llm.invoke({"input": "Нужен 'Евгений Онегин' Пушкина в оригинале на русском", "examples": examples}) ``` ```text Result: {'author': 'Пушкин', 'language': 'русский', 'title': 'Евгений Онегин'} ``` -------------------------------- ### RAG Chain Output Example Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/js/rag.ipynb This is an example of the output from the RAG chain, showing the answer to the question about installing certificates, including a TypeScript code snippet for setting up the HTTPS agent. ```text UPDATE TOKEN\n\nResult:\n"Для установки сертификатов при подключении к GigaChat необходимо использовать HTTPS-агент с вашими сертификатами. Вот пример кода на TypeScript:\ " +\n "\ " +\n "```typescript\ " +\n "import GigaChat from 'gigachat';\ " +\n "import { Agent } from 'node:https';\ " +\n "import fs from 'node:fs';\ " +\n "\ " +\n "const httpsAgent = new Agent({\ " +\n " ca: fs.readFileSync('path/to/your/ca.pem'),\ " +\n " cert: fs.readFileSync('path/to/your/tls.pem'),\ " +\n " key: fs.readFileSync('path/to/your/tls.key'),\ " +\n " passphrase: 'password',\ " +\n "});\ " +\n "\ " +\n "const client = new GigaChat({\ " +\n " baseUrl: 'YOUR_API_URL',\ " +\n " httpsAgent: httpsAgent,\ " +\n "});\ " +\n "```\ " +\n "\ " +\n "Не забудьте заменить `path/to/your/` на реальные пути к вашим сертификатам." ``` -------------------------------- ### Install Libraries Source: https://github.com/ai-forever/gigachain/blob/master/hub/prompts/summarize/map_reduce/summarize_examples.ipynb Installs the required Langchain and GigaChat libraries. Use this command to set up your environment. ```python !pip install langchain_gigachat python_dotenv --quiet -U ``` -------------------------------- ### Install project dependencies Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/js/langgraph_quickstart.ipynb Install the necessary LangChain and GigaChat packages required for the agent. ```bash npm install @langchain/core @langchain/langgraph langchain-gigachat @langchain/community ``` -------------------------------- ### Install LangGraph Studio Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/agent_debates/README.md Install the LangGraph CLI with in-memory support for debugging and development. ```sh pip install -U "langgraph-cli[inmem]" ``` -------------------------------- ### Install Dependencies Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/mcp/README.md Install the necessary Python libraries for GigaChat, MCP adapters, and LangGraph. Ensure you have Rich installed for enhanced output. ```sh pip install langchain-gigachat langchain_mcp_adapters langgraph rich ``` -------------------------------- ### Install Dependencies Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/gigachat_functions_agent.ipynb Installs necessary libraries for GigaChat and LangChain integration. Run this command in your environment. ```python !pip install -U langchain-gigachat langgraph python-dotenv -q ``` -------------------------------- ### Install Dependencies Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/js/tools.ipynb Install necessary npm packages for Langchain and Gigachat integration. ```bash npm install --save langchain langchain-gigachat @langchain/community @langchain/core ``` -------------------------------- ### Install Dependencies Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/agent_debates/README.md Install project dependencies using pip. Ensure you have a requirements.txt file in your project. ```sh pip install -r requirements.txt ``` -------------------------------- ### Install necessary libraries Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/gigachat_qa.ipynb Installs the pypdf and langchain-chroma libraries required for PDF loading and ChromaDB integration. Use --quiet to suppress verbose output. ```bash !pip install pypdf langchain-chroma --quiet ``` -------------------------------- ### Install Dependencies for GigaChat Phone Agent Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/gigachat_phone_agent.ipynb Install the necessary Python libraries for the GigaChat phone agent example. This includes langchain-gigachat, langgraph, and python-dotenv for environment variable management. ```python pip install langchain-gigachat langgraph python-dotenv ``` -------------------------------- ### Install gigachain_core Source: https://github.com/ai-forever/gigachain/blob/master/hub/prompts/nlp/nlp_examples.ipynb Install or upgrade the gigachat_core library to version 0.1.9.1 or higher for template compatibility. Use pip for manual installation. ```sh pip install -U gigachain_core ``` -------------------------------- ### Start LangGraph Studio Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/agent_debates/README.md Run the LangGraph Studio development server. Access the studio via the provided local URL in your browser. ```sh langgraph dev ``` -------------------------------- ### Install Langchain and GigaChat Dependencies Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/js/rag.ipynb Install the necessary npm packages for langchain, langchain-gigachat, and cheerio. ```bash npm install --save langchain langchain-gigachat cheerio ``` -------------------------------- ### Install GigaChain dependencies Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/images_and_videos/gigachat_with_images.ipynb Install the necessary libraries for GigaChain and environment variable management. ```python !pip install langchain-gigachat python-dotenv -q ``` -------------------------------- ### Initialize TagMe Client Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/tagme-agent/tagme-agent.ipynb Initializes the `TagmeClientAdvanced` using the generated configuration file. Ensure the `crowd-sdk` library is installed. ```python from crowd_sdk.tagme import TagmeClientAdvanced client = TagmeClientAdvanced("./crowd.cfg") ``` -------------------------------- ### Configure GigaChat Credentials Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/mcp/README.md Create a .env file in the example directory and add your GigaChat authorization key to the GIGACHAT_CREDENTIALS variable. Other GigaChat environment variables are also supported. ```sh GIGACHAT_CREDENTIALS=<ключ_авторизации> ``` -------------------------------- ### Install Dependencies for Report Generation Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/reporter/part_2.ipynb Installs necessary Python libraries for GigaChat integration, data handling, and report generation. Use this to set up your environment before running the analysis. ```python %%capture --no-stderr %pip install "arize-phoenix[embeddings]" langchain_gigachat pandas numpy md2pdf tqdm python-dotenv ``` -------------------------------- ### Start MCP Server in SSE Mode Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/mcp/README.md To use the HTTP client, first start the MCP server in SSE (Server-Sent Events) mode by running the math_server.py script with the 'sse' argument. ```sh python math_server.py sse ``` -------------------------------- ### Install Required Libraries Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/reporter/part_1.ipynb Installs necessary Python libraries for GigaChat embeddings, Kaggle dataset handling, Langchain, and data manipulation. Use this command before running the notebook. ```python %%capture --no-stderr %pip install "arize-phoenix[embeddings]" "kagglehub[pandas-datasets]" langchain_gigachat pandas numpy python-dotenv ``` -------------------------------- ### Prompt Template Input Variables Example Source: https://github.com/ai-forever/gigachain/blob/master/hub/prompts/README.md This YAML snippet shows an example of defining input variables for a prompt template. These variables are placeholders that will be filled in when the prompt is used. ```yaml input_variables: [dataset_size_min, dataset_size_max, subject] ``` -------------------------------- ### Prompt Template Example Source: https://github.com/ai-forever/gigachain/blob/master/hub/prompts/README.md This is an example of a prompt template in YAML format. It defines input variables, an output parser, the template string, template format, and the type. ```yaml input_variables: [dataset_size_min, dataset_size_max, subject, examples] output_parser: null template: 'Сгенерируй от {dataset_size_min} до {dataset_size_max} синонимов для слова "{subject}". Примеры фраз: {examples}. Результат верни в формате JSON-списка без каких либо пояснений, например, ["синоним1", "синоним2", "синоним3", "синоним4"]. Не повторяй фразы из примера и не дублируй фразы.' template_format: f-string _type: prompt ``` -------------------------------- ### Install Required Libraries Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/repl_graph/repl.ipynb Installs the necessary Python libraries for GigaChat integration, LangGraph, and E2B code interpreter. Use this command in your environment before running the notebook. ```python %%capture --no-stderr %pip install langchain_gigachat python-dotenv langgraph e2b-code-interpreter ``` -------------------------------- ### Install Dependencies for GigaChat Vision Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/gigachat_vision/gigachat_vision.ipynb Installs necessary libraries for GigaChat Vision, Langchain, and environment variable management. Use this at the beginning of your project. ```python !pip install langchain-gigachat langchain python-dotenv -q ``` -------------------------------- ### Install Dependencies for GigaChat RAG Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/gigachat_qa.ipynb Installs necessary libraries for using GigaChat with LangChain and Chroma for RAG applications. Run this command in your environment. ```python %pip install langchain-gigachat langchain-chroma python-dotenv --quiet ``` -------------------------------- ### Initialize GigaChat Model Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/yandex_search/retriever.ipynb Initializes the GigaChat model, specifying 'GigaChat-Pro' as the model name. SSL certificate verification is disabled for simplicity in this example. ```python model = GigaChat( model="GigaChat-Pro", verify_ssl_certs=False, ) ``` -------------------------------- ### Create Agent Generation Prompt Template Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/reporter/part_2.ipynb Constructs a chat prompt template for generating agent descriptions. It includes system instructions with examples and placeholders for dynamic input. The prompt is partially configured with format instructions from the Pydantic parser. ```python agent_generation = """Ты помощник в составлении отчетов. Твоя задача создать описания агента исходя из заданной пользователем темы. Определяется областью темы и конкретным именем агента, который может быть использован для создания отчета под конкретную тему. Агенты классифицируются по их области экспертизы. Отвечай в формате JSON: {format_instructions} Примеры: задача: "Инвестиции в акции Apple" ответ: {{ "name": "Финансовый агент", "agent_role_prompt": "Ты — ИИ-помощник аналитика финансов. Твоя основная задача — составлять всесторонние, продуманные, беспристрастные и методически структурированные финансовые отчёты на основе предоставленных данных и тенденций." }} задача: "перепродажа кроссовок" ответ: {{ "name": "Агент бизнес-аналитики", "agent_role_prompt": "Ты — ИИ-помощник бизнес-аналитика. Твоя основная цель — создавать всесторонние, проницательные, беспристрастные и систематически структурированные бизнес-отчёты на основе предоставленных бизнес-данных, рыночных тенденций и стратегического анализа." }} задача: "интересные места в Тель-Авиве" ответ: {{ "name": "Туристический агент", "agent_role_prompt": "Ты — ИИ-помощник гида. Твоя основная задача — составлять увлекательные, информативные, беспристрастные и хорошо структурированные туристические отчёты по заданным местам, включая историю, достопримечательности и культурные особенности." }}""" agent_prompt = ChatPromptTemplate.from_messages([ ("system", agent_generation), ("user", "задача: \"{message}\"") ]).partial(format_instructions=agent_parser.get_format_instructions()) ``` -------------------------------- ### MCP React Agent Usage Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/mcp/README.md This example demonstrates running a console agent for MCP servers configured via JSON. It requires setting up MCP servers in 'mcp_config.json' and GigaChat credentials in '.env'. ```sh python mcp_react_agent.py ``` -------------------------------- ### Initialize GigaChat Client Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/gigachat_vision/gigachat_vision.ipynb Initializes the GigaChat client, requiring an API key. The key can be set via the GIGACHAT_CREDENTIALS environment variable or entered interactively. This setup is crucial for authenticating with GigaChat services. ```python import getpass import os from dotenv import find_dotenv, load_dotenv load_dotenv(find_dotenv()) if "GIGACHAT_CREDENTIALS" not in os.environ: os.environ["GIGACHAT_CREDENTIALS"] = getpass.getpass("Введите ключ авторизации GigaChat API: ") from langchain_gigachat.chat_models import GigaChat llm = GigaChat( temperature=0.1, verify_ssl_certs=False, timeout=6000, model="GigaChat-Pro" ) ``` -------------------------------- ### MCP React Agent Example Interaction Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/mcp/README.md Illustrates an interactive console session with the MCP React Agent. The agent handles user queries, calls MCP tools like 'find_preson' and 'multiply', and provides responses. ```sh User: Привет Agent: Привет! Как настроение? User: Сколько лет Джону Доу? 🔧 Tool: find_preson | Args: {'name': {'query': 'Джон Доу'}} Agent: Джону Доу 30 лет. User: Умножь его возраст на число пи 🔧 Tool: find_preson | Args: {'name': {'query': 'Джон Доу'}} 🔧 Tool: multiply | Args: {'a': 30, 'b': 3.14159} Agent: Результат умножения возраста Джона Доу (30 лет) на число Пи примерно равен 94.25. ``` -------------------------------- ### Create and Bind Gigachat Agent with Functions Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/gigachat_functions_agent.ipynb Initializes a Gigachat agent with custom tools and binds them using `bind_functions`. This setup is necessary for the agent to recognize and utilize the defined functions during its operation. The `create_react_agent` function is used for this purpose. ```python functions = [PlayerReactionsTool()] giga_with_functions = giga.bind_functions(functions) agent_executor = create_react_agent(giga_with_functions, functions, checkpointer=MemorySaver(), debug=False) chat(agent_executor, thread_id="id_324") ``` -------------------------------- ### Initialize project directory Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/js/langgraph_quickstart.ipynb Create and enter a new directory for the LangGraph project. ```bash mkdir langgraph-agent cd langgraph-agent ``` -------------------------------- ### Generate Synonyms with Examples Source: https://github.com/ai-forever/gigachain/blob/master/hub/prompts/synonyms/README.md Use this snippet to generate synonyms for a given subject, optionally providing examples to guide the generation. Ensure the LLM chain is properly initialized. ```python from langchain_core.prompts import load_prompt from langchain.chains import LLMChain llm = ... synonyms_with_examples = load_prompt('synonyms_generation_with_examples.yaml') text = prompt.format(dataset_size_min=5, dataset_size_max=10, subject="кошка", examples='["кот", "котёнок"]') ``` -------------------------------- ### Check TagMe Platform Accessibility Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/tagme-agent/tagme-agent.ipynb Verifies that the TagMe platform is accessible by making a GET request. Ensure the `requests` library is installed. ```python import requests resp = requests.get("https://tagme.sberdevices.ru") assert resp.status_code == 200 ``` -------------------------------- ### Format Dates and Get Currency Rates Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/repl_graph/repl.ipynb Formats start and end dates for currency rate requests and retrieves the data. Displays a plot if data is available, otherwise prints an error message. ```python start_date_formatted = start_date.strftime('%d/%m/%Y') end_date_formatted = end_date.strftime('%d/%m/%Y') data = get_currency_rates(start_date_formatted, end_date_formatted) if data is not None and len(data) > 0: dates, values = zip(*data) # Построение графика plt.figure(figsize=(10,6)) plt.plot(dates, values, marker='o', linestyle='-', color='b') plt.title('Курс доллара США за последние 30 дней') plt.xlabel('Дата') plt.ylabel('Цена ($)') plt.grid(True) plt.show() else: print("Не удалось получить данные") ``` -------------------------------- ### Load and Format Basic QNA Prompt Source: https://github.com/ai-forever/gigachain/blob/master/hub/prompts/qna/README.md Demonstrates loading a QNA system prompt from a YAML file and formatting it with document text. Requires Langchain and a language model (LLM) to be initialized. ```python from langchain_core.prompts import load_prompt from langchain.chains import LLMChain llm = ...hub/ qna_system_prompt = load_prompt('qna_system.yaml') text = qna_system_prompt.format(text="... text of your documents ...") ``` -------------------------------- ### Initialize GigaChat and E2B Connections Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/repl_graph/repl.ipynb Sets up environment variables for GigaChat credentials and E2B API key, prompting the user if they are not already set. Defines the scope for GigaChat API access. ```python import getpass import os from dotenv import load_dotenv load_dotenv() if "GIGACHAT_CREDENTIALS" not in os.environ and "GIGACHAT_USER" not in os.environ: os.environ["GIGACHAT_CREDENTIALS"] = getpass.getpass("Credentials от GigaChat") if "E2B_API_KEY" not in os.environ: os.environ["E2B_API_KEY"] = getpass.getpass("Токен от E2B") scope = "GIGACHAT_API_PERS" # Возможно также: GIGACHAT_API_CORP / GIGACHAT_API_B2B ``` -------------------------------- ### Agent Response: Starting Annotation Wait Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/tagme-agent/tagme-agent.ipynb Signifies that the agent has started waiting for human annotation to be completed. ```text Result:\n👀 старт ожидания разметки ``` -------------------------------- ### Spotify Authentication Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/playlists.ipynb Set up Spotify API credentials as environment variables and initialize the Spotify client. Ensure you have your Spotify Client ID and Client Secret. ```python import json import sys import spotipy from langchain.agents import AgentExecutor, ZeroShotAgent from langchain.tools import Tool from spotipy.oauth2 import SpotifyClientCredentials os.environ["SP_ID"] = "" os.environ["SP_SECRET"] = "" spotify = spotipy.Spotify( client_credentials_manager=SpotifyClientCredentials( client_id=os.getenv("SP_ID"), client_secret=os.getenv("SP_SECRET") ) ) ``` -------------------------------- ### Start Annotation Wait Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/tagme-agent/tagme-agent.ipynb This snippet indicates that the system is now waiting for annotations to be completed. It signals the start of the annotation monitoring phase. ```text Result: 👀 старт ожидания разметки ``` -------------------------------- ### Initialize GigaChat Model Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/gigachat_qa.ipynb Sets up the GigaChat model with specified credentials, model name, and timeout settings. SSL certificate verification is disabled. ```python from langchain_gigachat.chat_models import GigaChat from langchain.schema import HumanMessage giga = GigaChat( credentials="ключ_авторизации", model="GigaChat-Pro", verify_ssl_certs=False, timeout=1200, ) ``` -------------------------------- ### Initialize GigaChat Language Model Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/tagme-agent/tagme-agent.ipynb Sets up the GigaChat language model with specific parameters. Requires the `langchain-gigachat` library. Note that `verify_ssl_certs` is set to `False`. ```python from langchain_gigachat import GigaChat llm = GigaChat( model="GigaChat-2-Max", verify_ssl_certs=False, top_p=0, profanity_check=False, timeout=600, ) ``` -------------------------------- ### Define Example Data for TagMe Task Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/tagme-agent/tagme-agent.ipynb Provides an example of the data structure for a TagMe task, including the task title and the name field which contains the question and answer. ```python example = { "task": "Оцените ответ модели на вопрос", "name": "Вопрос: кто ты Ответ: Я — GigaChat, виртуальный помощник от компании Sber. Могу поддержать разговор на любую тему, решить сложную задачу, объяснить непонятное явление или просто развлечь беседой. Чем займёмся?" } ``` -------------------------------- ### Initialize GigaChat Source: https://github.com/ai-forever/gigachain/blob/master/hub/prompts/nlp/nlp_examples.ipynb Initialize GigaChat with your credentials before working with prompts. Ensure you have obtained your authorization credentials. ```python from langchain_core.prompts import load_prompt from langchain_gigachat import GigaChat giga = GigaChat(credentials="<авторизационные_данные>") ``` -------------------------------- ### Generate Table with Gigachain Source: https://github.com/ai-forever/gigachain/blob/master/hub/prompts/content/content_examples.ipynb Load the table_generation.yaml prompt, initialize GigaChat, and invoke the chain with a text description to generate a table. Ensure you replace "<авторизационные_данные>" with your actual credentials. ```python from langchain_core.prompts import load_prompt from langchain_gigachat import GigaChat giga = GigaChat(credentials="<авторизационные_данные>", model="GigaChat-Pro") prompt = load_prompt("table_generation.yaml") chain = prompt | giga chain.invoke( { "text": "Столбцы: Предмет мебели, Краткое описание. В обычной квартире могут быть представлены самые разные предметы мебели. Например столы, стулья или кресла. Стол — предмет мебели, имеющий приподнятую горизонтальную или наклонную поверхность и предназначенный для размещения предметов, выполнения работ, принятия пищи, игр, рисования, обучения и другой деятельности. Стул — редмет мебели для сидения одного человека, с опорой для спины с подлокотниками или без них. Кресло — предмет мебели для комфортного продолжительного сидения, со спинкой, c подлокотниками или без них." } ).content ``` -------------------------------- ### Compare Pure vs RAG QA on Word vs Set Definition Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/gigachat_qa.ipynb Compares direct GigaChat output with RAG-enhanced output for a question differentiating 'word' and 'set' with an example. Useful for evaluating RAG's handling of definitions and examples. ```python """ Оригинал: Термин набор означает конечную последовательность элементов. Понятие набора отличается от понятия множества тем, что * в наборе могут быть одинаковые элементы, * порядок расположения элементов в наборе важен (наборы, состоящие из одинаковых элементов, расположенных в разном порядке, считаются различными). """ q = "Разница между словом и набором. Приведи пример." pure = giga([HumanMessage(content=q)]).content print(f"Pure: {pure}\n") rag = rag_chain.invoke({"input": q})["answer"] print(f"RAG: {rag}") ``` ```text Output: Pure: Слово — это лексическая единица языка, которая имеет определённое значение. Набор — это совокупность предметов, явлений, понятий, объединённых по какому-либо признаку. Пример: Слово «стол» — это лексическая единица русского языка, обозначающая предмет мебели для работы или приёма пищи. Набор столовых приборов — это совокупность различных предметов (ложек, вилок, ножей), которые используются во время еды. RAG: Разница между словом и набором заключается в том, что слово - это упорядоченная последовательность букв, в которой каждая буква может повторяться, тогда как набор - это просто последовательность элементов без учета их повторений или порядка. Пример: "мама" - это слово, потому что оно состоит из букв, которые могут повторяться ("м" и "а"), и порядок букв имеет значение. "ма", "ам", "ама" - это другие слова, но "мама" - единственное слово из этих трех. С другой стороны, набор "мама" будет содержать только одну запись, потому что набор не учитывает повторения элементов или их порядок. ``` -------------------------------- ### Configure API Access Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/agent_debates/README.md Set up your GigaChat API credentials and base URL in a .env file. Refer to the sample data for format. ```sh GIGACHAT_CREDENTIALS=ключ_авторизации GIGACHAT_BASE_URL=... ``` -------------------------------- ### Invoke RAG Chain Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/js/rag.ipynb Invoke the RAG chain with a specific question to get an answer based on the loaded documents. ```javascript await ragChain.invoke("Как установить сертификаты при подключении к GigaChat"); ``` -------------------------------- ### Experiment Evaluation Output Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/lean_canvas/lean_canvas_agent.ipynb This snippet shows the typical output during an experiment evaluation, indicating the start of the process and the progress bar. ```text 🧠 Evaluation started. ``` ```text running experiment evaluations |██████████| 30/30 (100.0%) | ⏳ 00:07<00:00 | 3.83it/s ``` -------------------------------- ### Initialize GigaChat with API Key Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/gigachat_phone_agent.ipynb Loads GigaChat API credentials from environment variables or prompts the user if not found. Initializes the GigaChat model. Ensure `GIGACHAT_CREDENTIALS` is set. ```python import getpass import os from dotenv import find_dotenv, load_dotenv from langchain_gigachat.chat_models import GigaChat load_dotenv(find_dotenv()) if "GIGACHAT_CREDENTIALS" not in os.environ: os.environ["GIGACHAT_CREDENTIALS"] = getpass.getpass("Введите ключ авторизации GigaChat API: ") model = GigaChat( model="GigaChat-2-Max", verify_ssl_certs=False, ) ``` -------------------------------- ### Assign Self as Annotator Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/tagme-agent/tagme-agent.ipynb Get the current user's UID and create an annotation pool with the user as the sole marker. This assigns the user as an annotator for a project. ```python self_person = await client.get_self_person() markers = [self_person.uid] pool = await client.create_pool( markers=markers, name="группа имени меня", ) ``` -------------------------------- ### Get All Phone Names Tool Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/gigachat_phone_agent.ipynb Defines a tool to retrieve all phone model names from the database. Use this when the agent needs a list of available phone models. ```python from typing import Dict from langchain.tools import tool @tool def get_all_phone_names() -> str: """Возвращает названия моделей всех телефонов через запятую""" # Подсвечивает вызов функции зеленым цветом print("\033[92m" + "Bot requested get_all_phone_names()" + "\033[0m") return ", ".join([stuff["name"] for stuff in stuff_database]) ``` -------------------------------- ### Create a New Project in TagMe Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/tagme-agent/tagme-agent.ipynb Creates a new project within the TagMe platform using the initialized client. This project is intended to help improve Gigachat's responses. Ensure the `client` object is properly initialized. ```python project = await client.create_project( name="giga answers improved project", # Имя вашего проекта description="Проект для помощи GigaChat лучше отвечать на вопросы", # Описание вашего проекта ) project ``` -------------------------------- ### Initialize GigaChat LLM with HTTPS Agent Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/js/rag.ipynb Initialize the GigaChat language model. This example includes an HTTPS agent that disables certificate verification, which might be necessary in certain Node.js environments but not in Deno. For Deno, consider setting NODE_EXTRA_CA_CERTS in your environment. ```javascript import { Agent } from 'node:https';\nimport { GigaChat } from "langchain-gigachat"\n/*\nВ обычном Node.js такое отключение проверки сертификатов срабатывает.\n\nНо в Deno нет, \nпоэтому используйте проставление NODE_EXTRA_CA_CERTS в env. \n*/\nconst httpsAgent = new Agent({\n rejectUnauthorized: false,\n}); \n\nconst llm = new GigaChat({\n maxRetries: 0,\n httpsAgent\n}) ``` -------------------------------- ### Define Zod Schema for Entity Extraction Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/js/extraction.ipynb Initialize a Zod schema to define the structure of entities to be extracted. This schema guides GigaChat on the expected output format. ```typescript import { z } from "zod"; const personSchema = z.object({ name: z.optional(z.string()).describe("Имя человека"), hair_color: z .optional(z.string()) .describe("Цвет волос, если известен"), height_in_meters: z.optional(z.number()) .describe("Высота в метрах"), }); ``` -------------------------------- ### Run HTTP MCP Client Agent Source: https://github.com/ai-forever/gigachain/blob/master/cookbook/mcp/README.md After starting the MCP server in SSE mode, run the HTTP client agent using the agent_http.py script for remote interaction. ```sh python agent_http.py ```