<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Lorenzo Favaro on Medium]]></title>
        <description><![CDATA[Stories by Lorenzo Favaro on Medium]]></description>
        <link>https://medium.com/@lorenzofavaro?source=rss-74ad312f5896------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Tqt-cGg0xbl8LkGi64wzDQ.png</url>
            <title>Stories by Lorenzo Favaro on Medium</title>
            <link>https://medium.com/@lorenzofavaro?source=rss-74ad312f5896------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 11:38:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lorenzofavaro/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building an Agentic GraphRAG System with LangGraph and Neo4j]]></title>
            <link>https://blog.cubed.run/building-an-agentic-graphrag-system-with-langgraph-and-neo4j-f4d6c7f8dcd3?source=rss-74ad312f5896------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4d6c7f8dcd3</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[graphrag]]></category>
            <category><![CDATA[neo4j]]></category>
            <dc:creator><![CDATA[Lorenzo Favaro]]></dc:creator>
            <pubDate>Wed, 25 Mar 2026 08:50:14 GMT</pubDate>
            <atom:updated>2026-03-25T08:50:14.560Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jjwagi7DxD4JVWq8F2lpAQ.png" /><figcaption>Image by <a href="https://medium.com/@lorenzofavaro">author</a>: Graph RAG illustration</figcaption></figure><ol><li>❓Introduction: Naive vs Graph RAG</li><li>🧠 Project overview</li><li>📊 Results</li><li>🔚 Conclusion</li></ol><p>In this article, I present a comprehensive <strong>GraphRAG</strong> multi-agent system built with <strong>LangGraph</strong> that serves as an intelligent food assistant. While I’ve chosen meal planning as the demonstration domain, this architecture represents a versatile framework applicable across numerous sectors where complex, multi-faceted queries require structured knowledge retrieval.</p><p>The system handles complex scenarios across three key domains: <strong>recipe discovery</strong> with dietary constraints, <strong>shopping list generation</strong> for specific recipes, and <strong>store product location</strong> mapping within supermarkets. By combining semantic search for fuzzy matching with precise Cypher queries for structured data retrieval, the assistant performs <strong>multi-step reasoning</strong> over a <strong>Neo4j knowledge graph</strong> to deliver contextually relevant responses to nuanced queries.</p><p><a href="https://github.com/lorenzofavaro/meal-planner-graphrag">Github repo HERE!</a></p><h3>1. Introduction: Naive RAG vs Graph RAG</h3><p>For the purpose of this project, a Naive RAG approach is not sufficient for the following reasons:</p><ul><li><strong>No Structured Relationship Modeling:</strong> Naive RAG retrieves information from unstructured text, lacking the ability to represent and reason over explicit relationships between entities. This limits its effectiveness for queries that require understanding how different pieces of information are connected.</li><li><strong>Limited Multi-Hop Reasoning:</strong> It processes queries at a single level, making it difficult to answer questions that require traversing multiple data points or combining information from various sources within a structured context.</li><li><strong>Lack of Explainability:</strong> Because retrieval is based solely on text similarity, it is challenging to trace how an answer was constructed or to provide transparent reasoning paths.</li></ul><p>A Graph RAG system was therefore implemented to address all these issues. A graph-based framework, in fact, allows for:</p><ul><li><strong>Explicit Relationship Representation:</strong> Entities and their connections are modeled directly in a knowledge graph, enabling the system to understand and utilize the structure of the data.</li><li><strong>Multi-Hop and Contextual Reasoning:</strong> The system can traverse the graph to perform multi-step reasoning, combining information across related nodes to answer complex queries.</li><li><strong>Schema-Driven Retrieval:</strong> By leveraging the graph’s schema, queries can be precisely formulated and results are consistent with the underlying data model.</li><li><strong>Improved Explainability:</strong> The reasoning path for each answer can be traced through the graph, providing clear explanations and greater transparency.</li></ul><p>Such functionality makes Graph RAG systems a more robust and reliable solution for applications where structured data, complex relationships, and explainability are essential.</p><h3>2. Project overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BdLAqFlQv2rR12gcqJLbbg.png" /><figcaption>Image by <a href="https://medium.com/@lorenzofavaro">author</a>: Agentic Graph RAG diagram</figcaption></figure><p><strong>GraphRAG Workflow Steps:</strong></p><ol><li><strong>Query Analysis and Routing:</strong> The user’s request is first <strong>analyzed</strong> and <strong>classified</strong>, allowing the system to route it to the appropriate workflow node. Depending on the query, the system may <strong>proceed to the next step</strong> (research plan generation), <strong>prompt the user for clarification</strong>, or <strong>respond immediately</strong> if the request is <strong>out of scope</strong>.</li><li><strong>Research Plan Generation:</strong> The system constructs a detailed, step-by-step research plan tailored to the complexity of the user’s query. This plan outlines the specific actions required to fulfill the request.</li><li><strong>Research Graph Execution:</strong> For each step in the research plan, a dedicated <strong>subgraph is invoked</strong>. The system generates Cypher queries via LLMs, targeting the Neo4j knowledge graph. Relevant nodes and relationships are retrieved using a hybrid approach that combines <strong>semantic search</strong> and structured <strong>graph queries</strong>, ensuring both breadth and precision in the results.</li><li><strong>Answer Generation:</strong> Leveraging the retrieved graph data, the system synthesizes a <strong>comprehensive response</strong> using an LLM, integrating information from multiple sources as needed.</li></ol><p>For the creation of the graph, there are different choices based on your needs. <strong>I built the graph by myself</strong> <strong>with sample data</strong> to go faster but various tools can be used. <br>In the following we see <a href="https://python.langchain.com/docs/how_to/graph_constructing/">one technique</a> using an LLM, with Langchain.</p><h3>Building Neo4J Graph using an LLM</h3><p>The selection of the LLM model significantly influences the output by determining the accuracy and nuance of the extracted graph data.</p><pre>import os<br>from langchain_openai import ChatOpenAI<br><br>os.environ[&quot;OPENAI_API_KEY&quot;] = &quot;your-openai-api-key&quot;<br>llm = ChatOpenAI(temperature=0, model_name=&quot;gpt-4o&quot;)</pre><p>TheLLMGraphTransformerconverts text documents into structured graph documents by leveraging a LLM to parse and categorize entities and their relationships. <br>We have the flexibility to define specific types of nodes and relationships for extraction according to our requirements.</p><p>For example, we might want to have the following nodes:</p><ul><li>Recipe</li><li>Foodproduct</li></ul><p>And the following relationships:</p><ul><li>CONTAINS</li></ul><p>We could specify those in this way:</p><pre>from langchain_experimental.graph_transformers import LLMGraphTransformer<br><br>llm_transformer_filtered = LLMGraphTransformer(<br>    llm=llm,<br>    allowed_nodes=[&quot;Recipe&quot;, &quot;Foodproduct&quot;],<br>    allowed_relationships=[&quot;CONTAINS&quot;],<br>)</pre><p>Now, we can pass in example text and examine the results.</p><pre>from langchain_core.documents import Document<br><br>text = &quot;&quot;&quot;<br>My favorite culinary creation is the irresistible Vegan Chocolate Cake Recipe. This delightful dessert is celebrated for its intense cocoa flavor and its incredibly soft and moist texture. It&#39;s completely vegan, dairy-free, and, thanks to the use of a special gluten-free flour blend, also gluten-free.<br>To make this cake, the recipe contains the following food products with their respective quantities: 250 grams of gluten-free flour blend, 80 grams of high-quality cocoa powder, 200 grams of granulated sugar, and 10 grams of baking powder. To enrich the taste and ensure a perfect rise, the recipe also contains 5 grams of vanilla extract. Among the liquid ingredients, 240 ml of almond milk and 60 ml of vegetable oil are needed.<br>This recipe produces a single chocolate cake, considered a FoodProduct of type dessert.<br>&quot;&quot;&quot;<br>documents = [Document(page_content=text)]<br>graph_documents_filtered = await llm_transformer_filtered.aconvert_to_graph_documents(<br>    documents<br>)<br>print(f&quot;Nodes:{graph_documents_filtered[0].nodes}&quot;)<br>print(f&quot;Relationships:{graph_documents_filtered[0].relationships}&quot;)</pre><p>And we obtain:</p><pre>Nodes:[Node(id=&#39;Vegan Chocolate Cake Recipe&#39;, type=&#39;Recipe&#39;, properties={}), Node(id=&#39;Gluten-Free Flour Blend&#39;, type=&#39;Foodproduct&#39;, properties={}), Node(id=&#39;High-Quality Cocoa Powder&#39;, type=&#39;Foodproduct&#39;, properties={}), Node(id=&#39;Granulated Sugar&#39;, type=&#39;Foodproduct&#39;, properties={}), Node(id=&#39;Baking Powder&#39;, type=&#39;Foodproduct&#39;, properties={}), Node(id=&#39;Vanilla Extract&#39;, type=&#39;Foodproduct&#39;, properties={}), Node(id=&#39;Almond Milk&#39;, type=&#39;Foodproduct&#39;, properties={}), Node(id=&#39;Vegetable Oil&#39;, type=&#39;Foodproduct&#39;, properties={}), Node(id=&#39;Chocolate Cake&#39;, type=&#39;Foodproduct&#39;, properties={})]<br>Relationships:[Relationship(source=Node(id=&#39;Vegan Chocolate Cake Recipe&#39;, type=&#39;Recipe&#39;, properties={}), target=Node(id=&#39;Gluten-Free Flour Blend&#39;, type=&#39;Foodproduct&#39;, properties={}), type=&#39;CONTAINS&#39;, properties={}), Relationship(source=Node(id=&#39;Vegan Chocolate Cake Recipe&#39;, type=&#39;Recipe&#39;, properties={}), target=Node(id=&#39;High-Quality Cocoa Powder&#39;, type=&#39;Foodproduct&#39;, properties={}), type=&#39;CONTAINS&#39;, properties={}), Relationship(source=Node(id=&#39;Vegan Chocolate Cake Recipe&#39;, type=&#39;Recipe&#39;, properties={}), target=Node(id=&#39;Granulated Sugar&#39;, type=&#39;Foodproduct&#39;, properties={}), type=&#39;CONTAINS&#39;, properties={}), Relationship(source=Node(id=&#39;Vegan Chocolate Cake Recipe&#39;, type=&#39;Recipe&#39;, properties={}), target=Node(id=&#39;Baking Powder&#39;, type=&#39;Foodproduct&#39;, properties={}), type=&#39;CONTAINS&#39;, properties={}), Relationship(source=Node(id=&#39;Vegan Chocolate Cake Recipe&#39;, type=&#39;Recipe&#39;, properties={}), target=Node(id=&#39;Vanilla Extract&#39;, type=&#39;Foodproduct&#39;, properties={}), type=&#39;CONTAINS&#39;, properties={}), Relationship(source=Node(id=&#39;Vegan Chocolate Cake Recipe&#39;, type=&#39;Recipe&#39;, properties={}), target=Node(id=&#39;Almond Milk&#39;, type=&#39;Foodproduct&#39;, properties={}), type=&#39;CONTAINS&#39;, properties={}), Relationship(source=Node(id=&#39;Vegan Chocolate Cake Recipe&#39;, type=&#39;Recipe&#39;, properties={}), target=Node(id=&#39;Vegetable Oil&#39;, type=&#39;Foodproduct&#39;, properties={}), type=&#39;CONTAINS&#39;, properties={}), Relationship(source=Node(id=&#39;Vegan Chocolate Cake Recipe&#39;, type=&#39;Recipe&#39;, properties={}), target=Node(id=&#39;Chocolate Cake&#39;, type=&#39;Foodproduct&#39;, properties={}), type=&#39;CONTAINS&#39;, properties={})]</pre><p>Finally, the generated graph documents can be stored in the Neo4J graph database, initializing it via Neo4jGraphusing the add_graph_documents method.</p><pre>import os<br>from langchain_neo4j import Neo4jGraph<br><br>os.environ[&quot;NEO4J_URI&quot;] = &quot;bolt://localhost:7687&quot;<br>os.environ[&quot;NEO4J_USERNAME&quot;] = &quot;neo4j&quot;<br>os.environ[&quot;NEO4J_PASSWORD&quot;] = &quot;password&quot;<br>graph = Neo4jGraph(refresh_schema=False)<br>graph.add_graph_documents(graph_documents_filtered)</pre><p>Finally, we can query the graph directly from the Neo4J console to see its content:</p><pre>MATCH p=(r:Recipe)-[:CONTAINS]-&gt;(fp:Foodproduct) RETURN p LIMIT 25;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TkrDPu1jPnYpG9pl5Fb84w.png" /><figcaption>Image by <a href="https://medium.com/@lorenzofavaro">author</a>: Neo4J query response</figcaption></figure><p><strong>Adding node embeddings<br></strong>To better understand and disambiguate user input, we can enhance our graph search with semantic search when needed. The following is just an example of how to do it, using OpenAI embeddings.</p><p>For example, if a user asks:</p><blockquote>“Give me all the ingredients of a chocolate cake recipe that is vegan”</blockquote><p>We need to identify the recipe node in the graph that is semantically closest to the query. To do this, we store an <strong>embedding</strong> for each Recipe node, computed from its ID.</p><p>Here’s how to generate and store an embedding in Neo4j:</p><pre>import openai<br>from neo4j import GraphDatabase<br><br>driver = GraphDatabase.driver(&quot;bolt://localhost:7687&quot;, auth=(&quot;neo4j&quot;, &quot;password&quot;))<br>recipe_id = &quot;Vegan Chocolate Cake Recipe&quot;<br>recipe_embedding = openai.embeddings.create(model=&quot;text-embedding-3-small&quot;, input=recipe_id).data[0].embedding<br>with driver.session() as session:<br>  # Create the embedding field<br>  session.run(<br>      &quot;MATCH (r:Recipe {id: $recipe_id}) SET r.embedding = $embedding&quot;,<br>      recipe_id=recipe_id,<br>      embedding=recipe_embedding<br>  )<br>  # Create the vector index<br>  session.run(<br>      &quot;CREATE VECTOR INDEX recipe_index IF NOT EXISTS FOR (r:Recipe) ON (r.embedding) OPTIONS {indexConfig: {`vector.dimensions`: 1536, `vector.similarity_function`: &#39;cosine&#39;}}&quot;<br>  )</pre><p>So that, later, we are able to perform semantic search:</p><pre>query = &quot;a chocolate cake recipe that is vegan&quot;<br>query_embedding = openai.embeddings.create(<br>    model=&quot;text-embedding-3-small&quot;,<br>    input=query<br>).data[0].embedding<br><br>with driver.session() as session:<br>    result = session.run(<br>        &quot;&quot;&quot;<br>        CALL db.index.vector.queryNodes(&#39;recipe_index&#39;, 1, $embedding)<br>        YIELD node, score<br>        RETURN node.id AS name, score<br>        ORDER BY score DESC<br>        &quot;&quot;&quot;,<br>        embedding=query_embedding<br>    )<br>    for record in result:<br>        print(record[&quot;name&quot;], &quot;=&gt;&quot;, record[&quot;score&quot;])</pre><pre>Vegan Chocolate Cake Recipe =&gt; 0.9284169673919678</pre><p>This was just a brief overview, to explore more about this technique check the Langchain documentation <a href="https://python.langchain.com/docs/how_to/graph_constructing/">here</a>, or explore other tools like the official <a href="https://neo4j.com/labs/genai-ecosystem/llm-graph-builder/">Neo4j LLM Knowledge Graph Builder</a>.</p><p>As I said, I created the graph iteratively introducing sample data.</p><h3>Designing the workflow</h3><p>The implemented system includes two graphs:</p><ul><li>A <strong>researcher subgraph</strong>, responsible for generating multiple Cypher queries that are used to retrieve the relevant nodes and relationships from the Neo4j knowledge graph.</li><li>A <strong>main graph</strong>, which contains the primary workflow, including analyzing the user’s query, generating the necessary steps to accomplish the task, and producing the final response.</li></ul><h4>Main Graph structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*SSnTvEjC5fMb-1gY8W_pnQ.png" /><figcaption>Image by <a href="https://medium.com/@lorenzofavaro">author</a>: LangGraph graph preview</figcaption></figure><p>One of the central concepts of <strong>LangGraph</strong> is <strong>state</strong>. Each graph execution creates a state that is passed between nodes in the graph as they execute, and each node updates this internal state with its return value after it executes.</p><p>Let’s start the project with building the graph states. To achieve this, we define the two classes:</p><ul><li><strong>Router:</strong> Contains the result of classifying the user’s query into one of the classes: “more-info,” “valid,” or “general.”</li></ul><pre>from typing import Literal<br>from pydantic import BaseModel<br><br>class Router(BaseModel):<br>    &quot;&quot;&quot;Classify user query.&quot;&quot;&quot;<br>    logic: str<br>    type: Literal[&quot;more-info&quot;, &quot;valid&quot;, &quot;general&quot;]</pre><p>The defined graph states are:</p><ul><li><strong>InputState:</strong> Includes the list of messages exchanged between the user and the agent.</li><li><strong>AgentState:</strong> Contains the Router’s classification of the user’s query, the list of steps to execute in the Research Plan, the list of retrieved graph knowledge that the agent can reference.</li></ul><pre>from dataclasses import dataclass<br>from typing import Annotated<br>from langchain_core.messages import AnyMessage<br>from langgraph.graph import add_messages<br><br>@dataclass(kw_only=True)<br>class InputState:<br>    &quot;&quot;&quot;<br>    Represents the input state containing a list of messages.<br>    Attributes:<br>        messages (list[AnyMessage]): The list of messages associated with the state, <br>            processed using the add_messages function.<br>    &quot;&quot;&quot;<br>    messages: Annotated[list[AnyMessage], add_messages]</pre><pre>from dataclasses import dataclass, field<br>from typing import Annotated<br>from utils.utils import update_knowledge<br>from core.state_graph.states.main_graph.input_state import InputState<br>from core.state_graph.states.main_graph.router import Router<br>from core.state_graph.states.step import Step<br><br>@dataclass(kw_only=True)<br>class AgentState(InputState):<br>    &quot;&quot;&quot;<br>    Represents the state of an agent within the main state graph.<br>    Attributes:<br>        router (Router): The routing logic for the agent.<br>        steps (list[Step]): The sequence of steps taken by the agent.<br>        knowledge (list[dict]): The agent&#39;s accumulated knowledge, updated via the update_knowledge function.<br>    &quot;&quot;&quot;<br>    router: Router = field(default_factory=lambda: Router(type=&quot;general&quot;, logic=&quot;&quot;))<br>    steps: list[Step] = field(default_factory=list)<br>    knowledge: Annotated[list[dict], update_knowledge] = field(default_factory=list)</pre><h4>Step 1: Analyze and route query</h4><p>The function analyze_and_route_query returns and updates the router variable of the state AgentState. The function route_query determines the next step based on the previous query classification</p><p>Specifically, this step updates the state with a Router object whose type variable contains one of the following values: &quot;more-info&quot;, &quot;valid&quot;, or &quot;general&quot;. Based on this information, the workflow will be routed to the appropriate node (one of &quot;create_research_plan&quot;, &quot;ask_for_more_info&quot;, or &quot;respond_to_general_query&quot;).</p><pre>async def analyze_and_route_query(state: AgentState, *, config: RunnableConfig) -&gt; dict[str, Router]:<br>    &quot;&quot;&quot;<br>    Analyzes the current agent state and determines the routing logic for the next step.<br>    Args:<br>        state (AgentState): The current state of the agent, including messages and context.<br>        config (RunnableConfig): Configuration for the runnable execution.<br>    Returns:<br>        dict[str, Router]: A dictionary containing the updated router object.<br>    &quot;&quot;&quot;<br>    model = init_chat_model(<br>        name=&quot;analyze_and_route_query&quot;, **app_config[&quot;inference_model_params&quot;]<br>    )<br>    messages = [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: ROUTER_SYSTEM_PROMPT}] + state.messages<br>    print(&quot;---ANALYZE AND ROUTE QUERY---&quot;)<br>    print(f&quot;MESSAGES: {state.messages}&quot;)<br>    response = cast(<br>        Router, await model.with_structured_output(Router).ainvoke(messages)<br>    )<br>    return {&quot;router&quot;: response}<br><br>def route_query(state: AgentState) -&gt; Literal[&quot;create_research_plan&quot;, &quot;ask_for_more_info&quot;, &quot;respond_to_general_query&quot;]:<br>    &quot;&quot;&quot;<br>    Determines the next action for the agent based on the router type in the current state.<br>    Args:<br>        state (AgentState): The current state of the agent, including the router type.<br>    Returns:<br>        Literal[&quot;create_research_plan&quot;, &quot;ask_for_more_info&quot;, &quot;respond_to_general_query&quot;]:<br>            The next node/action to execute in the state graph.<br>    Raises:<br>        ValueError: If the router type is unknown.<br>    &quot;&quot;&quot;<br>    _type = state.router.type<br>    if _type == &quot;valid&quot;:<br>        return &quot;create_research_plan&quot;<br>    elif _type == &quot;more-info&quot;:<br>        return &quot;ask_for_more_info&quot;<br>    elif _type == &quot;general&quot;:<br>        return &quot;respond_to_general_query&quot;<br>    else:<br>        raise ValueError(f&quot;Unknown router type {_type}&quot;)</pre><p>Output example to the question:</p><blockquote>“Suggest me some sweet recipe!”</blockquote><pre>{<br>  &quot;logic&quot;:&quot;While the flavor profile &#39;Sweet&#39; is provided, other mandatory constraints (dietary requirements, meal timing, recipe complexity, meal course, cooking time, and caloric content) are missing. Therefore, more information is needed before suggesting recipes.&quot;,<br>  &quot;type&quot;:&quot;more-info&quot;<br>}</pre><p>The request is classified as more-info because it doesn’t contain all the mandatory constraints that we have inserted in the prompt.</p><h4>Step 1.1 Out of scope / More informations needed</h4><p>We then define the functions ask_for_more_info and respond_to_general_query, which directly generate a response for the user by making a call to the LLM: the first will be executed if the router determines that more information is needed from the user, while the second generates a response to a general query not related to our topic. In this case, it is necessary to concatenate the generated response to the list of messages, updating the messages variable in the state.</p><pre>async def ask_for_more_info(state: AgentState, *, config: RunnableConfig) -&gt; dict[str, list[BaseMessage]]:<br>    &quot;&quot;&quot;<br>    Asks the user for more information based on the current routing logic.<br>    Args:<br>        state (AgentState): The current state of the agent, including routing logic and messages.<br>        config (RunnableConfig): Configuration for the runnable execution.<br>    Returns:<br>        dict[str, list[BaseMessage]]: A dictionary containing the new message(s) requesting more information.<br>    &quot;&quot;&quot;<br>    model = init_chat_model(<br>        name=&quot;ask_for_more_info&quot;, **app_config[&quot;inference_model_params&quot;]<br>    )<br>    system_prompt = MORE_INFO_SYSTEM_PROMPT.format(logic=state.router.logic)<br>    messages = [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: system_prompt}] + state.messages<br>    response = await model.ainvoke(messages)<br>    return {&quot;messages&quot;: [response]}<br><br>async def respond_to_general_query(state: AgentState, *, config: RunnableConfig) -&gt; dict[str, list[BaseMessage]]:<br>    &quot;&quot;&quot;<br>    Generates a response to a general user query based on the agent&#39;s current state and routing logic.<br>    Args:<br>        state (AgentState): The current state of the agent, including routing logic and messages.<br>        config (RunnableConfig): Configuration for the runnable execution.<br>    Returns:<br>        dict[str, list[BaseMessage]]: A dictionary containing the generated response message(s).<br>    &quot;&quot;&quot;<br>    model = init_chat_model(<br>        name=&quot;respond_to_general_query&quot;, **app_config[&quot;inference_model_params&quot;]<br>    )<br>    system_prompt = GENERAL_SYSTEM_PROMPT.format(logic=state.router.logic)<br>    print(&quot;---RESPONSE GENERATION---&quot;)<br>    messages = [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: system_prompt}] + state.messages<br>    response = await model.ainvoke(messages)<br>    return {&quot;messages&quot;: [response]}</pre><p>Output example to the question:</p><blockquote>“What’s the weather like in Munich?”</blockquote><pre>{<br>  &quot;logic&quot;:&quot;The request is about the current weather in Munich, which is not related to the Recipe, Shopping List, or Location Use Cases. It is therefore classified as a general question.&quot;,<br>  &quot;type&quot;:&quot;general&quot;<br>}</pre><pre># ---RESPONSE GENERATION---<br>&quot;I understand you’d like to know the weather in Munich, but I can only help with recipes, shopping lists for recipes, and the location of products in supermarkets.&quot;</pre><h4>Step 2: Create a research plan</h4><p>If the query classification returns the value &quot;valid&quot;, the user&#39;s request is in scope with the document, and the workflow will reach the create_research_plan node, whose function creates a step-by-step research plan for answering a food-related query.</p><ul><li>review_research_plan checks and improves a research plan for quality and relevance.</li><li>reduce_research_plan simplifies or condenses the plan’s steps to make it more efficient.</li><li>create_research_plan orchestrates the process: it generates a plan, reduces it, reviews it, and returns the final steps.</li></ul><pre>async def review_research_plan(plan: Plan) -&gt; Plan:<br>    &quot;&quot;&quot;<br>    Reviews a research plan to ensure its quality and relevance.Args:<br>        plan (Plan): The research plan to be reviewed.<br>    Returns:<br>        Plan: The reviewed and potentially modified research plan.<br>    &quot;&quot;&quot;<br>    formatted_plan = &quot;&quot;<br>    for i, step in enumerate(plan[&quot;steps&quot;]):<br>        formatted_plan += f&quot;{i+1}. ({step[&#39;type&#39;]}): {step[&#39;question&#39;]}\n&quot;<br>    model = init_chat_model(<br>        name=&quot;create_research_plan&quot;, **app_config[&quot;inference_model_params&quot;]<br>    )<br>    system_prompt = REVIEW_RESEARCH_PLAN_SYSTEM_PROMPT.format(<br>        schema=neo4j_graph.get_structured_schema, plan=formatted_plan<br>    )<br>    reviewed_plan = cast(<br>        Plan, await model.with_structured_output(Plan).ainvoke(system_prompt)<br>    )<br>    return reviewed_plan<br><br>async def reduce_research_plan(plan: Plan) -&gt; Plan:<br>    &quot;&quot;&quot;<br>    Reduces a research plan by simplifying or condensing its steps.<br>    Args:<br>        plan (Plan): The research plan to be reduced.<br>    Returns:<br>        Plan: The reduced research plan.<br>    &quot;&quot;&quot;<br>    formatted_plan = &quot;&quot;<br>    for i, step in enumerate(plan[&quot;steps&quot;]):<br>        formatted_plan += f&quot;{i+1}. ({step[&#39;type&#39;]}): {step[&#39;question&#39;]}\n&quot;<br>    model = init_chat_model(<br>        name=&quot;reduce_research_plan&quot;, **app_config[&quot;inference_model_params&quot;]<br>    )<br>    system_prompt = REDUCE_RESEARCH_PLAN_SYSTEM_PROMPT.format(<br>        schema=neo4j_graph.get_structured_schema, plan=formatted_plan<br>    )<br>    reduced_plan = cast(<br>        Plan, await model.with_structured_output(Plan).ainvoke(system_prompt)<br>    )<br>    return reduced_plan<br><br>async def create_research_plan(<br>    state: AgentState, *, config: RunnableConfig<br>) -&gt; dict[str, list[str] | str]:<br>    &quot;&quot;&quot;<br>    Creates, reduces, and reviews a research plan based on the agent&#39;s current knowledge and messages.<br>    Args:<br>        state (AgentState): The current state of the agent, including knowledge and messages.<br>        config (RunnableConfig): Configuration for the runnable execution.<br>    Returns:<br>        dict[str, list[str] | str]: A dictionary containing the final steps of the reviewed plan and an empty knowledge list.<br>    &quot;&quot;&quot;<br>    formatted_knowledge = &quot;\n&quot;.join([item[&quot;content&quot;] for item in state.knowledge])<br>    model = init_chat_model(<br>        name=&quot;create_research_plan&quot;, **app_config[&quot;inference_model_params&quot;]<br>    )<br>    system_prompt = RESEARCH_PLAN_SYSTEM_PROMPT.format(<br>        schema=neo4j_graph.get_structured_schema, context=formatted_knowledge<br>    )<br>    messages = [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: system_prompt}] + state.messages<br>    print(&quot;---PLAN GENERATION---&quot;)<br>    # Generate plan<br>    plan = cast(Plan, await model.with_structured_output(Plan).ainvoke(messages))<br>    print(&quot;Plan&quot;)<br>    for i, step in enumerate(plan[&quot;steps&quot;]):<br>        print(f&quot;{i+1}. ({step[&#39;type&#39;]}): {step[&#39;question&#39;]}&quot;)<br>    # Reduce plan<br>    reduced_plan = cast(Plan, await reduce_research_plan(plan=plan))<br>    print(&quot;Reduced Plan&quot;)<br>    for i, step in enumerate(reduced_plan[&quot;steps&quot;]):<br>        print(f&quot;{i+1}. ({step[&#39;type&#39;]}): {step[&#39;question&#39;]}&quot;)<br>    # Review plan<br>    reviewed_plan = cast(Plan, await review_research_plan(plan=reduced_plan))<br>    print(&quot;Reviewed Plan&quot;)<br>    for i, step in enumerate(reviewed_plan[&quot;steps&quot;]):<br>        print(f&quot;{i+1}. ({step[&#39;type&#39;]}): {step[&#39;question&#39;]}&quot;)<br>    return {&quot;steps&quot;: reviewed_plan[&quot;steps&quot;], &quot;knowledge&quot;: []}<br></pre><p>Output example to the question:</p><blockquote>“Suggest me some recipes. I’m vegetarian and I don’t know what to cook for breakfast. It should be less than 1000 calories though. I don’t have any other preferences.”</blockquote><pre>{<br>  &quot;steps&quot;:<br>    [<br>      {&quot;type&quot;: &quot;semantic_search&quot;, &quot;question&quot;: &quot;Find recipes that fit a vegetarian diet by searching for &#39;Vegetarian&#39; in the Diet node&#39;s name property.&quot;},<br>      {&quot;type&quot;: &quot;semantic_search&quot;, &quot;question&quot;: &quot;Find recipes that are suitable for breakfast by searching for &#39;Breakfast&#39; in the MealMoment node&#39;s name property.&quot;},<br>      {&quot;type&quot;: &quot;query_search&quot;, &quot;question&quot;: &quot;Retrieve recipes that are both vegetarian and served during breakfast by finding the intersection of results from steps 1 and 2. Filter these recipes to ensure they contain ingredients with a total calorie count of less than 1000. Use the CONTAINS relationship to sum the calories from the FoodProduct nodes. Limit 50.&quot;}<br>    ]<br>}</pre><p>In this case, the user’s request requires three steps to retrieve the information.</p><h4>Step 3: Conduct research</h4><p>This function takes the first step from the research plan and uses it to conduct research. For the research, the function calls the <strong>subgraph</strong> researcher_graph, which returns all the new knowledge gathered that we will explore in the next section. Finally, we update the steps variable in the state by removing the step that was just executed.</p><pre>async def conduct_research(state: AgentState) -&gt; dict[str, Any]:<br>    &quot;&quot;&quot;<br>    Executes a research step using the research graph and updates the agent&#39;s knowledge.Args:<br>        state (AgentState): The current state of the agent, including steps and knowledge.<br>    Returns:<br>        dict[str, Any]: A dictionary containing the updated knowledge and remaining steps.<br>    &quot;&quot;&quot;<br>    response = await research_graph.ainvoke(<br>        {&quot;step&quot;: state.steps[0], &quot;knowledge&quot;: state.knowledge}<br>    )<br>    knowledge = response[&quot;knowledge&quot;]<br>    step = state.steps[0]<br>    print(<br>        f&quot;\n{len(knowledge)} pieces of knowledge retrieved in total for the step: {step}.&quot;<br>    )<br>    return {&quot;knowledge&quot;: knowledge, &quot;steps&quot;: state.steps[1:]}<br></pre><h4>Step 4: Research subgraph building</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*OSRSJST0STbTN57hWwb6xQ.png" /><figcaption>Image by <a href="https://medium.com/@lorenzofavaro">author</a>: Research Graph diagram</figcaption></figure><p>As visible in the image above, the graph consists of:</p><ul><li>a query generation and an execution step, or</li><li>a semantic search step</li></ul><p>As we did for the main graph, let’s proceed with defining the states QueryState (private state for the execute_query node in the researcher graph) and ResearcherState (state of the researcher graph).</p><pre>@dataclass(kw_only=True)<br>class QueryState:<br>    &quot;&quot;&quot;State class for managing research queries in the research graph.&quot;&quot;&quot;<br>    query: str<br><br>class Step(TypedDict):<br>    &quot;&quot;&quot;Single research step&quot;&quot;&quot;<br>    question: str<br>    type: Literal[&quot;semantic_search&quot;, &quot;query_search&quot;]<br><br>@dataclass(kw_only=True)<br>class ResearcherState:<br>    &quot;&quot;&quot;State of the researcher graph.&quot;&quot;&quot;<br>    step: Step<br>    queries: list[str] = field(default_factory=list)<br>    knowledge: Annotated[list[dict], update_knowledge] = field(default_factory=list)</pre><h4>Step 4.1 Semantic search</h4><p>This step performs vector-based semantic searches on the Neo4j graph database to find relevant nodes based on similarity rather than exact matches.</p><p>It is composed by two functions:</p><ul><li>semantic_search determines search parameters using an LLM and orchestrates the semantic search execution.</li><li>execute_semantic_search performs the actual vector similarity search using OpenAI embeddings and Neo4j’s vector index.</li></ul><pre>def execute_semantic_search(node_label: str, attribute_name: str, query: str):<br>    &quot;&quot;&quot;Execute a semantic search on Neo4j vector indexes.<br>    <br>    This function performs vector-based similarity search using OpenAI embeddings<br>    to find nodes in the Neo4j graph database that are semantically similar to<br>    the provided query. It converts the query to an embedding vector and searches<br>    the corresponding vector index for the most similar nodes.<br>    <br>    Args:<br>        node_label (str): The label of the node type to search (e.g., &#39;Recipe&#39;, &#39;FoodProduct&#39;).<br>        attribute_name (str): The attribute/property of the node to search within (e.g., &#39;name&#39;, &#39;description&#39;).<br>        query (str): The search query to find semantically similar content.<br>        <br>    Returns:<br>        list: A list of dictionaries containing the matching nodes with their attributes,<br>              ordered by similarity score (highest first).<br>    &quot;&quot;&quot;<br>    index_name = f&quot;{node_label.lower()}_{attribute_name}_index&quot;<br>    top_k = 1<br>    query_embedding = (<br>        openai.embeddings.create(model=app_config[&quot;embedding_model&quot;], input=query)<br>        .data[0]<br>        .embedding<br>    )<br>    nodes = (<br>        f&quot;node.name as name, node.{attribute_name} as {attribute_name}&quot;<br>        if attribute_name != &quot;name&quot;<br>        else f&quot;node.{attribute_name} as name&quot;<br>    )<br>    response = neo4j_graph.query(<br>        f&quot;&quot;&quot;<br>        CALL db.index.vector.queryNodes(&#39;{index_name}&#39;, {top_k}, {query_embedding})<br>        YIELD node, score<br>        RETURN {nodes}<br>        ORDER BY score DESC&quot;&quot;&quot;<br>    )<br>    print(<br>        f&quot;Semantic Search Tool invoked with parameters: node_label: &#39;{node_label}&#39;, attribute_name: &#39;{attribute_name}&#39;, query: &#39;{query}&#39;&quot;<br>    )<br>    print(f&quot;Semantic Search response: {response}&quot;)<br>    return response<br><br>async def semantic_search(state: ResearcherState, *, config: RunnableConfig):<br>    &quot;&quot;&quot;Perform semantic search to find relevant nodes in the research graph.<br>    <br>    This function analyzes a research question to determine optimal search parameters<br>    and executes a semantic search on the Neo4j graph database. It uses an LLM to<br>    identify which node type and attribute should be searched, then performs vector-based<br>    similarity search to find semantically related content that can help answer the question.<br>    <br>    Args:<br>        state (ResearcherState): The current researcher state containing the<br>            research step question and accumulated knowledge.<br>        config (RunnableConfig): Configuration for the runnable execution.<br>        <br>    Returns:<br>        dict[str, list]: A dictionary with a &quot;knowledge&quot; key containing<br>            a list with the semantic search results formatted as knowledge items.<br>    &quot;&quot;&quot;<br>    class Response(TypedDict):<br>        node_label: str<br>        attribute_name: str<br>        query: str<br>    model = init_chat_model(<br>        name=&quot;semantic_search&quot;, **app_config[&quot;inference_model_params&quot;]<br>    )<br>    vector_indexes = neo4j_graph.query(&quot;SHOW VECTOR INDEXES YIELD name RETURN name;&quot;)<br>    print(f&quot;vector_indexes: {vector_indexes}&quot;)<br>    system_prompt = SEMANTIC_SEARCH_SYSTEM_PROMPT.format(<br>        schema=neo4j_graph.get_structured_schema,<br>        vector_indexes=str(vector_indexes)<br>    )<br>    messages = [<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: system_prompt},<br>        {&quot;role&quot;: &quot;human&quot;, &quot;content&quot;: state.step[&quot;question&quot;]},<br>    ]<br>    response = cast(<br>        Response, await model.with_structured_output(Response).ainvoke(messages)<br>    )<br>    sem_search_response = execute_semantic_search(<br>        node_label=response[&quot;node_label&quot;],<br>        attribute_name=response[&quot;attribute_name&quot;],<br>        query=response[&quot;query&quot;],<br>    )<br>    search_names = [f&quot;&#39;{record[&#39;name&#39;]}&#39;&quot; for record in sem_search_response]<br>    joined_search_names = &quot;, &quot;.join(search_names)<br>    knowledge = {<br>        &quot;id&quot;: new_uuid(),<br>        &quot;content&quot;: f&quot;Executed Semantic Search on {response[&#39;node_label&#39;]}.{response[&#39;attribute_name&#39;]} for values similar to: &#39;{response[&#39;query&#39;]}&#39;\nResults: {joined_search_names}&quot;,<br>    }<br>    return {&quot;knowledge&quot;: [knowledge]}</pre><p>Output example to the produced steps:</p><pre>[<br>  {&quot;type&quot;: &quot;semantic_search&quot;, &quot;question&quot;: &quot;Find recipes that fit a vegetarian diet by searching for &#39;Vegetarian&#39; in the Diet node&#39;s name property.&quot;},<br>  {&quot;type&quot;: &quot;semantic_search&quot;, &quot;question&quot;: &quot;Find recipes that are suitable for breakfast by searching for &#39;Breakfast&#39; in the MealMoment node&#39;s name property.&quot;}<br>]</pre><pre># -- NEW KNOWLEDGE --<br>Semantic Search Tool invoked with parameters: node_label: &#39;Diet&#39;, attribute_name: &#39;name&#39;, query: &#39;Vegetarian&#39;<br>Semantic Search response: [{&#39;name&#39;: &#39;Vegetarian&#39;}]<br>Semantic Search Tool invoked with parameters: node_label: &#39;MealMoment&#39;, attribute_name: &#39;name&#39;, query: &#39;Breakfast&#39;<br>Semantic Search response: [{&#39;name&#39;: &#39;Breakfast&#39;}]</pre><h4>Step 4.2 Generate queries</h4><p>This step generate search queries based on the question (a step in the research plan). This function uses a LLM to generate diverse Cypher queries to help answer the question. It is composed by three functions:</p><ul><li>generate_queries main function that generates initial queries and applies both correction methods.</li><li>correct_query_by_llm corrects Cypher queries using a language model with schema awareness.</li><li>correct_query_by_parser applies structural corrections using a parser-based query corrector.</li></ul><pre>async def correct_query_by_llm(query: str) -&gt; str:<br>    &quot;&quot;&quot;Correct a Cypher query using a language model.<br>    <br>    This function uses an LLM to review and correct a Cypher query based on<br>    the Neo4j graph schema. It provides schema-aware correction to ensure<br>    the query is properly formatted and uses valid relationships and nodes.<br>    <br>    Args:<br>        query (str): The Cypher query to be corrected.<br>        <br>    Returns:<br>        str: The corrected Cypher query.<br>    &quot;&quot;&quot;<br>    model = init_chat_model(<br>        name=&quot;correct_query_by_llm&quot;, **app_config[&quot;inference_model_params&quot;]<br>    )<br>    system_prompt = FIX_QUERY_SYSTEM_PROMPT.format(<br>        schema=neo4j_graph.get_structured_schema<br>    )<br>    messages = [<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: system_prompt},<br>        {&quot;role&quot;: &quot;human&quot;, &quot;content&quot;: query},<br>    ]<br>    response = await model.ainvoke(messages)<br>    return response.content<br><br>def correct_query_by_parser(query: str) -&gt; str:<br>    &quot;&quot;&quot;Correct a Cypher query using a parser-based corrector.<br>    <br>    This function uses the CypherQueryCorrector to parse and correct<br>    Cypher queries based on the graph schema. It extracts the Cypher<br>    query from the text and applies structural corrections.<br>    <br>    Args:<br>        query (str): The text containing the Cypher query to be corrected.<br>        <br>    Returns:<br>        str: The corrected Cypher query.<br>    &quot;&quot;&quot;<br>    corrector_schema = [<br>        Schema(el[&quot;start&quot;], el[&quot;type&quot;], el[&quot;end&quot;])<br>        for el in neo4j_graph.get_structured_schema.get(&quot;relationships&quot;, [])<br>    ]<br>    cypher_query_corrector = CypherQueryCorrector(corrector_schema)<br>    extracted_query = extract_cypher(text=query)<br>    corrected_query = cypher_query_corrector(extracted_query)<br>    return corrected_query<br><br>async def generate_queries(<br>    state: ResearcherState, *, config: RunnableConfig<br>) -&gt; dict[str, list[str]]:<br>    &quot;&quot;&quot;Generate and correct Cypher queries for a research step.<br>    <br>    This function generates multiple Cypher queries based on a research question<br>    and existing knowledge context. It uses an LLM to generate initial queries,<br>    then applies both LLM-based and parser-based corrections to ensure the<br>    queries are valid and properly formatted for the Neo4j graph database.<br>    <br>    Args:<br>        state (ResearcherState): The current researcher state containing the<br>            research step question and accumulated knowledge.<br>        config (RunnableConfig): Configuration for the runnable execution.<br>        <br>    Returns:<br>        dict[str, list[str]]: A dictionary with a &quot;queries&quot; key containing<br>            a list of corrected Cypher queries.<br>    &quot;&quot;&quot;<br>    <br>    class Response(TypedDict):<br>        queries: list[str]<br>    print(&quot;---GENERATE QUERIES---&quot;)<br>    formatted_knowledge = &quot;\n\n&quot;.join(<br>        [f&quot;{i+1}. {item[&#39;content&#39;]}&quot; for i, item in enumerate(state.knowledge)]<br>    )<br>    model = init_chat_model(<br>        name=&quot;generate_queries&quot;, **app_config[&quot;inference_model_params&quot;]<br>    )<br>    system_prompt = GENERATE_QUERIES_SYSTEM_PROMPT.format(<br>        schema=neo4j_graph.get_schema, context=formatted_knowledge<br>    )<br>    messages = [<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: system_prompt},<br>        {&quot;role&quot;: &quot;human&quot;, &quot;content&quot;: state.step[&quot;question&quot;]},<br>    ]<br>    response = cast(<br>        Response, await model.with_structured_output(Response).ainvoke(messages)<br>    )<br>    response[&quot;queries&quot;] = [<br>        await correct_query_by_llm(query=q) for q in response[&quot;queries&quot;]<br>    ]<br>    response[&quot;queries&quot;] = [<br>        correct_query_by_parser(query=q) for q in response[&quot;queries&quot;]<br>    ]<br>    print(f&quot;Queries: {response[&#39;queries&#39;]}&quot;)<br>    return {&quot;queries&quot;: response[&quot;queries&quot;]}<br></pre><p>Output example to the question (after the semantic search queries execution):</p><blockquote>“Suggest me some recipes. I’m vegetarian and I don’t know what to cook for breakfast. It should be less than 1000 calories though. I don’t have any other preferences.”</blockquote><pre>MATCH (r:Recipe)-[:FITS_DIET]-&gt;(:Diet {name: &#39;Vegetarian&#39;}),<br>      (r)-[:SERVED_DURING]-&gt;(:MealMoment {name: &#39;Breakfast&#39;}),<br>      (r)-[c:CONTAINS]-&gt;(fp:FoodProduct)<br>WITH r, SUM(c.grams * (fp.calories / 100.0)) AS total_calories<br>WHERE total_calories &lt; 1000<br>RETURN r.name AS recipe_name, total_calories<br>LIMIT 5</pre><p>And after its execution:</p><pre># -- NEW KNOWLEDGE --<br>╒════════════════════════════╤══════════════════╕<br>│recipe_name                 │total_calories    <br>╞════════════════════════════╪══════════════════╡<br>│&quot;Mascarpone Dessert&quot;        │945.8000000000001 <br>├────────────────────────────┼──────────────────┤<br>│&quot;Buffalo Mozzarella Salad&quot;  │668.88            <br>├────────────────────────────┼──────────────────┤<br>│&quot;Raisin and Almond Snack&quot;   │374.69999999999993<br>├────────────────────────────┼──────────────────┤<br>│&quot;Mozzarella and Basil Salad&quot;│528.4             <br>└────────────────────────────┴──────────────────┘</pre><h4>Step 4.3 Building subgraph</h4><pre>def build_research_graph():<br>    builder = StateGraph(ResearcherState)<br>    builder.add_node(generate_queries)<br>    builder.add_node(execute_query)<br>    builder.add_node(semantic_search)<br>    builder.add_conditional_edges(<br>        START,<br>        route_step,<br>        {&quot;generate_queries&quot;: &quot;generate_queries&quot;, &quot;semantic_search&quot;: &quot;semantic_search&quot;},<br>    )<br>    builder.add_conditional_edges(<br>        &quot;generate_queries&quot;,<br>        query_in_parallel,  # type: ignore<br>        path_map=[&quot;execute_query&quot;],<br>    )<br>    builder.add_edge(&quot;execute_query&quot;, END)<br>    builder.add_edge(&quot;semantic_search&quot;, END)<br>    return builder.compile()<br><br>research_graph = build_research_graph()</pre><h4>Step 5: Check finished</h4><p>Using a conditional_edge, we build a loop with the end condition determined by the value returned by check_finished. This function checks that there are no more steps to process in the list of steps created by the create_research_plan node. Once all steps are completed, the flow proceeds to the respond node.</p><pre>def check_finished(state: AgentState) -&gt; Literal[&quot;respond&quot;, &quot;conduct_research&quot;]:<br>    &quot;&quot;&quot;<br>    Determines whether the agent should respond or conduct further research based on the steps taken.Args:<br>        state (AgentState): The current state of the agent, including the steps performed.<br>    Returns:<br>        Literal[&quot;respond&quot;, &quot;conduct_research&quot;]: <br>            &quot;conduct_research&quot; if there are steps present, otherwise &quot;respond&quot;.<br>    &quot;&quot;&quot;<br>    if len(state.steps or []) &gt; 0:<br>        return &quot;conduct_research&quot;<br>    else:<br>        return &quot;respond&quot;</pre><h4>Step 6: Respond</h4><p>Generates a final response to the user’s query based on the conducted research. This function formulates a comprehensive answer using the conversation history and the documents retrieved by the researcher agent.</p><pre>async def respond(<br>    state: AgentState, *, config: RunnableConfig<br>) -&gt; dict[str, list[BaseMessage]]:<br>    &quot;&quot;&quot;<br>    Generates a final response to the user based on the agent&#39;s accumulated knowledge and messages.<br>    Args:<br>        state (AgentState): The current state of the agent, including knowledge and messages.<br>        config (RunnableConfig): Configuration for the runnable execution.<br>    Returns:<br>        dict[str, list[BaseMessage]]: A dictionary containing the generated response message(s).<br>    &quot;&quot;&quot;<br>    print(&quot;--- RESPONSE GENERATION STEP ---&quot;)<br>    model = init_chat_model(name=&quot;respond&quot;, **app_config[&quot;inference_model_params&quot;])<br>    formatted_knowledge = &quot;\n\n&quot;.join([item[&quot;content&quot;] for item in state.knowledge])<br>    prompt = RESPONSE_SYSTEM_PROMPT.format(context=formatted_knowledge)<br>    messages = [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: prompt}] + state.messages<br>    response = await model.ainvoke(messages)<br>    return {&quot;messages&quot;: [response]}<br></pre><h4>Step 7: Building main graph</h4><pre>def build_main_graph():<br>    builder = StateGraph(AgentState, input=InputState)<br>    builder.add_node(analyze_and_route_query)<br>    builder.add_node(ask_for_more_info)<br>    builder.add_node(respond_to_general_query)<br>    builder.add_node(create_research_plan)<br>    builder.add_node(conduct_research)<br>    builder.add_node(&quot;respond&quot;, respond)<br>    builder.add_edge(&quot;create_research_plan&quot;, &quot;conduct_research&quot;)<br>    builder.add_edge(START, &quot;analyze_and_route_query&quot;)<br>    builder.add_conditional_edges(&quot;analyze_and_route_query&quot;, route_query)<br>    builder.add_conditional_edges(&quot;conduct_research&quot;, check_finished)<br>    builder.add_edge(&quot;respond&quot;, END)<br>    return builder.compile()</pre><h3>3. Results</h3><p>We can see its performance testing it with the following question:</p><blockquote>“Give me the shopping list for the recipe pasta alla carbonara.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N7RJoRy-UGf0ts6hMAUvJQ.png" /><figcaption>Image by <a href="https://medium.com/@lorenzofavaro">author</a>: Console Logs</figcaption></figure><p>As we can see from the console logs, the Main Graph create the following reviewed plan:</p><ol><li><strong>semantic_search</strong>: Find the Recipe node with a name similar to ‘pasta alla carbonara’ using semantic search on the ‘name’ property of the Recipe node.</li><li><strong>query_search</strong>: Retrieve the StoreProduct nodes that are connected to the identified Recipe node from Step 1 through the ‘CONTAINS’ and ‘IS_INSTANCE_OF’ relationships, and list their details such as name, brand, price, and quantity to form the shopping list. Limit 50.</li></ol><p>After executing the first step, we get to know that the exact name of the Recipe node corresponding to the ‘<em>pasta alla carbonara</em>’ is ‘<em>Classic Carbonara</em>’.</p><pre>app_service-1  | Semantic Search Tool invoked with parameters: node_label: &#39;Recipe&#39;, attribute_name: &#39;name&#39;, query: &#39;pasta alla carbonara&#39;<br>app_service-1  | Semantic Search response: [{&#39;name&#39;: &#39;Classic Carbonara&#39;}]</pre><p>Then it executes the second step, with the following Cypher query:</p><pre>MATCH (r:Recipe {name: &#39;Classic Carbonara&#39;})-[:CONTAINS]-&gt;(fp:FoodProduct)&lt;-[:IS_INSTANCE_OF]-(sp:StoreProduct)<br>RETURN sp.name, sp.brand, sp.price, sp.quantity, sp.quantity_unit<br>LIMIT 50</pre><p>And then we get the final response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*G-oLRiMktDgbYaTLAEUTTA.gif" /><figcaption>Image by <a href="https://medium.com/@lorenzofavaro">author</a>: Live demo — UI made with <a href="https://github.com/Chainlit/chainlit">Chainlit</a></figcaption></figure><p>Checking from the graph content we see that the complete result is correct.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*emxog3vgClTMUM0hTVoZaQ.png" /><figcaption>Image by <a href="https://medium.com/@lorenzofavaro">author</a>: Graph response — Store products for “Classic Carbonara”</figcaption></figure><h3>4. Conclusion</h3><h4>Graph RAG: Technical Challenges and Considerations</h4><p>Despite the improved performance, implementing Graph RAG is not without its challenges:</p><ul><li><strong>Latency</strong>: The increased complexity of agentic interactions often leads to longer response times. Striking a balance between speed and accuracy is a critical challenge.</li><li><strong>Evaluation and Observability</strong>: As Agentic RAG systems become more complex, continuous evaluation and observability become necessary.</li></ul><p>In conclusion, Graph RAG marks a major breakthrough in the realm of AI. By merging the capabilities of large language models with autonomous reasoning and information retrieval, Graph RAG introduce a new standard of intelligence and flexibility. As AI continues to evolve, Graph RAG will play an fundamental role in various industries, transforming the way we use technology.</p><p><a href="https://github.com/lorenzofavaro/meal-planner-graphrag">Github repo HERE!</a></p><blockquote>References:</blockquote><blockquote><a href="https://python.langchain.com/docs/how_to/graph_constructing/">https://python.langchain.com/docs/how_to/graph_constructing/</a></blockquote><blockquote><a href="https://infohub.delltechnologies.com/it-it/p/the-rise-of-agentic-rag-systems/">https://infohub.delltechnologies.com/it-it/p/the-rise-of-agentic-rag-systems/</a></blockquote><blockquote><a href="https://langchain-ai.github.io/langgraph/how-tos/">https://langchain-ai.github.io/langgraph/how-tos/</a></blockquote><blockquote><a href="https://neo4j.com/labs/genai-ecosystem/llm-graph-builder/">https://neo4j.com/labs/genai-ecosystem/llm-graph-builder/</a></blockquote><blockquote><a href="https://github.com/Chainlit/chainlit">https://github.com/Chainlit/chainlit</a></blockquote><h3>A message from our Founder</h3><p>Hey, <a href="https://linkedin.com/in/sunilsandhu">Sunil</a> here. I wanted to take a moment to thank you for reading until the end and for being a part of this community. Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? We don’t receive any funding, we do this to support the community.</p><p>If you want to show some love, please take a moment to follow me on <a href="https://linkedin.com/in/sunilsandhu">LinkedIn</a>, <a href="https://tiktok.com/@messyfounder">TikTok</a>, <a href="https://instagram.com/sunilsandhu">Instagram</a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/">weekly newsletter</a>. And before you go, don’t forget to clap and follow the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4d6c7f8dcd3" width="1" height="1" alt=""><hr><p><a href="https://blog.cubed.run/building-an-agentic-graphrag-system-with-langgraph-and-neo4j-f4d6c7f8dcd3">Building an Agentic GraphRAG System with LangGraph and Neo4j</a> was originally published in <a href="https://blog.cubed.run/">Cubed</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Deep Research System with Google ADK, Gemini, QDrant, and MCP]]></title>
            <link>https://aiadvances.org/building-an-deep-research-system-with-google-adk-gemini-qdrant-and-mcp-3df8df8b6335?source=rss-74ad312f5896------2</link>
            <guid isPermaLink="false">https://medium.com/p/3df8df8b6335</guid>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[multi-agent-systems]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[deep-research]]></category>
            <category><![CDATA[google-adk]]></category>
            <dc:creator><![CDATA[Lorenzo Favaro]]></dc:creator>
            <pubDate>Wed, 03 Sep 2025 22:30:39 GMT</pubDate>
            <atom:updated>2025-09-04T13:14:16.041Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Deep Research System with Google ADK, Gemini, QDrant, and MCP</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S7RDBZ54XM-cqmjpcwwDeQ.png" /><figcaption>Image from author: Deep Research system’s components</figcaption></figure><p>1. ❓ Introduction: Multi-Agent Research</p><p>2. 🧠 Project Overview</p><p>3. 🔧 System Architecture Deep Dive</p><p>4. 📊 Results</p><p>5. 🔚 Conclusion</p><p><strong>Github Repo </strong><a href="https://github.com/lorenzofavaro/deep-research"><strong>here</strong></a><strong>!</strong></p><p>In this article, I present a comprehensive <strong>multi-agent research assistant</strong> built with <a href="https://github.com/google/adk-python"><strong>Google’s Agent Development Kit</strong></a> (ADK) and powered by <strong>Gemini 2.0 Flash</strong>. This system demonstrates how modern AI architectures can orchestrate agents to conduct academic-quality research by combining <strong>ArXiv papers</strong> analysis with <strong>real-time web search</strong> capabilities.</p><p>The system handles complex research scenarios across multiple domains by coordinating <strong>four specialized agent types</strong>: <strong>classification</strong> <strong>agents</strong> for query analysis, <strong>planning</strong> <strong>agents</strong> for research strategy, <a href="https://arxiv.org/"><strong>ArXiv</strong></a><strong> agents</strong> for academic <strong>paper ingestion</strong> and <strong>RAG</strong>, and <strong>web search agents</strong> for current developments.</p><h3>1. Introduction: Multi-Agent Research</h3><p>A multi-agent system addresses has different advantages:</p><ul><li><strong>Parallel Processing</strong>: Simultaneous execution of multiple research streams ensures coverage without time penalties.</li><li><strong>Specialized Intelligence</strong>: Each agent is optimized for specific tasks (classification, planning, academic search, web search) leading to higher quality results.</li><li><strong>Source Triangulation</strong>: Academic papers provide theoretical foundations while web search captures recent developments, creating complete research coverage.</li></ul><p>This architecture makes multi-agent research systems particularly powerful for scenarios requiring both academic rigor and current market intelligence.</p><h3>2. Project Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EzmQDnJNVfAK1FglNpG4nA.png" /><figcaption>System workflow</figcaption></figure><p><strong>Multi-Agent Workflow:</strong></p><ol><li><strong>Query Classification and Routing</strong>: The system analyzes the incoming request to determine if it constitutes a valid research question, need clarification, or fall outside the research domain.</li><li><strong>Research Planning</strong>: A specialized planning agent creates a research plan, combining ArXiv searches with web searches.</li><li><strong>Research Execution</strong>: Multiple agents execute research steps (<strong>max 3</strong>) simultaneously:<br>- <strong>ArXiv Agent</strong>: Searches top 50 papers, filters to top 3 based on relevance, ingests full papers into <a href="https://qdrant.tech/">Qdrant</a> vector store, and performs RAG for information extraction<br>- <strong>Web Search Agent</strong>: Uses <a href="https://docs.tavily.com/documentation/mcp">Tavily MCP server</a> for real-time web content gathering and trend analysis</li><li><strong>Answer Synthesis</strong>: Results from the plan steps are aggregated and synthesized into a unique response.</li></ol><h3>3. System Architecture Deep Dive</h3><h4>Step 1: Query Classification with Gemini 2.0 Flash</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5dXEikZMI-nN1WudOQMZIw.png" /><figcaption>Query Classification Workflow</figcaption></figure><p>The classification agent determines request validity and routes appropriately using <strong>structured outputs</strong> to ensure <strong>predictable responses </strong>by leveraging Pydantic models:</p><pre>GEMINI_MODEL = ‘gemini-2.0-flash’<br>system_prompt = &quot;&quot;&quot;You are a Request Classification Agent that categorizes user requests into three types:<br><br>**Categories:**<br>1. **valid** - Specific, clear research requests with defined topics/domains<br>2. **need-more-info** - Too broad but shows research intent (needs refinement)<br>3. **general** - Non-research requests (e.g., &quot;2+2?&quot;, greetings, general questions) that don&#39;t involve research<br><br>**Output Format:**<br>- **valid**: Return classification + user_intent (concise description of research goal)<br>- **need-more-info**: Return classification + next_message (ask for clarification)<br>- **general**: Return classification + next_message (politely decline and explain you only help with research)<br><br>Personalize messages when possible.<br>&quot;&quot;&quot;<br><br>classify_agent = LlmAgent(<br>    name=&#39;ClassifyAgent&#39;,<br>    model=GEMINI_MODEL,<br>    instruction=system_prompt,<br>    description=&#39;Classify user requests and provide follow-up messages&#39;,<br>    input_schema=UserRequest,<br>    output_schema=ClassificationResult,<br>    output_key=&#39;classification&#39;,<br>)</pre><p><strong>Output example</strong> for:</p><blockquote>“How much is 2+2?”</blockquote><pre>{<br>  &quot;type&quot;: &quot;general&quot;,<br>  &quot;user_intent&quot;: null,<br>  &quot;next_message&quot;: &quot;I help with research topics requiring <br>                   academic analysis, not simple math&quot;<br>}</pre><h4>Step 2: Research Plan Generation</h4><p>The planning agent creates a plan of one or multiple steps (max 3):</p><pre>GEMINI_MODEL = &#39;gemini-2.0-flash&#39;<br>system_prompt = &quot;&quot;&quot;You are a Research Planning Agent that creates step-by-step research plans from the user_intent.**Available Tools:**<br>1. **ArXiv Search** - Academic papers, theoretical foundations, established research<br>2. **Web Search** - Recent developments, industry applications, current trends<br>**Process:**<br>1. Start from the provided user_intent<br>2. Break it into key research components<br>3. Create targeted search queries using appropriate tools<br>4. Sequence steps logically to build comprehensive understanding<br>**Requirements:**<br>- Maximum 3 steps<br>- Each step must directly address the user&#39;s intent<br>- Build knowledge progressively from foundations to current applications<br>&quot;&quot;&quot;<br><br>plan_agent = LlmAgent(<br>    name=&#39;PlanAgent&#39;,<br>    model=GEMINI_MODEL,<br>    instruction=system_prompt,<br>    planner=PlanReActPlanner(),<br>    description=&#39;Plan a list of steps to gather all the information needed to answer the user query&#39;,<br>    input_schema=ClassificationResult,<br>    output_schema=ResearchPlan,<br>    output_key=&#39;research_plan&#39;,<br>)</pre><p>In this module we use the <a href="https://google.github.io/adk-docs/api-reference/python/google-adk.html#google.adk.planners.PlanReActPlanner">Plan ReAct Planner</a> of Google ADK, a planner that constrains the LLM response to generate a plan before any action/observation.</p><p>Note: this planner does not require the model to support built-in thinking features.</p><p><strong>Output example</strong> for:</p><blockquote>Tell me about the latest advancements on graph theory.</blockquote><pre>{<br>  &quot;steps&quot;: [<br>    {<br>      &quot;action&quot;: &quot;arxiv_search&quot;,<br>      &quot;query&quot;: &quot;recent advances in graph theory&quot;<br>    },<br>    {<br>      &quot;action&quot;: &quot;web_search&quot;,<br>      &quot;query&quot;: &quot;latest developments graph theory&quot;<br>    },<br>    {<br>      &quot;action&quot;: &quot;web_search&quot;,<br>      &quot;query&quot;: &quot;applications of graph theory in 2025&quot;<br>    }<br>  ]<br>}</pre><h4>Step 3: Parallel Research Execution</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZiIH_ZRy8ygry0W-hppaWg.png" /><figcaption>Research Execution Workflow</figcaption></figure><p><strong>ArXiv Research Agent</strong></p><p>The ArXiv agent implements a paper analysis pipeline:</p><pre>class ArxivAgent(BaseAgent):<br>    &quot;&quot;&quot;Agent for coordinating ArXiv paper research workflow.&quot;&quot;&quot;<br><br>    def __init__(<br>        self,<br>        *,<br>        name: str,<br>        run_id: str,<br>        agent_id: str,<br>        document_service: DocumentIngestionService,<br>    ) -&gt; None:<br>        &quot;&quot;&quot;<br>        Initialize the ArXiv agent.<br><br>        Args:<br>            name: Name of the agent<br>            run_id: Unique identifier for the current run<br>            agent_id: Unique identifier for this agent instance<br>            document_service: Service for document ingestion and retrieval<br>        &quot;&quot;&quot;<br>        super().__init__(name=name)<br>        self._run_id = run_id<br>        self._agent_id = agent_id<br>        self._document_service = document_service<br>        self._find_step = FindStep(<br>            name=&#39;find_step&#39;, description=&#39;Find papers on arxiv&#39;, run_id=run_id, agent_id=agent_id,<br>        )<br>        self._ingest_step = IngestStep(<br>            name=&#39;ingest_step&#39;, description=&#39;Ingest documents&#39;, run_id=run_id, document_service=document_service,<br>        )<br>        self._rag_step = RAGStep(<br>            name=&#39;rag_step&#39;, description=&#39;Perform RAG&#39;,<br>            run_id=run_id, agent_id=agent_id, document_service=document_service,<br>        )<br><br>    async def _run_async_impl(self, context: InvocationContext) -&gt; AsyncGenerator[Event, None]:<br>        &quot;&quot;&quot;<br>        Execute the complete ArXiv research workflow.<br><br>        Args:<br>            context: Invocation context containing session state and configuration<br><br>        Yields:<br>            Events from each step of the workflow<br>        &quot;&quot;&quot;<br>        logger.debug(<br>            f&#39;Starting ArXiv research workflow for agent {self._agent_id}&#39;,<br>        )<br><br>        logger.debug(&#39;Starting ArXiv paper search step&#39;)<br>        async for event in self._find_step.run_async(context):<br>            yield event<br><br>        logger.debug(&#39;Starting paper filtering step&#39;)<br>        async for event in filter_agent.run_async(context):<br>            yield event<br><br>        logger.debug(&#39;Starting paper ingestion step&#39;)<br>        async for event in self._ingest_step.run_async(context):<br>            yield event<br><br>        logger.debug(&#39;Starting RAG step&#39;)<br>        async for event in self._rag_step.run_async(context):<br>            yield event<br><br>        logger.info(<br>            f&#39;Completed ArXiv research workflow for agent {self._agent_id}&#39;,<br>        )</pre><p><strong>Pipeline:</strong></p><p><strong>1. Find</strong> (ArXiv API): Search 50 papers on Arxiv, using the produced step’s query. Do not get the papers content yet, just their abstracts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*fkBJQU5HeYnXrRQ-EtRXrg.png" /><figcaption>HTTP requests to fetch Arxiv papers</figcaption></figure><p><strong>2. Filter</strong> (Gemini 2.0 Flash): Filter results, take the top 3 papers that are the most coherent to the step’s query. Now, we download their contents.</p><pre>GEMINI_MODEL = &#39;gemini-2.0-flash&#39;<br>PAPERS_NUM = 3<br><br>system_prompt = f&quot;&quot;&quot;You are a Research Search Agent.<br>Your role is to identify the most relevant academic papers for a given user query.<br><br>**Step 1 — Analyze candidates:**<br>- Carefully review the retrieved papers, considering both *title* and *abstract*.<br>- Assess their relevance to the user query with precision.<br><br>**Step 2 — Select results:**<br>- Choose **up to {PAPERS_NUM}** papers that best match the query.<br>- Prefer recent works (published in the last 3 years).<br>- Only include papers that provide direct, specific insights on the topic.<br>- If fewer than {PAPERS_NUM} are relevant, return only those (never add irrelevant ones).<br><br>Output rules (strict):<br>- The output must be a **valid JSON array of strings**, containing only the selected paper IDs.<br>- Do not include explanations, text outside the JSON, or formatting such as Markdown.<br>&quot;&quot;&quot;<br><br>filter_agent = LlmAgent(<br>    name=&#39;FilterAgent&#39;,<br>    model=GEMINI_MODEL,<br>    instruction=system_prompt,<br>    description=&#39;Filter papers&#39;,<br>    input_schema=PapersMetas,<br>    output_schema=PaperIDs,<br>    output_key=&#39;paper_ids&#39;,<br>)</pre><p><strong>3. Ingest</strong> (OpenAI Embeddings): Chunk, tokenize and embed each paper content inside a QDrant vector store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U4da4cMXZ0_j_8RveuAOXA.png" /><figcaption>Ingestion Workflow, from document to embedding ingested into QDrant</figcaption></figure><p><strong>4. RAG</strong> (OpenAI Embeddings + Semantic Search): Use Retrieval Augmented Generation (RAG) to extract the necessary pieces of knowledge to answer the step query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F-XsqCeoBAyYBIicncn0dg.png" /></figure><p><strong>Web Search Agent with MCP Integration</strong></p><p>The web search agent uses the <a href="https://docs.tavily.com/documentation/mcp">Tavily MCP server</a> for real-time information. This way, we are able to dynamically search for new knowledge, delegating the constraints selection to the LLM. Tavily in fact has a different set of search constraints, like:</p><ul><li>Start Date and End Date</li><li>Search Topic</li><li>Search Depth</li></ul><p><strong>Output example</strong> for the second step’s query:</p><blockquote>latest developments graph theory</blockquote><pre>{<br>  &quot;query&quot;: &quot;latest developments graph theory&quot;,<br>  &quot;results&quot;: [<br>    {<br>      &quot;url&quot;: &quot;https://www.quantamagazine.org/how-does-graph-theory-shape-our-world-20250626/&quot;,<br>      &quot;title&quot;: &quot;How Does Graph Theory Shape Our World? - Quanta Magazine&quot;,<br>      &quot;content&quot;: &quot;Maria Chudnovsky reflects on her journey in graph theory, her groundbreaking solution to the long-standing perfect graph problem, and the unexpected ways this&quot;,<br>      &quot;score&quot;: 0.98533,<br>      &quot;raw_content&quot;: null<br>    },<br>    {<br>      &quot;url&quot;: &quot;https://ijsrem.com/download/a-review-on-the-latest-developments-in-graph-theory-and-its-applications/&quot;,<br>      &quot;title&quot;: &quot;A review on the latest developments in graph theory and its ...&quot;,<br>      &quot;content&quot;: &quot;This study explores recent advances in graph theory, particularly in terms of algorithmic development, novel types of graphs, and their diverse applications.&quot;,<br>      &quot;score&quot;: 0.98393,<br>      &quot;raw_content&quot;: null<br>    },<br>    {<br>      &quot;url&quot;: &quot;https://news.mit.edu/2024/graph-based-ai-model-maps-future-innovation-1112&quot;,<br>      &quot;title&quot;: &quot;Graph-based AI model maps the future of innovation | MIT News&quot;,<br>      &quot;content&quot;: &quot;The new AI approach uses graphs based on methods inspired by category theory as a central mechanism to understand symbolic relationships in&quot;,<br>      &quot;score&quot;: 0.97673,<br>      &quot;raw_content&quot;: null<br>    },<br>    {<br>      &quot;url&quot;: &quot;https://www.mdpi.com/journal/axioms/special_issues/560T7U3LML&quot;,<br>      &quot;title&quot;: &quot;Special Issue : Recent Developments in Graph Theory - Axioms&quot;,<br>      &quot;content&quot;: &quot;This special issue focuses on advancements in graph theory, discrete applied mathematics, domination theory, and chemical graph theory, with applications in&quot;,<br>      &quot;score&quot;: 0.97205,<br>      &quot;raw_content&quot;: null<br>    },<br>    {<br>      &quot;url&quot;: &quot;https://research.google/blog/the-evolution-of-graph-learning/&quot;,<br>      &quot;title&quot;: &quot;The evolution of graph learning - Google Research&quot;,<br>      &quot;content&quot;: &quot;We describe how graphs and graph learning have evolved since the advent of PageRank in 1996, highlighting key studies and research.&quot;,<br>      &quot;score&quot;: 0.97179,<br>      &quot;raw_content&quot;: null<br>    }<br>  ],<br>  &quot;response_time&quot;: 1.4<br>}</pre><h4>Step 4: Knowledge Gathering and Answer</h4><p>Finally, we aggregate the knowledge generated through the execution of the different steps to derive the answer.</p><pre>system_prompt = &quot;&quot;&quot;Synthesize the research results to provide a direct, comprehensive answer to the user&#39;s query.<br><br>Research Results:<br>{results}<br><br>User Query:<br>{query}<br><br>Instructions:<br>- Use ALL research findings to answer the query completely<br>- Support your response with specific evidence from the results<br>- For EVERY piece of information you include, cite the source with proper references<br>- When referencing ArXiv papers, use the format: [Author et al., Year] (arXiv:ID)<br>- When referencing web sources, use the format: [Title] (URL)<br>- Include a &quot;References&quot; section at the end listing all sources used<br>- Structure your answer clearly and concisely with proper citations throughout<br>- Address the query directly without unnecessary elaboration<br>- Ensure each claim or statement is backed by a specific source reference&quot;&quot;&quot;<br><br><br>class AnswerAgent(BaseAgent):<br>    &quot;&quot;&quot;Agent for synthesizing research results into a comprehensive answer.&quot;&quot;&quot;<br><br>    def __init__(self, *, name: str, run_id: str) -&gt; None:<br>        &quot;&quot;&quot;<br>        Initialize the AnswerAgent.<br><br>        Args:<br>            name: Name of the agent<br>            run_id: Unique identifier for the current run<br>        &quot;&quot;&quot;<br>        super().__init__(name=name)<br>        self._run_id = run_id<br><br>        self._answer_llm = LlmAgent(<br>            model=&#39;gemini-2.0-flash&#39;,<br>            name=f&#39;answer&#39;,<br>            instruction=system_prompt.format(<br>                results=f&#39;{{results:{self._run_id}}}&#39;,<br>                query=&#39;{query}&#39;,<br>            ),<br>        )<br><br>    async def _run_async_impl(self, context: InvocationContext) -&gt; AsyncGenerator[Event, None]:<br>        &quot;&quot;&quot;<br>        Execute the answer generation process.<br><br>        Args:<br>            context: Invocation context containing research results and query<br><br>        Yields:<br>            Events from the answer generation LLM<br>        &quot;&quot;&quot;<br>        async for event in self._answer_llm.run_async(context):<br>            yield event</pre><p>Finally, we get the answer (shortened here for clarity and brevity):</p><blockquote>Recent advancements in graph theory include:</blockquote><blockquote><strong>Graph Transformers (GTs)</strong>: These have demonstrated strong capabilities in modeling graph structures and addressing limitations of graph neural networks (GNNs) such as over-smoothing and over-squashing [Bharatiya’s Blog]. Research focuses on architectures, explainability, and applications [2502.16533v2].</blockquote><blockquote><strong>Superhypergraph Neural Networks (SHGNNs) and Plithogenic Graph Neural Networks</strong>: Theoretical foundations are being established to expand neural network applicability to these advanced graph structures [<strong>2412.01176v1</strong>].</blockquote><blockquote>…</blockquote><blockquote><strong>REFERENCES</strong>:</blockquote><blockquote>* [2502.16533v2] A Survey of Graph Transformers: Architectures, Theories and Applications (<strong>http://arxiv.org/pdf/2502.16533v2</strong>)</blockquote><blockquote>* [2412.01176v1] Superhypergraph Neural Networks and Plithogenic Graph Neural Networks: Theoretical Foundations (<strong>http://arxiv.org/pdf/2412.01176v1</strong>)</blockquote><blockquote>…</blockquote><h3>4. Results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XuQzJO4K4blBFskrLCU3lg.gif" /></figure><p><strong>Performance Metrics:</strong></p><ul><li><strong>Query Processing Time</strong>: 27 seconds (parallel execution)</li><li><strong>Papers Analyzed</strong>: 100 total across 2 ArXiv searches</li><li><strong>Papers Selected</strong>: 6 high-relevance papers</li><li><strong>Web Sources</strong>: 5 sources from major tech companies and research institutions</li><li><strong>Response Quality</strong>: Comprehensive coverage of both theoretical foundations and practical implementations</li></ul><h3>5. Conclusion</h3><p>This prototype represents just the beginning. The modular and extensible nature of this system makes it an ideal foundation for continuous improvement. Future development can focus on several key areas to push the boundaries of multi-agent research:</p><ul><li><strong>Expanded Tooling for Heterogeneous Data:</strong> The current system uses ArXiv and web search. This can be extended by integrating more specialized tools to gather diverse information. Imagine adding a financial data API to analyze stock market trends, a medical database for clinical research, or a social media analytics tool for public sentiment analysis.</li><li><strong>Leveraging Advanced Embedding Models:</strong> The system currently uses OpenAI embeddings, but Google’s own <strong>Gemini Embeddings</strong> offer a compelling alternative. Migrating to Gemini Embeddings would avoid using OpenAI completely.</li><li><strong>Transitioning to Production-Grade Infrastructure:</strong> To move from a prototype to a scalable, reliable service, the infrastructure must be hardened. Migrating the Qdrant vector store to a fully managed cloud solution like <strong>GCP Vector Search</strong> would provide enterprise-grade features.</li><li><strong>Introducing New Agent Personas:</strong> The current system uses four agent types, but new agents could be added to tackle more complex tasks. A “Critique Agent” could analyze the final response for biases or logical fallacies, an “Expert Agent” could be fine-tuned on a specific domain (e.g., legal or medical) to provide highly specialized insights, or a “Creative Agent” could help brainstorm new research directions based on the gathered data.</li></ul><p><strong>Github Repo </strong><a href="https://github.com/lorenzofavaro/deep-research"><strong>here</strong></a><strong>!</strong></p><blockquote><strong>References:</strong></blockquote><blockquote><a href="https://github.com/google/adk-python">https://github.com/google/adk-python</a></blockquote><blockquote><a href="https://github.com/google/adk-python">https://cloud.google.com/vertex-ai/generative-ai/docs/models/gemini</a></blockquote><blockquote><a href="https://github.com/google/adk-python">https://qdrant.tech/</a></blockquote><blockquote><a href="https://docs.tavily.com/documentation/mcp">https://docs.tavily.com/documentation/mcp</a></blockquote><blockquote><a href="https://platform.openai.com/docs/guides/embeddings">https://platform.openai.com/docs/guides/embeddings</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3df8df8b6335" width="1" height="1" alt=""><hr><p><a href="https://aiadvances.org/building-an-deep-research-system-with-google-adk-gemini-qdrant-and-mcp-3df8df8b6335">Building an Deep Research System with Google ADK, Gemini, QDrant, and MCP</a> was originally published in <a href="https://aiadvances.org/">AI Advances</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Wasting Money on LLMs: A Smart Orchestrator for Cost efficient AI]]></title>
            <link>https://ai.plainenglish.io/stop-wasting-money-on-llms-a-smart-orchestrator-for-cost-efficient-ai-30fba76d193e?source=rss-74ad312f5896------2</link>
            <guid isPermaLink="false">https://medium.com/p/30fba76d193e</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[multi-agent-systems]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[cost-efficient-ai]]></category>
            <dc:creator><![CDATA[Lorenzo Favaro]]></dc:creator>
            <pubDate>Wed, 27 Aug 2025 21:55:50 GMT</pubDate>
            <atom:updated>2025-09-01T02:33:10.156Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CI7sL3N42p21icGhLQWwyA.png" /><figcaption>Image by <a href="https://medium.com/@lorenzofavaro">author</a>: Different agents working together</figcaption></figure><ol><li>🧠 Project overview</li><li>📊 Results</li><li>🔚 Conclusion</li></ol><p><strong>Github Repo </strong><a href="https://github.com/lorenzofavaro/agentic-workflow-orchestrator"><strong>here</strong></a><strong>!</strong></p><p>Choosing the right AI model for the job isn’t easy, especially when you have a bunch of different models, each with their own strengths, weaknesses, and costs.</p><p>That’s exactly the challenge this project tackles: how can we build a multi agent system that <strong>plans, selects, and coordinates</strong> multiple language models to solve complex tasks, all while keeping an eye on <strong>quality</strong>, <strong>speed</strong>, and <strong>budget</strong>? <br>The result is a modular system that <strong>lets models compete</strong>, <strong>learn from feedback</strong>, and adapt to different needs, without breaking the bank.</p><h3>1. Project overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GP8geCaM_xGwinbh08HHOg.png" /><figcaption>Image by <a href="https://medium.com/@lorenzofavaro">author</a>: System architecture (created with <a href="https://excalidraw.com/">excalidraw.com</a>)</figcaption></figure><h3>Planner</h3><p>The planner receives the user’s question and generates a structured plan to address it. It follows a <strong>divide-and-conquer strategy</strong>, breaking down the main problem into a sequence of manageable <strong>steps</strong> (subproblems).</p><pre>class PlanStep(BaseModel):<br>    &quot;&quot;&quot;<br>    Represents a single step in a plan, including the required skill, description, and constraints.<br>    &quot;&quot;&quot;<br>    skill: str = Field(..., description=&quot;The skill required for this step&quot;)<br>    description: str = Field(..., description=&quot;Human-readable description of the step&quot;)<br>    k_models: int = Field(2, description=&quot;Number of models that will compete for this step&quot;)<br>    tier_hint: Optional[int] = Field(None, description=&quot;Minimum model tier for this step: 0=cheap, 1=mid, 2=premium&quot;)<br>    max_rounds: int = Field(1, description=&quot;Number of improvement rounds allowed by the verifier&quot;)</pre><p>Each step must have different attributes:</p><ul><li><strong>skill</strong>: The specific ability required to accomplish the step (e.g., analyze, reason, code, math, summarize, plan).</li><li><strong>description</strong>: A concise, human-readable explanation of what the step entails.</li><li><strong>k_models</strong>: The number of models that will independently attempt the step, allowing for competition and selection of the best result.</li><li><strong>tier_hint</strong>: (Optional) The minimum quality or cost tier of models eligible for this step (0=cheap, 1=mid, 2=premium). Some tasks may be more complex and therefore require higher-tier models.</li><li><strong>max_rounds</strong>: The maximum number of improvement or verification rounds permitted for this step, enabling iterative refinement if needed.</li></ul><p>A certain number of steps compose the overall plan.</p><pre>class Plan(BaseModel):<br>    &quot;&quot;&quot;<br>    Represents a multi-step plan, including steps, budget, latency, and random seed.<br>    &quot;&quot;&quot;<br>    steps: List[PlanStep] = Field(..., description=&quot;List of plan steps&quot;)<br>    hard_budget_usd: float = Field(..., description=&quot;Hard budget limit in USD&quot;)<br>    hard_latency_s: Optional[float] = Field(None, description=&quot;Hard latency limit in seconds&quot;)<br>    seed: int = Field(123, description=&quot;Random seed for reproducibility&quot;)</pre><p>In addition to the steps, the plan also includes crucial constraints. For example, you can specify the <strong>maximum budget</strong> you want to spend on the request, expressed in USD (e.g., hard_budget_usd=5.0 to limit the total cost to $5). You can also set the <strong>maximum allowed latency</strong> in seconds (e.g., hard_latency_s=10.0 to ensure the plan completes within 10 seconds).</p><p>The current planner logic is driven by the following prompt:</p><pre>PLANNER_PROMPT = &quot;&quot;&quot;Create the **most concise step-by-step plan** to solve this task: {task}<br><br>Requirements:<br>- Minimize the number of steps; each step must be as short as possible.<br>- For each step, specify:<br>  1. **Skill**: Choose exactly one skill from: {skills}<br>  2. **Models (k_models)**: Specify as an **integer** the number of models that will compete to solve this step.<br>     - 1 for simple steps (only one model executes the step)<br>     - 2 for complex steps (two models with the required skill execute the step and the best result is chosen)<br>  3. **Tier hint**: Specify as an **integer** the minimum tier of model to consider for this step (0=cheap, 1=mid, 2=premium).<br>  4. **Max rounds**: Specify as an **integer** the maximum number of improvement rounds allowed by the verifier for this step (max 3 for really important steps).<br>  5. **Description**: Provide a short human-readable description of the step.<br><br>Format your response as a structured plan with brief, clear step descriptions only.&quot;&quot;&quot;</pre><p>The make_plan function leverages this prompt and the acomplete_structured adapter method to ensure the response <strong>is always well-structured and formatted</strong> as a Planobject.</p><pre>async def make_plan(<br>        self, task: str, budget_usd: float, latency_s: Optional[float]<br>    ) -&gt; Plan:<br>        &quot;&quot;&quot;<br>        Generate a plan for the given task and constraints using the language model.<br>        Args:<br>            task (str): The task to plan for.<br>            budget_usd (float): The hard budget limit in USD.<br>            latency_s (Optional[float]): The hard latency limit in seconds.<br>        Returns:<br>            Plan: The generated plan.<br>        &quot;&quot;&quot;<br>        user = self.task_prompt.format(task=task, skills=&quot;, &quot;.join(skill.value for skill in Skill))<br>        req = CallRequest(system=PLANNER_SYSTEM_PROMPT, user=user, temperature=0, max_tokens=512)<br>        <br>        res: CallResult = await self.adapter.acomplete_structured(req, Plan)<br>        plan: Plan = res.structured<br>        plan.hard_budget_usd = budget_usd<br>        plan.hard_latency_s = latency_s<br>        <br>        return plan</pre><h3>Router</h3><p>The router is responsible for selecting <strong>which language model </strong>will be used to execute each step of the plan generated by the planner. It acts as a dynamic load balancer and performance optimizer, making decisions based on both historical performance and configurable policies.</p><h4>Tracking model</h4><p>The router maintains statistics for each model, including usage count (pulls), average win rate, and average cost:</p><pre>@dataclass<br>class ArmStat:<br>    &quot;&quot;&quot;<br>    Tracks statistics for an adapter (arm) in the router, including pulls, winrate, and cost.<br>    &quot;&quot;&quot;<br>    pulls: int = 0<br>    winrate: float = 0.0<br>    cost: float = 0.0<br><br>    def update(self, reward: float, cost: float) -&gt; None:<br>        &quot;&quot;&quot;<br>        Update statistics with a new reward and cost observation.<br>        Args:<br>            reward (float): The observed reward.<br>            cost (float): The observed cost.<br>        &quot;&quot;&quot;<br>        self.pulls += 1<br>        self.winrate += (reward - self.winrate) / self.pulls<br>        self.cost += (cost - self.cost) / self.pulls</pre><h4><strong>Scoring and selection</strong></h4><p>When a step needs to be assigned, the router computes a score for each eligible model, balancing <strong>exploitation</strong> (using the best so far) and <strong>exploration</strong> (occasionally trying others):</p><pre>def _score(self, name: str) -&gt; float:<br>        &quot;&quot;&quot;<br>        Compute a score for an adapter based on winrate, cost, and exploration.<br>        Args:<br>            name (str): The name of the adapter.<br>        Returns:<br>            float: The computed score.<br>        &quot;&quot;&quot;<br>        s = self.stats[name]<br>        explore = self.rng.random() &lt; self.cfg.epsilon<br>        if explore or s.pulls == 0:<br>            return self.rng.random()<br>        # Default static utility: winrate − alpha·cost<br>        return s.winrate - self.cfg.alpha_cost * s.cost</pre><p>It then <strong>selects the top-k models</strong> matching the required skill and tier:</p><pre>def pick_k(self, skill: str, k: int, tier_hint: Optional[int] = None) -&gt; List[str]:<br>        &quot;&quot;&quot;<br>        Select up to k adapter names that match the skill and tier requirements, ordered by score.<br>        Args:<br>            skill (str): The required skill.<br>            k (int): Number of adapters to select.<br>            tier_hint (Optional[int]): Minimum model tier required.<br>        Returns:<br>            List[str]: List of selected adapter names.<br>        &quot;&quot;&quot;<br>        cand = [<br>            a<br>            for a in self.adapters.values()<br>            if (tier_hint is None or a.spec.tier &gt;= tier_hint)<br>            and (not skill or any(s.value == skill for s in a.spec.skills) or not a.spec.skills)<br>        ]<br>        if not cand:<br>            cand = list(self.adapters.values())<br>        scored = sorted(cand, key=lambda a: self._score(a.spec.name), reverse=True)<br>        return [a.spec.name for a in scored[: max(1, k)]]</pre><h4>Learning and adaptation</h4><p>After each step, the router <strong>updates the statistics</strong> for the models used, allowing it to learn and adapt over time:</p><pre>def update(self, name: str, reward: float, cost: float) -&gt; None:<br>        &quot;&quot;&quot;<br>        Update the statistics for a given adapter after an outcome.<br>        Args:<br>            name (str): The name of the adapter.<br>            reward (float): The observed reward.<br>            cost (float): The observed cost.<br>        &quot;&quot;&quot;<br>        self.stats[name].update(reward, cost)</pre><h3>Debate</h3><p>The Debate component orchestrates a “debate” among multiple language models, allowing them to <strong>independently generate responses to the same prompt</strong> in parallel. This mechanism enables the system to <strong>compare</strong>, <strong>select</strong>, or further process <strong>multiple candidate answers</strong>.</p><h4>Parallel Execution of Models</h4><p>The Debate class receives a list of model names and a request. It then runs each one asynchronously, collecting their responses as candidates:</p><pre>async def run(self, names: List[str], req: CallRequest) -&gt; List[Candidate]:<br>        &quot;&quot;&quot;<br>        Run a debate among the specified adapters, collecting their responses in parallel.<br>        Args:<br>            names (List[str]): List of adapter names to participate in the debate.<br>            req (CallRequest): The request to send to each adapter.<br>        Returns:<br>            List[Candidate]: List of candidate responses from each adapter.<br>        &quot;&quot;&quot;<br>        async def one(name: str) -&gt; Candidate:<br>            res = await self.adapters[name].acomplete(req)<br>            return Candidate(<br>                name,<br>                res.text,<br>                res.latency_s,<br>                res.cost_usd,<br>                res.tokens_in,<br>                res.tokens_out,<br>            )<br><br>        return await asyncio.gather(*[one(n) for n in names])</pre><p>The Debate component is typically used when a plan step <strong>specifies </strong><em>k_models &gt; 1</em>, meaning multiple models should attempt the same task.</p><h3>Judge</h3><p>The Judge component <strong>evaluates multiple candidate responses</strong> and <strong>selects the best one</strong>. It acts as an impartial evaluator to determine which response best addresses the given task.</p><h4>LLM-Based Judging</h4><p>We use a language model as the judge with this prompt:</p><pre>JUDGE_SYSTEM_PROMPT = &quot;You are a strict evaluator.&quot;<br>JUDGE_USER_PROMPT = &quot;Task: {task} Choose the best numbered answer and provide a short rationale.{listing}&quot;</pre><p>The judge formats all candidates into a <strong>numbered list</strong> and asks the language model to select the best one with a reason:</p><pre>async def pick(<br>        self, task: str, candidates: List[Candidate]<br>    ) -&gt; Tuple[int, Dict[str, Any]]:<br>        &quot;&quot;&quot;<br>        Use the language model to select the best candidate for the given task.<br>        Args:<br>            task (str): The task or question to judge.<br>            candidates (List[Candidate]): List of candidate answers.<br>        Returns:<br>            Tuple[int, Dict[str, Any]]: Index of the best candidate and additional judge information.<br>        &quot;&quot;&quot;<br>        listing = &quot;&quot;.join([f&quot;[#{i}]{c.text}&quot; for i, c in enumerate(candidates)])<br>        <br>        req = CallRequest(<br>            system=JUDGE_SYSTEM_PROMPT,<br>            user=JUDGE_USER_PROMPT.format(task=task, listing=listing),<br>        )<br>        res: CallResult = await self.judge.acomplete_structured(req, JudgeResponse)<br>        judge_response: JudgeResponse = res.structured<br>        return judge_response.best_answer_index, {&quot;judge_text&quot;: str(judge_response)}</pre><p>Finally, it returns a structured response that includes both the selection and reasoning:</p><pre>class JudgeResponse(BaseModel):<br>    &quot;&quot;&quot;<br>    Structured response from the judge, indicating the best answer and the reason for the choice.<br>    &quot;&quot;&quot;<br>    best_answer_index: int = Field(..., description=&quot;The best answer&#39;index among candidates&quot;)<br>    reason: str = Field(..., description=&quot;Short reason for the decision&quot;)</pre><h3>Verifier</h3><p>The Verifier component performs quality control by <strong>checking whether an answer is acceptable or needs revision</strong>.</p><h4>LLM-Based Verification</h4><p>Again, we use a language model as the verifier, with the following prompts:</p><pre>VERIFIER_SYSTEM_PROMPT = &quot;You are a strict verifier.&quot;<br>VERIFIER_USER_PROMPT = &quot;Task: {task} Answer: {answer} Metadata: {metadata}&quot;</pre><p>The verifier evaluates the answer against the task and returns a structured decision with reasoning:</p><pre>async def check(<br>        self, task: str, answer: str, metadata: Dict[str, Any]<br>    ) -&gt; Tuple[bool, Dict[str, Any]]:<br>        &quot;&quot;&quot;<br>        Use the language model to check the validity of an answer for a given task and metadata.<br>        Args:<br>            task (str): The task or question being verified.<br>            answer (str): The answer to verify.<br>            metadata (Dict[str, Any]): Additional metadata for verification.<br>        Returns:<br>            Tuple[bool, Dict[str, Any]]: (True if accepted, False if revision needed; additional verifier info)<br>        &quot;&quot;&quot;<br>        req = CallRequest(<br>            system=VERIFIER_SYSTEM_PROMPT,<br>            user=VERIFIER_USER_PROMPT.format(task=task, answer=answer, metadata=metadata),<br>        )<br>        res: CallResult = await self.ver.acomplete_structured(req, VerifyResponse)<br>        verify_response: VerifyResponse = res.structured<br>        return verify_response.response == &quot;ACCEPT&quot;, {&quot;verifier_text&quot;: str(verify_response)}</pre><p>It also returns a structured response indicating whether to accept the answer or request a revision:</p><pre>class VerifyResponse(BaseModel):<br>    &quot;&quot;&quot;<br>    Structured response from the verifier, indicating whether to accept or revise the answer and the reason.<br>    &quot;&quot;&quot;<br>    response: str = Field(..., description=&quot;ACCEPT or REVISE the answer&quot;)<br>    reason: str = Field(..., description=&quot;Short reason for the decision&quot;)</pre><h3>Adaptive Improvement Mechanism</h3><p>When the verifier rejects an answer as inadequate, the system doesn’t just fail, it automatically attempts to <strong>improve the response using a smarter model</strong>.</p><p>The improvement process kicks in when two conditions are met:</p><ol><li><strong>The verifier rejects the chosen answer</strong> (<em>not ok</em>)</li><li><strong>The step allows improvement rounds</strong> (<em>step.max_rounds &gt; 0</em>) and there’s budget remaining</li></ol><pre>...<br>if (not ok) and step.max_rounds &gt; 0 and budget.usd_left &gt; 0.0:<br>    # Escalate to a higher tier model<br>    next_tier = max(self.adapters[n].spec.tier for n in names) + 1<br>    names2 = self.router.pick_k(<br>        skill=step.skill, k=1, tier_hint=next_tier,<br>    )<br>...</pre><p>When this happens, the system follows an escalation strategy.</p><h4>Smart escalation</h4><p>Instead of randomly trying different models, the system intelligently escalates to the next tier. If the original attempt used tier = 0 (cheap) models, it jumps to tier = 1 (mid-range) or even tier = 2 (premium) models. A basic prompt is used:</p><pre>AGENT_IMPROVE_SYSTEM_PROMPT = &quot;Improve the answer.&quot;<br>AGENT_IMPROVE_USER_PROMPT = &quot;Task: {task} Previous answer: {previous} Fix issues succinctly.&quot;</pre><h4>Head to head competition</h4><p>The improved answer doesn’t automatically replace the original. Instead, both responses compete in a final judge round.</p><p>This mechanism elegantly balances cost and quality:</p><ul><li><strong>Start cheap</strong>: Initial attempts use lower-tier models</li><li><strong>Escalate smartly</strong>: Only spend more when quality is insufficient</li><li><strong>Budget-aware</strong>: Improvements only happen if budget allows</li><li><strong>Verifiable</strong>: Even improved answers go through verification</li></ul><p>Over time, the system learns which models consistently produce verifiable results for different skills, reducing the need for costly improvement rounds.</p><h3>2. Results</h3><p>To evaluate the system’s effectiveness, a test was conducted with a complex, multi-part query. The query required several distinct skills: data <strong>analysis</strong>, <strong>reasoning</strong>, <strong>mathematical calculation</strong>, and <strong>code generation</strong>. The goal was to see if the orchestrator could break down the task, route each sub-problem to an appropriate model, and deliver a coherent, accurate final response within the specified budget of $0.10 USD.</p><p>I tested three models that share some overlapping capabilities (you can test whatever model you want):</p><ul><li>Gemini 1.5 Flash</li><li>GPT 4o</li><li>GPT 4o mini</li></ul><p>The question I asked was:</p><blockquote>“You are given monthly website data: January 1200 visits and 60 conversions, February 1500 visits and 63 conversions, March 1600 visits and 80 conversions, April 1800 visits and 81 conversions, May 2000 visits and 100 conversions, and June 2400 visits and 120 conversions.</blockquote><blockquote>Describe the main pattern you observe, propose a plausible explanation for it, calculate the overall conversion rate as a percentage with two decimal places, and then provide a short Python snippet (without external libraries) that can compute this conversion rate when given a list of (visits, conversions) pairs.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kO0CKiI4JrkHe1LVj9JIFA.png" /><figcaption>Image by <a href="https://medium.com/@lorenzofavaro">author</a> — Steps log</figcaption></figure><p><strong>Planning and Initial Selection</strong>: The orchestrator generated a plan with four steps, each with a specific skill. The key difference here is in the model selection.</p><ul><li><strong>Step 1 (</strong><strong>analyze)</strong>: The router selected two models, gpt-4o-mini and gemini-1.5-flash, to compete. The <strong>Debate</strong> component ran both in parallel, and the <strong>Judge</strong> chose the response from gemini-1.5-flash as the best candidate (Chosen candidate: #1). This shows the system isn&#39;t hard-coded to a single model; it leverages competition to find the optimal result.</li><li><strong>Step 2 (</strong><strong>reason)</strong>: This step, deemed less complex, was handled by a single model, gpt-4o-mini, as specified by the plan&#39;s k_models parameter.</li><li><strong>Step 3 (</strong><strong>math)</strong>: The router again initiated a debate, this time between gpt-4o and gpt-4o-mini. The gpt-4o response was selected as the best one, reinforcing its reputation for mathematical accuracy.</li><li><strong>Step 4 (</strong><strong>code)</strong>: Similar to the first step, gpt-4o and gemini-1.5-flash competed. The judge&#39;s choice of gpt-4o as the best candidate demonstrates its superior performance for code generation in this instance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T3Y8ew7A7M3ZNPVlSxmyFw.png" /><figcaption>Image by <a href="https://medium.com/@lorenzofavaro">author</a> — Results log</figcaption></figure><p>The final output provides the data pattern, explanation, a conversion rate of <strong>4.80%</strong>, and a working Python snippet. The consistency of the final answer across different model selections proves the system’s robustness.</p><ul><li><strong>Total Cost</strong>: The total cost remains the same at <strong>$0.0190 USD</strong>, well below the budget. This highlights that adding competition doesn’t necessarily increase costs significantly, especially when using cost-effective models. The minimal additional cost of running two models is offset by the increased confidence in the final result.</li><li><strong>Total Latency</strong>: The total latency was <strong>31.19 seconds</strong>. While running models in parallel can sometimes reduce latency, the overhead of the judging and verification processes means the overall time can be similar to a sequential run. The priority here is <strong>quality and accuracy</strong>, which the parallel execution and judging mechanism ensure.</li></ul><h3>3. Conclusion</h3><p>This project was all about one thing: being smart with how we use large language models. Instead of just throwing a single, expensive model at every problem, we built a system that thinks.</p><p>The real magic happens when something isn’t quite right. Our system doesn’t just give up. Instead, it <strong>adaptively improves</strong> by bringing in a smarter, more capable model to fix the problem, but only if the budget allows. This intelligent escalation means we start cheap and only spend more when we absolutely have to.</p><p>Ultimately, we proved that you don’t have to break the bank to get high-quality AI results. By orchestrating a team of specialized models, we can get a robust, accurate answer for a fraction of the cost. It’s about working smarter, not harder, or in this case, spending smarter, not more.</p><p><strong>Github Repo </strong><a href="https://github.com/lorenzofavaro/agentic-workflow-orchestrator"><strong>here</strong></a><strong>!</strong></p><blockquote>References:</blockquote><blockquote><a href="https://arxiv.org/abs/2411.07464">https://arxiv.org/abs/2411.07464</a></blockquote><blockquote><a href="https://www.oreilly.com/radar/llm-system-design-and-model-selection/">https://www.oreilly.com/radar/llm-system-design-and-model-selection</a></blockquote><blockquote><a href="https://cloud.google.com/architecture/framework/perspectives/ai-ml/cost-optimization">https://cloud.google.com/architecture/framework/perspectives/ai-ml/cost-optimization</a></blockquote><blockquote><a href="https://www.evidentlyai.com/llm-guide/llm-as-a-judge">https://www.evidentlyai.com/llm-guide/llm-as-a-judge</a></blockquote><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30fba76d193e" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/stop-wasting-money-on-llms-a-smart-orchestrator-for-cost-efficient-ai-30fba76d193e">Stop Wasting Money on LLMs: A Smart Orchestrator for Cost efficient AI</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>