### Install GigaChain packages and Tavily Source: https://github.com/ai-forever/gigagraph/blob/main/README.md Install the required Python packages for the agent example: gigachain, gigachain_openai, and tavily-python. ```shell pip install -U gigachain gigachain_openai tavily-python ``` -------------------------------- ### Install required packages Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/multi_agent/agent_supervisor.ipynb Installs the necessary Python packages for the example: langgraph, langchain, langchain_openai, langchain_experimental, langsmith, and pandas. ```python %%capture --no-stderr %pip install -U langgraph langchain langchain_openai langchain_experimental langsmith pandas ``` -------------------------------- ### Install required packages for STORM Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/storm/storm.ipynb Install the necessary Python packages for the STORM tutorial. The first line installs core packages, while the second line is commented out and shows optional search services (DuckDuckGo, Tavily). ```python # %pip install -U gigachain_community gigachain_openai langgraph wikipedia scikit-learn # Используется один из заданных поисковых сервисов # %pip install -U duckduckgo tavily-python ``` -------------------------------- ### Install chromadb and gigachain Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/reflexion/advenced.ipynb Install the required Python packages for the notebook. ```python % pip install chromadb gigachain ``` -------------------------------- ### Create SQLDatabaseToolkit and get tools Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/sql_agent_react/sql-agent-react.ipynb Initializes the SQLDatabaseToolkit with the database and LLM, then retrieves the available tools. ```python from langchain_community.agent_toolkits import SQLDatabaseToolkit toolkit = SQLDatabaseToolkit(db=db, llm=llm) tools = toolkit.get_tools() ``` -------------------------------- ### Install LangGraph and langchain-gigachat Source: https://github.com/ai-forever/gigagraph/blob/main/README.md Install the recommended packages for the new workflow. It is important to install these packages in a clean Python environment. ```bash pip install langgraph langchain-gigachat ``` -------------------------------- ### Install Required Packages Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/reflexion/based.ipynb Install gigachain, gigagraph, and duckduckgo-search packages. These are commented out by default; uncomment to run. ```python # %pip install -U --quiet gigachain gigagraph # %pip install -U --quiet duckduckgo-search ``` -------------------------------- ### Install Playwright browser (commented out) Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/web-navigation/web_voyager.ipynb Shows the commands to install Playwright and its browser. These are commented out and need to be uncommented to run. ```python # %pip install --upgrade --quiet playwright > /dev/null # !playwright install ``` -------------------------------- ### First Tool Call Node Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/sql_agent_react/sql-agent-react.ipynb Creates an AIMessage to call the sql_db_list_tables tool, used to get table names for few-shot examples. ```python from langchain.agents.output_parsers import ReActSingleInputOutputParser from langchain_core.messages import AIMessage parser = ReActSingleInputOutputParser() def first_tool_call(state: State) -> dict[str, list[AIMessage]]: message = AIMessage( content="Action: sql_db_list_tables\n" + "Action Input: {}", ) return {"messages": [message], "steps": [parser.invoke(message)]} ``` -------------------------------- ### Initialize state and invoke first_responder Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/reflexion/based.ipynb Sets up an example question and state dictionary, then calls first_responder.respond and extracts the function call arguments from the last message. ```python example_question = "Как победить глобальное потепление" state = { 'messages': [HumanMessage(content=example_question)], 'references': [], 'iteration': 0, "question": example_question } state = {**state, **first_responder.respond(state)} state['messages'][-1].additional_kwargs['function_call']['arguments'] ``` -------------------------------- ### Example generated question output Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/storm/storm.ipynb Example output from the generate_question chain, showing a question about large language models and consciousness. ```text Result: 'Да, именно. Я хотел бы узнать больше о том, как большие языковые модели, такие как GPT-3, могут влиять на изучение сознания. Можете ли поделиться своими мыслями на этот счет?' ``` -------------------------------- ### Install required packages Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/sql_agent_react/sql-agent-react.ipynb Installs the gigagraph and gigachain-community packages via pip. ```bash !pip install gigagraph gigachain-community ``` -------------------------------- ### Install and configure GigaChat certificates Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/rag/langgraph_adaptive_rag_giga.ipynb Commands to install the gigachain-cli utility and then install Russian certificates (НУЦ Минцифры) for GigaChat. These steps are required for authorization. ```sh pip install gigachain-cli ``` ```sh gigachain install-rus-certs ``` -------------------------------- ### Invoke generate_question with example topic Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/storm/storm.ipynb Shows how to call the generate_question chain with an initial human message and an editor perspective, then prints the generated question content. ```python messages = [ HumanMessage(f"Итак, вы говорите, что пишете статью на тему {example_topic}?") ] question = await generate_question.ainvoke( { "editor": perspectives.editors[0], "messages": messages, } ) question["messages"][0].content ``` -------------------------------- ### Install required packages Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/rag/langgraph_adaptive_rag_giga.ipynb Installs necessary Python packages for the Adaptive RAG implementation, including gigachain_community, gigachain-openai, gigachain-cohere, langchainhub, chromadb, gigachain, gigagraph, and dotavily-python. ```python %%capture --no-stderr ! pip install -U gigachain_community tiktoken gigachain-openai gigachain-cohere langchainhub chromadb gigachain gigagraph dotavily-python dotenv ``` -------------------------------- ### Output: Generated outline for example topic Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/storm/storm.ipynb Shows the generated outline for the example topic, including sections on introduction, definition of consciousness in AI, problems, and potential solutions. ```text Output: # Проблема сознания у больших языковых моделей ## Введение Обзор проблемы сознания у больших языковых моделей и их влияния на различные области исследований. ## Определение сознания в контексте искусственного интеллекта Объяснение того, что представляет собой сознание в контексте искусственного интеллекта и как оно связано с языковыми моделями. ## Проблемы сознания у больших языковых моделей Обсуждение основных проблем, возникающих при обучении и использовании больших языковых моделей, связанных с сознанием. ## Потенциальные решения Изучение возможных подходов и методов для преодоления проблемы сознания у больших языковых моделей. ``` -------------------------------- ### Install graphviz and pygraphviz for graph diagrams Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/storm/storm.ipynb Optional installation for generating graph diagrams. On macOS, run 'brew install graphviz' first and set CFLAGS and LDFLAGS environment variables before installing pygraphviz. ```python # Для генерации диаграм графов раскомментируйте строки. # Если вы работаете на MacOS, вам нужно будет запустить brew install graphviz перед установкой и обновить некоторые флаги окружения. # ! brew install graphviz # !CFLAGS="-I $(brew --prefix graphviz)/include" LDFLAGS="-L $(brew --prefix graphviz)/lib" pip install -U pygraphviz ``` -------------------------------- ### Install required Python packages Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/web-navigation/web_voyager.ipynb Installs the gigagraph, langsmith, and gigachain_openai packages using pip. This is the first step in setting up the environment for the Web Voyager agent. ```python %pip install -U --quiet gigagraph langsmith gigachain_openai ``` -------------------------------- ### Example output of reflection responder Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/reflexion/advenced.ipynb Shows the result of the reflection responder, containing a reflection and search queries. ```text Result: {'reflection': 'Твой ответ слишком общий и не предлагает конкретных решений. Как насчет предложения мер по адаптации к изменению климата?', 'search_queries': ['меры по адаптации к изменению климата', 'конкретные действия для борьбы с глобальным потеплением']} ``` -------------------------------- ### StateGraph Usage Example Source: https://github.com/ai-forever/gigagraph/blob/main/README.md Shows how to initialize and compile a StateGraph with AgentState. Inputs must be a dictionary because the state is a TypedDict; agent_outcome defaults to None and intermediate_steps defaults to an empty list due to operator.add. ```python # Инициализируйте StateGraph с помощью состояния AgentState graph = StateGraph(AgentState) # Создайте вершины и ребра ... # Скомпилируйте граф app = graph.compile() # На вход должен передаваться словарь, так как состояние создано как TypedDict inputs = { # Пример входный данныъ "input": "hi" # Предположим, что `agent_outcome` задается графом как некоторая точка # Передавать значение не нужно, по умолчанию оно будет None # Предположим, что граф со временем наполняет `intermediate_steps` # Передавать значение не нужно, по умолчанию список будет пустым # Список `intermediate_steps` будет представлен в виде пустого списка, а не None потому, # что он аннотирован с помощью `operator.add` } ``` -------------------------------- ### Setup browser and define call_agent helper function Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/web-navigation/web_voyager.ipynb Initializes a Playwright browser in headless=False mode and defines an async function call_agent that streams agent events, displays intermediate screenshots, and returns the final answer. The function uses a graph object with astream and expects a page, question, and scratchpad. ```python from IPython import display from playwright.async_api import async_playwright browser = await async_playwright().start() # We will set headless=False so we can watch the agent navigate the web. browser = await browser.chromium.launch(headless=False, args=None) page = await browser.new_page() _ = await page.goto("https://www.google.com") async def call_agent(question: str, page, max_steps: int = 150): event_stream = graph.astream( { "page": page, "input": question, "scratchpad": [], }, { "recursion_limit": max_steps, }, ) final_answer = None steps = [] async for event in event_stream: # We'll display an event stream here if "agent" not in event: continue pred = event["agent"].get("prediction") or {} action = pred.get("action") action_input = pred.get("args") display.clear_output(wait=False) steps.append(f"{len(steps) + 1}. {action}: {action_input}") print("\n".join(steps)) display.display(display.Image(base64.b64decode(event["agent"]["img"]))) if "ANSWER" in action: final_answer = action_input[0] break return final_answer ``` -------------------------------- ### Example question about sign language Source: https://github.com/ai-forever/gigagraph/blob/main/examples/rag/langgraph_agentic_rag.ipynb Calls the qna function with a Russian question asking what sign language is, demonstrating a query that does not require additional retrieval. ```python qna("Что такое жестовый язык?") ``` -------------------------------- ### Define tools with TavilySearchResults Source: https://github.com/ai-forever/gigagraph/blob/main/README.md Create a list of tools using TavilySearchResults with max_results=1. This is the example tool used in the agent. ```python from langchain_community.tools.tavily_search import TavilySearchResults tools = [TavilySearchResults(max_results=1)] ``` -------------------------------- ### Generate initial outline for example topic Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/storm/storm.ipynb Invokes the outline generation chain with a sample topic and prints the resulting outline. The topic is 'Проблема сознания у больших языковых моделей моделей' (note the duplicate 'моделей'). ```python example_topic = "Проблема сознания у больших языковых моделей моделей" initial_outline = generate_outline_direct.invoke({"topic": example_topic}) print(initial_outline.as_str) ``` -------------------------------- ### Example output of revise_respond Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/reflexion/advenced.ipynb Shows the printed output after invoking revise_respond. The output includes the 'combine answer' message and the updated answer text. ```text Output: combine answer Для победы над глобальным потеплением требуется комплексный подход. Важными мерами являются сокращение выбросов парниковых газов путем снижения использования ископаемого топлива и увеличения использования возобновляемых источников энергии, повышение энергоэффективности и озеленение городов. Однако, помимо этого, необходимо также принимать меры по адаптации к уже запущенным климатическим изменениям. Это может включать внесение масштабных изменений в инфраструктуру, учет будущих рисков при проектировании текущей инфраструктуры, а также применение природных подходов, таких как сохранение и восстановление лесов, болот и мангровых зарослей. В индивидуальном плане каждый человек может внести свой вклад в борьбу с глобальным потеплением. Например, можно использовать свой голос в качестве потребителя, клиента, члена избирателей и активного гражданина, присоединиться к социальным движениям или кампаниям, связанным с экологической деятельностью, перейти на растительную диету, использовать возобновляемые источники энергии в своем доме, ходить пешком, ездить на велосипеде или использовать общественный транспорт вместо автомобиля, а также перейти на электромобиль. Все эти действия помогут сократить выбросы парниковых газов и улучшить общую ситуацию с изменением климата. ``` -------------------------------- ### Tavily Web Search Tool Setup Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/rag/langgraph_adaptive_rag_giga.ipynb Initializes a TavilySearchResults tool with k=3 for web search. Used later in the web_search node to retrieve additional documents. ```python ### Search from langchain_community.tools.tavily_search import TavilySearchResults web_search_tool = TavilySearchResults(k=3) ``` -------------------------------- ### ReviseAnswer class and revision_chain setup Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/reflexion/based.ipynb Defines revise_instructions and a ReviseAnswer class extending AnswerQuestion with fields for answer, reflection, search_queries, and references. Then builds revision_chain using actor_prompt_template, llm.bind_tools, and a validator, and creates a revisor ResponderWithRetries. ```python revise_instructions = """Дополни существующий ответ, ответь на критику с помощью функции ReviseAnswer. * Перепиши ответ, отвечая на свою критику, добавь информацию из результатов поиска ниже * Покритикуй свой новый дополненный ответ и создай новые поисковые запросы """ # noqa # Расширяем функцию ответа на вопрос, для того, чтобы мы могли добавлять источники к ответам class ReviseAnswer(AnswerQuestion): """Функция ответа на вопрос пользователя. Дополни предыдущий ответ, ответь на критику. Сделай новую критику своего дополненного ответа и создай новые ссылки. Возвращает результаты поиска. Дополни дальше свой ответ исходя из них""" answer: str = Field(description="Новый ответ на вопрос пользователя") reflection: str = Field( description="Критика нового ответа. Что в нем можно дополнить?" ) search_queries: List[str] = Field( description="1–3 поисковых запроса, которые позволят решить критику и дополнить твой новый ответ" # noqa ) references: List[str] = Field( description="Ссылки на источники информации, которые ты использовал в своем ответе." ) revision_chain = actor_prompt_template.partial( first_instruction=revise_instructions ) | llm.bind_tools(tools=[ReviseAnswer], tool_choice="ReviseAnswer") revision_validator = PydanticOutputFunctionsParser(pydantic_schema=ReviseAnswer) revisor = ResponderWithRetries(runnable=revision_chain, validator=revision_validator) ``` -------------------------------- ### Initialize SQLDatabase and run query Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/sql_agent_react/sql-agent-react.ipynb Creates a SQLDatabase instance from the Chinook SQLite file, prints the dialect and usable table names, and runs a sample query on the Artist table. ```python from langchain_community.utilities import SQLDatabase db = SQLDatabase.from_uri("sqlite:///Chinook.db") print(db.dialect) print(db.get_usable_table_names()) db.run("SELECT * FROM Artist LIMIT 10;") ``` -------------------------------- ### Initialize state and invoke answer_respond Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/reflexion/advenced.ipynb Sets up the initial state dictionary with the user's question and empty fields for reflection, search, and results. Calls answer_respond to generate the initial answer and updates the state with the new values. ```python state = { "messages": [], "iteration": 1, "question": "Как победить глобальное потепление?", "current_answer": "", "reflection": "", "search_queries": [], "search_results": {}, "downloaded_urls": set(), "finish": False, "lang": "en" } new_state = answer_respond(state) state = {**state, **new_state} state['current_answer'] ``` -------------------------------- ### Set up LangSmith tracing (optional) Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/web-navigation/web_voyager.ipynb Prompts for the OPENAI_API_KEY environment variable if not already set. This is optional but recommended for tracing and debugging agent actions. ```python # Необязательно: добавьте отслеживание для визуализации работы агента import os from getpass import getpass def _getpass(env_var: str): if not os.environ.get(env_var): os.environ[env_var] = getpass(f"{env_var}=") _getpass("OPENAI_API_KEY") ``` -------------------------------- ### Initialize GigaChat LLM Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/reflexion/based.ipynb Create a GigaChat instance with profanity check disabled, SSL verification off, a 600-second timeout, and the GigaChat-Pro model. Replace with your credentials. ```python llm = GigaChat( ## Тут ваши данные для входа profanity_check=False, verify_ssl_certs=False, timeout=600, model="GigaChat-Pro", top_p=0.8, ) ``` -------------------------------- ### Run graph with sample question (GigaChat API) Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/rag/langgraph_adaptive_rag_giga.ipynb Executes the compiled graph with a question about GigaChat API authorization, streaming node outputs and printing the final generation. ```python # Run inputs = {"question": "Как авторизоваться в gigachat api"} for output in app.stream(inputs): for key, value in output.items(): # Node pprint(f"Node '{key}':") pprint("---") # Final generation pprint(value["generation"]) ``` -------------------------------- ### .add_edge(start_key, end_key) Source: https://github.com/ai-forever/gigagraph/blob/main/README.md Creates an edge connecting a start node to an end node. The output of the start node is passed to the end node. ```APIDOC ## .add_edge(start_key, end_key) ### Description Creates an edge connecting a start node to an end node. The output of the start node is passed to the end node. ### Method add_edge ### Parameters - **start_key** (str) - Required - Name of the start node. Must be registered in the graph. - **end_key** (str) - Required - Name of the end node. Must be registered in the graph. ### Signature ```python def add_edge(self, start_key: str, end_key: str) -> None: ``` ``` -------------------------------- ### Example refined outline output Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/storm/storm.ipynb Example output of the refined outline for the topic 'Проблема сознания у больших языковых моделей'. It shows the structure with sections and subsections. ```text # Проблема сознания у больших языковых моделей ## Введение Обзор проблемы сознания у больших языковых моделей и их влияния на различные области исследований. ## Определение сознания в контексте искусственного интеллекта Объяснение того, что представляет собой сознание в контексте искусственного интеллекта и как оно связано с языковыми моделями. ## Технические аспекты и вызовы Обсуждение технических аспектов и вызовов, связанных с большими языковыми моделями, включая предвзятость и справедливость, конфиденциальность и безопасность данных, мультимодальное обучение и интеграцию, этический ИИ и надежные LLM, подготовка данных, модельная архитектура и дизайн, учебный процесс, оценка производительности модели и обучение LLM. ### Предвзятость и справедливость Методы и инструменты для оценки предвзятости и справедливости, включая оценку справедливости, дебиасинг моделей и критический обзор литературы о предвзятости. ### Конфиденциальность и безопасность данных Меры для обеспечения конфиденциальности данных и безопасности, включая безопасное удаление данных, методы маскирования данных и обновление моделей. ### Мультимодальное обучение и интеграция Методы и принципы мультимодального обучения и интеграции, включая объединение различных типов данных и совместное обучение моделей. ### Оценка производительности модели Методы и инструменты для оценки производительности моделей, включая метрики точности, полноты, BLEU и ROUGE. ## Потенциальные решения Изучение возможных подходов и методов для преодоления проблемы сознания у больших языковых моделей. ``` -------------------------------- ### SQL Agent Prompt Template with SQL_PREFIX and ChatPromptTemplate Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/sql_agent_react/sql-agent-react.ipynb Defines the SQL_PREFIX instructions for the SQL agent, including constraints like LIMIT to top_k results, no DML statements, and using only provided tools. Then builds a ChatPromptTemplate with the system template, a user message, and a MessagesPlaceholder for conversation history. ```python from langchain_core.prompts import MessagesPlaceholder, ChatPromptTemplate SQL_PREFIX = """Ты специалист по SQL базам данных. Получив входной вопрос ("Question"), создай синтаксически правильный запрос {dialect} для выполнения, затем посмотри на результаты запроса и верни ответ. Если пользователь не указывает конкретное количество примеров, которые он хочет получить, ОБЯЗАТЕЛЬНО ограничивай свой запрос максимумом {top_k} результатов (LIMIT). Ты можешь упорядочить результаты по релевантной колонке, чтобы вернуть наиболее интересные примеры из базы данных. Никогда не запрашивай все колонки из конкретной таблицы, запрашивай только релевантные колонки, учитывая вопрос. НЕ делай никаких DML-заявлений (INSERT, UPDATE, DELETE, DROP и т.д.) в базе данных. Всегда свой ответ выводи с помощью Final Answer. Пример: Final Answer: твой ответ Если вопрос, не связан с базой данных, верни свой ответ в Final Answer! Пример: Final Answer: твой ответ У тебя есть инструменты для взаимодействия с базой данных. Используй только приведенные ниже инструменты. Используй только информацию, возвращенную приведенными ниже инструментами, чтобы составить свой окончательный ответ. У тебя есть набор следующих инструментов: """ template = "\n\n".join( [ SQL_PREFIX, "{tools}", REACT_FORMAT_INSTRUCTIONS, """Question: "{input}" Thought: Ты должен следовать следующим шагам: 1. посмотреть на таблицы в базе данных, чтобы увидеть, что я могу запросить. 2. Затем тебе следует запросить схему ВСЕХ РЕЛЕВАНТНЫХ таблиц, которые будут участвовать в запросе 3. Написать запрос. """, ] ) prompt = ChatPromptTemplate.from_messages( [ ("system", template), ( "user", "Начинаем!", ), MessagesPlaceholder("messages"), ] ) ``` -------------------------------- ### add_edge Method Signature Source: https://github.com/ai-forever/gigagraph/blob/main/README.md Creates an edge connecting start and end nodes. The output of the start node is passed to the end node. Both node names must be registered in the graph. ```python def add_edge(self, start_key: str, end_key: str) -> None: ``` -------------------------------- ### Output: Reflection Step Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/reflexion/advenced.ipynb Shows the reflection output criticizing the initial answer and listing search queries. ```text Output: ## 2. reflect Критика: Твой ответ не содержит никакой информации или мнения о том, выиграет ли Дональд Трамп на выборах 2024 года. Что будем искать: ['выборы США 2024', 'Дональд Трамп прогнозы выборов'] --- ``` -------------------------------- ### Invoke revise_respond and print updated answer Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/reflexion/advenced.ipynb Updates the state by calling revise_respond and prints the new current_answer. This is the usage example for the revision chain. ```python state = {**state, **revise_respond(state)} print(state["current_answer"]) ``` -------------------------------- ### Assemble agent with LLM and chain Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/web-navigation/web_voyager.ipynb Creates the agent by combining the annotate function, format_descriptions, prompt, GPT-4V model, and parser into a runnable chain. Uses the 'gpt-4-vision-preview' model with max_tokens set to 4096. ```python llm = ChatOpenAI(model="gpt-4-vision-preview", max_tokens=4096) agent = annotate | RunnablePassthrough.assign( prediction=format_descriptions | prompt | llm | StrOutputParser() | parse ) ``` -------------------------------- ### Установка начальной точки графа Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/introduction.ipynb Добавление ребра от START к узлу chatbot, определяющего точку входа в граф. ```python graph_builder.add_edge(START, "chatbot") ``` -------------------------------- ### Output: Initial Draft Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/reflexion/advenced.ipynb Shows the output of the first draft step, which returns 'NEED_INFO'. ```text Output: ## 1. draft Ответ: NEED_INFO --- ``` -------------------------------- ### Create graph builder and add chatbot and tools nodes Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/introduction.ipynb Initializes the StateGraph and adds the chatbot and tools nodes. The tools node uses the DuckDuckGoSearchRun tool. ```python graph_builder = StateGraph(State) graph_builder.add_node("chatbot", chatbot) graph_builder.add_node("tools", ToolNode(tools=[tool])) ``` -------------------------------- ### .add_conditional_edges(start_key, condition, conditional_edge_mapping) Source: https://github.com/ai-forever/gigagraph/blob/main/README.md Creates a conditional edge that determines the next node based on the result of the start node's execution. ```APIDOC ## .add_conditional_edges(start_key, condition, conditional_edge_mapping) ### Description Creates a conditional edge that determines the next node based on the result of the start node's execution. ### Method add_conditional_edges ### Parameters - **start_key** (str) - Required - Name of the start node. Must be registered in the graph. - **condition** (Callable[..., str]) - Required - Function called to determine the path. Takes the result of the start node and returns a string that must be a key in `conditional_edge_mapping`. - **conditional_edge_mapping** (Dict[str, str]) - Required - Mapping of edge names to downstream nodes. Keys are possible return values of `condition`; values are the nodes to call. ### Signature ```python def add_conditional_edges( self, start_key: str, condition: Callable[..., str], conditional_edge_mapping: Dict[str, str], ) -> None: ``` ``` -------------------------------- ### Extract tool calls from last message Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/introduction.ipynb Gets the last message from the snapshot and accesses its tool_calls attribute to inspect the pending tool call. ```python existing_message = snapshot.values["messages"][-1] existing_message.tool_calls ``` -------------------------------- ### Initialize chat model with streaming Source: https://github.com/ai-forever/gigagraph/blob/main/README.md Create a ChatOpenAI model with temperature=0 and streaming=True. The model must support message lists and function calling. ```python from langchain_openai import ChatOpenAI from langgraph.checkpoint import MemorySaver from langgraph.graph import END, StateGraph, MessagesState from langgraph.prebuilt import ToolNode # Параметр streaming=True включает потоковую передачу токенов # Подробнее в разделе Потоковая передача. model = ChatOpenAI(temperature=0, streaming=True) ``` -------------------------------- ### AgentState TypedDict Definition Source: https://github.com/ai-forever/gigagraph/blob/main/README.md Defines the state structure for the graph. The 'agent_outcome' field starts as None, and 'intermediate_steps' uses operator.add to accumulate steps rather than overwrite. ```python class AgentState(TypedDict): # Входная строка input: str # The outcome of a given call to the agent # Needs `None` as a valid type, since this is what this will start as # Результат вызова агента # Должен принимать `None` в качестве валидного типа, так как это начальное значение agent_outcome: Union[AgentAction, AgentFinish, None] # Список действий и соответвтующих шагов # Аннотация `operator.add` указывает что состояние должно дополняться (ADD) новыми данными, # а не перезаписываться intermediate_steps: Annotated[list[tuple[AgentAction, str]], operator.add] ``` -------------------------------- ### Get graph state snapshot and next node Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/introduction.ipynb Retrieves the current graph state and checks the 'next' attribute to confirm the graph is interrupted at the tools node. ```python snapshot = graph.get_state(config) snapshot.next ``` -------------------------------- ### Import create_react_agent Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs/reference/prebuilt.md Import the create_react_agent function from langgraph.prebuilt to create a prebuilt ReAct agent. ```python from langgraph.prebuilt import create_react_agent ``` -------------------------------- ### Invoke refine outline chain Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/storm/storm.ipynb Invokes the refine_outline_chain with the example topic, the initial outline as a string, and the conversations from the final state. The conversations are formatted with expert names and content. ```python refined_outline = refine_outline_chain.invoke( { "topic": example_topic, "old_outline": initial_outline.as_str, "conversations": "\n\n".join( f"### {m.name}\n\n{m.content}" for m in final_state["messages"] ), } ) ``` -------------------------------- ### Add edges and compile graph with interrupt_before Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/introduction.ipynb Adds edges from 'tools' and 'human' to 'chatbot', and from START to 'chatbot'. Compiles with MemorySaver and interrupt_before=['human'] to pause before the human node. ```python # The rest is the same graph_builder.add_edge("tools", "chatbot") graph_builder.add_edge("human", "chatbot") graph_builder.add_edge(START, "chatbot") memory = MemorySaver() graph = graph_builder.compile( checkpointer=memory, # We interrupt before 'human' here instead. interrupt_before=["human"], ) ``` -------------------------------- ### ReAct Format Instructions with Human Feedback Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/sql_agent_react/sql-agent-react.ipynb Defines the REACT_FORMAT_INSTRUCTIONS string that instructs the agent to execute one function per request, use a Thought/Action/Action Input/Observation loop, and return to the loop if the human asks a follow-up question after the final answer. ```python REACT_FORMAT_INSTRUCTIONS = """ За один запрос ты можешь выполнить одну функцию Question: *изначальный вопрос пользователя* Используй следующий формат: ----- [Начало цикла] Thought: Введи здесь Мысль, что ты должен сделать Action: [название функции, должно быть из списка [{tool_names}]] Action Input: [параметры для функции] Observation: Результат выполнения функции [Конец цикла] ------ Цикл с вопросами может выполняться N раз Thought -> Action -> Action Input -> Observation Если в результате выполнения функции ты не получил финальный ответ, выполни цикл еще раз Когда ты знаешь окончательный ответ ты должен написать ----- Thought: Теперь я знаю окончательный ответ Final Answer: окончательный ответ на исходный вопрос ----- Если у человека после твоего окончательного ответа возник вопрос (Human), возвращайся в начало цикла """ ``` -------------------------------- ### Instantiate ToolExecutor with tools Source: https://github.com/ai-forever/gigagraph/blob/main/README.md Creates a ToolExecutor with a list of tools. Pass an AgentAction to automatically determine the appropriate tool and input. ```python tools = [...] tool_executor = ToolExecutor(tools) ``` -------------------------------- ### Output of RAG generation with GigaChat Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/rag/langgraph_adaptive_rag_giga.ipynb Shows the printed output from the generation chain. It includes instructions about GigaChat certificate setup and answers about transformer architecture and chatbot identity. ```text Output: Чтобы авторизоваться в GigaChat, необходимо установить сертификаты НУЦ Минцифры и настроить их в соответствии с официальной документацией. Также можно использовать утилиту `gigachain-cli` для установки сертификатов. Если вы не используете сертификат НУЦ Минцифры, то при создании объекта `GigaChat` нужно передать параметр `verify_ssl_certs=False`. Трансформерная архитектура - это тип архитектуры нейронных сетей, используемый в глубоком обучении, особенно в области обработки естественного языка. Она была впервые предложена в 2017 году и с тех пор стала одной из самых популярных архитектур для задач машинного обучения. Нет, я не чатбот. Чтобы подключить сертификат НУЦ Минцифры к GigaChat, необходимо установить сертификаты с помощью утилиты `gigachain-cli`. Для этого нужно выполнить следующие шаги: 1. Установить утилиту с помощью менеджера пакетов pip: ```sh pip install gigachain-cli ``` 2. Установить сертификаты: ```sh gigachain install-rus-certs ``` Если вы не используете сертификат НУЦ Минцифры, то при создании объекта `GigaChat` вам нужно передать параметр `verify_ssl_certs=False`. ``` -------------------------------- ### Output: page fetching progress Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/reflexion/advenced.ipynb Shows the progress bars from fetching pages during the search, indicating 5 pages downloaded in about 3 and 1 seconds respectively. ```text Fetching pages: 100%|##########| 5/5 [00:03<00:00, 1.53it/s] Fetching pages: 100%|##########| 5/5 [00:01<00:00, 2.65it/s] ``` -------------------------------- ### add_conditional_edges Method Signature Source: https://github.com/ai-forever/gigagraph/blob/main/README.md Creates a conditional edge. The condition callable receives the start node's output and returns a string key in conditional_edge_mapping to determine which edge to take. ```python def add_conditional_edges( self, start_key: str, condition: Callable[..., str], conditional_edge_mapping: Dict[str, str], ) -> None: ``` -------------------------------- ### Set environment variables for LangChain and API keys Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/storm/storm.ipynb Defines a helper function to prompt for environment variables if not already set. Sets LANGCHAIN_TRACING_V2 to 'false' and LANGCHAIN_PROJECT to 'STORM', then prompts for LANGCHAIN_API_KEY and OPENAI_API_KEY. ```python import getpass import os def _set_env(var: str): if os.environ.get(var): return os.environ[var] = getpass.getpass(var + ":") # Set for tracing os.environ["LANGCHAIN_TRACING_V2"] = "false" os.environ["LANGCHAIN_PROJECT"] = "STORM" _set_env("LANGCHAIN_API_KEY") _set_env("OPENAI_API_KEY") ``` -------------------------------- ### Get state snapshot after interruption Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/introduction.ipynb Retrieves the current graph state and prints the next nodes. After the LLM calls RequestAssistance, the state is interrupted before 'human', so snapshot.next returns ('human',). ```python snapshot = graph.get_state(config) snapshot.next ``` -------------------------------- ### Invoke reflection responder and extract arguments Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/reflexion/advenced.ipynb Calls the reflection responder with the current state and extracts the function call arguments from the last message. This is used to get the reflection and search queries. ```python state = {**state, **reflection_responder.respond(state)} state["messages"][-1].additional_kwargs["function_call"]["arguments"] ``` -------------------------------- ### Partially fill prompt with tool descriptions Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/sql_agent_react/sql-agent-react.ipynb Uses render_text_description to format the tools list and partially fills the prompt with tool descriptions, tool names, dialect, and top_k. ```python from langchain.tools.render import render_text_description prompt = prompt.partial( tools=render_text_description(list(tools)), tool_names=", ".join([t.name for t in tools]), dialect=toolkit.dialect, top_k=10, ) ``` -------------------------------- ### Run graph with sample question (Euro 2024) Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/rag/langgraph_adaptive_rag_giga.ipynb Executes the compiled graph with a question about Euro 2024, streaming node outputs and printing the final generation. The output shows the decision flow and the generated answer. ```python from pprint import pprint # Run inputs = { "question": "Кто победил в Евро 2024 по футболу?" } for output in app.stream(inputs): for key, value in output.items(): # Node pprint(f"Node '{key}':") # Optional: print full state at each node # pprint(f"Value: {value}", indent=2, width=80, depth=None) pprint("---") # Final generation pprint(value["generation"]) ``` ```text Output: ---ВЫБОР ИСТОЧНИКА ПОИСКА ЗНАНИЙ--- ---ПОИСК ЗНАНИЙ В: WEB SEARCH--- ---WEB ПОИСК--- "Node 'web_search':" '---' ---ГЕНЕРАЦИЯ ОТВЕТА--- ('Сгенерирован ответ: Победителем Евро 2024 стала сборная Испании, которая ' 'обыграла Англию со счетом 2:1.') ---ПРОВЕРКА ГАЛЛЮЦИНАЦИЙ--- ---РЕШЕНИЕ: ОТВЕТ ОСНОВАН НА ДОКУМЕНТАХ--- ---ОТВЕЧАЕТ ЛИ ОТВЕТ НА ВОПРОС?--- ---РЕШЕНИЕ: ОТВЕТ ОТВЕЧАЕТ НА ВОПРОС--- "Node 'generate':" '---' ('Победителем Евро 2024 стала сборная Испании, которая обыграла Англию со ' 'счетом 2:1.') ``` -------------------------------- ### Import ToolNode Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs/reference/prebuilt.md Import the ToolNode class from langgraph.prebuilt to create a node that executes tools. ```python from langgraph.prebuilt import ToolNode ``` -------------------------------- ### Print next node and config of the replay state Source: https://github.com/ai-forever/gigagraph/blob/main/docs/docs_ru/tutorials/introduction.ipynb Prints the next node and the config of the selected replay state, confirming that the next node is 'tools'. ```python print(to_replay.next) print(to_replay.config) ```