<?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 Josias Hartmann on Medium]]></title>
        <description><![CDATA[Stories by Josias Hartmann on Medium]]></description>
        <link>https://medium.com/@josias.hartmann?source=rss-75d40deb740f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kIRJeFR9RHULMWfeBygG5Q.png</url>
            <title>Stories by Josias Hartmann on Medium</title>
            <link>https://medium.com/@josias.hartmann?source=rss-75d40deb740f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:48:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@josias.hartmann/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[How to build a multi-agent content development team using LangGraph]]></title>
            <link>https://medium.com/indiciumtech/how-to-build-a-multi-agent-content-development-team-using-langgraph-d062ce4051c3?source=rss-75d40deb740f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d062ce4051c3</guid>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Josias Hartmann]]></dc:creator>
            <pubDate>Wed, 10 Jul 2024 14:17:12 GMT</pubDate>
            <atom:updated>2024-07-10T18:29:42.525Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LFm-B65wMa0-pxiW7tYT0A.png" /></figure><p>Hey! I’m back.</p><p>Building a multi-agent content development team can be complex, especially when using advanced tools like LangGraph.</p><p>But don’t worry!</p><p>In this post, I’ll guide you step-by-step through creating a simple yet effective multi-agent team with LangGraph.</p><p>We’ll revisit some key concepts to ensure a solid understanding, making the process smoother even if you’re new to LangGraph.</p><p>Let’s dive in and master this powerful tool together!</p><p><strong>What is Lan…</strong></p><p>“This again?” One might ask.</p><p>Yeah, bear with me, let’s fix this concept once and for all!</p><h4><strong>What is LangGraph?</strong></h4><p>Well, as I was saying, LangGraph is an extension of LangChain, whose main objective is creating agent and multi-agent projects.</p><p>It adds the ability to create cyclical flows while providing developers a high degree of control, which is — obviously — very important for creating custom agents and flows.</p><p>I think that’s enough theoretical jibber jabber for now. Let’s start building something!</p><p>I don’t know if you all read my first blog post about LangGraph. If you didn’t and want to check out some basics, here it is: <a href="https://medium.com/indiciumtech/what-is-langgraph-and-can-it-help-you-build-llm-agents-c66b6def0b83">What is LangGraph and can it help you build LLM agents?</a></p><h4><strong>Building — not the best, but — pretty good content development team</strong></h4><p>With this project, I want to show you all that we can improve almost any process in depth and quality by leveraging multiple agents with specialized skills.</p><p>Why is that?</p><p>Well, having every agent focus and specialize only in a specific task allows more customizability, better separation of concerns, and, of course, further development as the project grows. LangGraph is no place for a jack of all trades.</p><h4><strong>The content development team</strong></h4><p>Our humble team consists of three agents:</p><p><strong>Researcher</strong> — This fella is specialized in web search. He will deliver in-depth research on a given topic. No questions asked.</p><p><strong>Editor</strong> — The role of this agent is to be annoying to his buddy, the researcher. The editor will review the content brought by the researcher agent and demand more whenever he thinks it’s needed. He will also provide some query tips.</p><p><strong>Writer</strong> — This is the last agent of our flow, responsible for writing about the suggested topic using the context available from the previously mentioned agents.</p><p>Before we get started with the setup, I want to let you know that the code I’ll be showing you was originally written and tested in a Jupyter notebook. If you’d like to download and test it yourself, you can find the notebook <a href="https://github.com/techindicium/tech-blog/blob/main/GenAI/2024-07-03-How-to-build-a-multi-agent-content-development-team-using-LangGraph/how-to-build-a-multi-agent-content-development-team-using-LangGraph.ipynb">here</a>.</p><p><strong>As promised, we will now dive into the code!!</strong></p><h4>Setup</h4><p>As always, first we need to install the required packages.</p><pre>%%capture --no-stderr<br>%pip install -U langgraph langsmith<br><br># Used for this tutorial; not a requirement for LangGraph<br>%pip install -U langchain_openai</pre><p>Next, let’s set the API key for OpenAI.</p><pre>import os<br>import getpass<br><br>os.environ[&quot;OPENAI_API_KEY&quot;] = getpass.getpass(&quot;OpenAI API Key:&quot;)</pre><p>Also, let’s set up our <a href="https://www.langchain.com/langsmith">LangSmith</a> key, as it makes it a lot easier to see what’s going on under the hood (optional, but encouraged).</p><pre>os.environ[&quot;LANGSMITH_API_KEY&quot;] = getpass.getpass(&quot;LangSmith API Key:&quot;)<br>os.environ[&quot;LANGCHAIN_TRACING_V2&quot;] = &quot;true&quot;<br>os.environ[&quot;LANGCHAIN_PROJECT&quot;] = &quot;Multi-Agent Tutorial&quot;</pre><p>We’ll be using the <a href="https://python.langchain.com/v0.1/docs/integrations/tools/tavily_search/">Tavily Search Engine</a>. <strong>It’s super easy to register and they offer a free tier.</strong> Feel free to check <a href="https://gptr.dev/">GPT Researcher</a> as well!</p><pre>os.environ[&quot;TAVILY_API_KEY&quot;] = getpass.getpass(&quot;Tavily API Key:&quot;)</pre><h4><strong>Define the State</strong></h4><p>Now, this is an awesome feature from LangGraph that I absolutely love: state management.</p><p>States in LangGraph are facilitated through a structured approach, in which developers define a GraphState that encapsulates the entire state of the application. Each node in the graph can modify this state, allowing for dynamic responses based on the evolving context of the interaction.</p><p>If you’ve worked with data, you know the data schema is always a key point that you just can’t take for granted, even in a simple project like this one. Check ours out:</p><pre>from langgraph.graph import StateGraph<br>from langgraph.graph.message import add_messages<br>from typing_extensions import TypedDict<br>from typing import Annotated<br><br><br>class State(TypedDict):<br>    query: Annotated[list, add_messages]<br>    research: Annotated[list, add_messages]<br>    content: str<br>    content_ready: bool<br>    iteration_count: int  # Counter for iterations<br><br># Initialize the StateGraph<br>graph = StateGraph(State)</pre><h4>Introducing our multi-agent team</h4><p>Let’s dive into the team we were talking about: our one and only <strong>content development team</strong>. It is made up of three specialized agents, each with a distinct role to ensure high-quality content development.</p><h4>Research Agent</h4><p>First up, we have the Research Agent. This agent is responsible for conducting in-depth web searches to gather valuable information on a given topic.</p><pre>from langchain_community.tools.tavily_search import TavilySearchResults<br>from langchain_openai import ChatOpenAI<br><br># Initialize ChatOpenAI instance for language model<br>llm = ChatOpenAI(openai_api_key=os.environ[&quot;OPENAI_API_KEY&quot;], model=&quot;gpt-3.5-turbo&quot;, temperature=0)<br><br><br>class ResearchAgent:<br>    def __init__(self):<br>        pass<br>    <br>    def format_search(self, query: str) -&gt; str:<br>        # Prepare prompt for the language model to optimize the search query<br>        # Using Few-Shot Prompting to ensure we receive only the optimized query<br>        prompt = (<br>            &quot;You are an expert at optimizing search queries for Google. &quot;<br>            &quot;Your task is to take a given query and return an optimized version of it, making it more likely to yield relevant results. &quot;<br>            &quot;Do not include any explanations or extra text, only the optimized query.\n\n&quot;<br>            &quot;Example:\n&quot;<br>            &quot;Original: best laptop 2023 for programming\n&quot;<br>            &quot;Optimized: top laptops 2023 for coding\n\n&quot;<br>            &quot;Example:\n&quot;<br>            &quot;Original: how to train a puppy not to bite\n&quot;<br>            &quot;Optimized: puppy training tips to prevent biting\n\n&quot;<br>            &quot;Now optimize the following query:\n&quot;<br>            f&quot;Original: {query}\n&quot;<br>            &quot;Optimized:&quot;<br>        )<br>        <br>        # Invoke language model to optimize query<br>        response = llm.invoke(prompt)<br>        return response.content<br>    <br>    def search(self, state: State):<br>        # Initialize TavilySearchResults instance to perform the web search<br>        search = TavilySearchResults(max_results=1)<br>        # Get the latest query from the state and optimize it using the format_search method<br>        optimized_query = self.format_search(state.get(&#39;query&#39;, &quot;&quot;)[-1].content)<br>        # Perform the search using the optimized query<br>        results = search.invoke(optimized_query)<br>        # Return only the content from the research results<br>        return {&quot;research&quot;: [results[0][&quot;content&quot;]]}</pre><h4>Editor Agent</h4><p>The Editor Agent is responsible for evaluating the research provided by the Research Agent. This agent checks if the research content is sufficient for creating a comprehensive and accurate blog post. If the content is insufficient, it suggests new queries to improve the research results.</p><pre>class EditorAgent:<br>    def __init__(self):<br>        pass<br>    <br>    def evaluate_research(self, state: State):<br>        # Combine all queries into a single string<br>        query = &#39;\n&#39;.join(message.content for message in state.get(&quot;query&quot;))<br>        print(f&quot;Query/queries: {query}&quot;)<br>        print(&quot;-&quot;*20)<br>        <br>        # Combine all research content into a single string<br>        research = &#39;\n&#39;.join(message.content for message in state.get(&quot;research&quot;))<br>        print(f&quot;Research Content: {research}&quot;)<br>        print(&quot;-&quot;*20)<br>        <br>        # Get the current iteration count, defaulting to 1 if not set<br>        iteration_count = state.get(&quot;iteration_count&quot;, 1)<br>        <br>        # Ensure iteration_count is always an integer<br>        if iteration_count is None:<br>            iteration_count = 1<br>        <br>        print(f&quot;Iteration n.: {iteration_count}&quot;)<br>        print(&quot;-&quot;*20)<br>        <br>        # Limit to 3 iterations to avoid infinite loops<br>        if iteration_count &gt;= 3:<br>            return {&quot;content_ready&quot;: True}<br>        <br>        # Prepare the prompt for the language model to evaluate the research<br>        prompt = (<br>            &quot;You are an expert editor. Your task is to evaluate the research based on the query. &quot;<br>            &quot;If the information is sufficient to create a comprehensive and accurate blog post, respond with &#39;sufficient&#39;. &quot;<br>            &quot;If the information is not sufficient, respond with &#39;insufficient&#39; and provide a new, creative query suggestion to improve the results. &quot;<br>            &quot;If the research results appear repetitive or not diverse enough, think about a very different kind of question that could yield more varied and relevant information. &quot;<br>            &quot;Consider the depth, relevance, and completeness of the information when making your decision.\n\n&quot;<br>            &quot;Example 1:\n&quot;<br>            &quot;Used queries: What are the benefits of a Mediterranean diet?\n&quot;<br>            &quot;Research: The Mediterranean diet includes fruits, vegetables, whole grains, and healthy fats.\n&quot;<br>            &quot;Evaluation: Insufficient\n&quot;<br>            &quot;New query: Detailed health benefits of a Mediterranean diet\n\n&quot;<br>            &quot;Example 2:\n&quot;<br>            &quot;Used queries: How does solar power work?\n&quot;<br>            &quot;Research: Solar power works by converting sunlight into electricity using photovoltaic cells.\n&quot;<br>            &quot;Evaluation: Sufficient\n\n&quot;<br>            &quot;Example 3:\n&quot;<br>            &quot;Used queries: Effects of climate change on polar bears?\n&quot;<br>            &quot;Research: Climate change is reducing sea ice, affecting polar bear habitats.\n&quot;<br>            &quot;Evaluation: Insufficient\n&quot;<br>            &quot;New query: How are polar bears adapting to the loss of sea ice due to climate change?\n\n&quot;<br>            &quot;Now evaluate the following:\n&quot;<br>            f&quot;Used queries: {query}\n&quot;<br>            f&quot;Research: {research}\n\n&quot;<br>            &quot;Evaluation (sufficient/insufficient):\n&quot;<br>            &quot;New query (if insufficient):&quot;<br>        )<br>        <br>        # Invoke the language model with the prompt<br>        response = llm.invoke(prompt)<br>        evaluation = response.content.strip()<br>        <br>        # Display the evaluation result for debugging purposes<br>        print(f&quot;Eval: {evaluation}&quot;)<br>        print(&quot;-&quot;*20)<br>        <br>        # Check if a new query is suggested in the evaluation<br>        if &quot;new query:&quot; in evaluation.lower():<br>            new_query = evaluation.split(&quot;New query:&quot;, 1)[-1].strip()<br>            return {&quot;query&quot;: [new_query], &quot;iteration_count&quot;: iteration_count + 1}<br>        else:<br>            return {&quot;content_ready&quot;: True}</pre><h4>Writer Agent</h4><p>The Writer Agent is responsible for taking the optimized query and research content provided by the other agents to craft a well-written, engaging, and informative blog post. This agent ensures that the final content is comprehensive and easy to read.</p><pre>class WriterAgent:<br>    def __init__(self):<br>        pass<br>    <br>    def write_blogpost(self, state: State):<br>        # Extract the original query from the state<br>        query = state.get(&quot;query&quot;)[0].content<br>        # Combine all research content into a single string<br>        research = &#39;\n&#39;.join(message.content for message in state.get(&quot;research&quot;))<br>        <br>        # Prepare the prompt for the language model to write the blog post<br>        prompt = (<br>            &quot;You are an expert blog post writer. Your task is to take a given query and context, and write a comprehensive, engaging, and informative short blog post about it. &quot;<br>            &quot;Make sure to include an introduction, main body with detailed information, and a conclusion. Use a friendly and accessible tone, and ensure the content is well-structured and easy to read.\n\n&quot;<br>            f&quot;Query: {query}\n\n&quot;<br>            f&quot;Context:\n{research}\n\n&quot;<br>            &quot;Write a detailed and engaging blog post based on the above query and context.&quot;<br>        )<br>        <br>        # Invoke the language model with the prompt to generate the blog post<br>        response = llm.invoke(prompt)<br>        <br>        # Return the generated content<br>        return {&quot;content&quot;: response.content}</pre><h4>Creating the graph</h4><p>Creating the LangGraph graph is very straightforward and consists of three main functions: `add_node`, `add_edge`, and `set_entry_point. With these main functions, you can first add the nodes to the graph, connect the edges, and finally set the starting point.</p><p>Let’s break down the steps with comments to make it easy to follow.</p><pre>from langgraph.graph import END<br><br># Define nodes: Adding each agent to the graph as a node<br># &quot;search_agent&quot; uses the search method of the ResearchAgent<br># &quot;writer_agent&quot; uses the write_blogpost method of the WriterAgent<br># &quot;editor_agent&quot; uses the evaluate_research method of the EditorAgent<br>graph.add_node(&quot;search_agent&quot;, ResearchAgent().search)<br>graph.add_node(&quot;writer_agent&quot;, WriterAgent().write_blogpost)<br>graph.add_node(&quot;editor_agent&quot;, EditorAgent().evaluate_research)<br><br># Set entry point: The graph starts with the search_agent node<br>graph.set_entry_point(&quot;search_agent&quot;)<br><br># Define edges: Connect the nodes in the order they should be executed<br># After search_agent finishes, editor_agent is triggered<br>graph.add_edge(&quot;search_agent&quot;, &quot;editor_agent&quot;)<br><br># Define conditional edges for the editor agent<br># Depending on the evaluation result, either proceed to writer_agent or go back to search_agent for revision<br>graph.add_conditional_edges(<br>    &quot;editor_agent&quot;,<br>    lambda state: &quot;accept&quot; if state.get(&quot;content_ready&quot;) else &quot;revise&quot;,<br>    {<br>        &quot;accept&quot;: &quot;writer_agent&quot;, # If content is ready, proceed to writer_agent<br>        &quot;revise&quot;: &quot;search_agent&quot; # If content is not ready, go back to search_agent<br>    }<br>)<br><br># Define edge to end the graph once the writer_agent is done<br>graph.add_edge(&quot;writer_agent&quot;, END)<br><br># Compile the graph to finalize its structure<br>graph = graph.compile()</pre><h4>Visualizing the graph</h4><p>To help visualize the structure of our LangGraph, we can use the `IPython.display` module to display the graph. This visualization shows how the agents are connected and how the flow proceeds from start to end, including conditional paths.</p><pre>from IPython.display import Image, display<br><br>display(Image(graph.get_graph().draw_mermaid_png()))</pre><figure><img alt="This image is a flowchart diagram representing the structure of a LangGraph." src="https://cdn-images-1.medium.com/max/135/0*BhgPtjCkkwfTLq8-" /><figcaption>LangGraph Flowchart: Visualizing the Sequence and Conditional Paths of Connected Agents from Start to End</figcaption></figure><h4>Running the graph</h4><p>Now that we’ve created and visualized our graph, it’s time to see it in action. By invoking the graph with an initial query, we can start the multi-agent process and see the results.</p><p>Let’s initiate the process with a sample query, “What are the differences between LangChain and LangGraph?”.</p><pre>blogpost = graph.invoke({&quot;query&quot;:&quot;What are the differences between LangChain and LangGraph?&quot;})</pre><p>After running the graph, you can check the results of some print statements that we put into the editor agent. These will allow you to see what’s happening as the iterations go through. When it stops running, you can run a simple `print(blogpost[‘content’])` to see the final result.</p><pre>print(blogpost[&#39;content&#39;])<br><br>&quot;&quot;&quot;<br>In the world of language models and AI applications, two key tools have been making waves: LangChain and LangGraph. While both are designed to enhance the capabilities of large language models (LLMs), they serve different purposes and offer unique features. Let&#39;s dive into the differences between LangChain and LangGraph to understand how they can benefit developers and users alike.<br><br>LangGraph is a powerful library that focuses on building stateful, multi-actor applications with LLMs. It extends the LangChain Expression Language to enable the coordination of multiple chains or actors across various tasks. This means that developers can create complex applications that involve multiple actors working together, making it ideal for scenarios where collaboration and coordination are essential.<br><br>On the other hand, LangChain is a comprehensive framework that aims to streamline the development, productionization, and deployment of applications powered by LLMs. It acts as a bridge between the raw computational power of LLMs and practical, real-world applications, allowing developers to leverage the full potential of LLMs in their projects. LangChain is particularly useful for developers looking to harness the capabilities of LLMs beyond just language processing, enabling them to create a wide range of AI-powered applications.<br><br>One key difference between LangChain and LangGraph lies in their focus and functionality. While LangGraph is geared towards building multi-actor applications and coordinating tasks across different chains, LangChain is more focused on facilitating the development and deployment of LLM-powered applications. This distinction makes each tool suitable for different use cases and scenarios, depending on the specific requirements of the project.<br><br>In conclusion, both LangChain and LangGraph offer valuable tools and capabilities for developers working with LLMs. Whether you need to build complex multi-actor applications or streamline the deployment of LLM-powered projects, these tools can help you achieve your goals efficiently and effectively. By understanding the differences between LangChain and LangGraph, developers can choose the right tool for their specific needs and unlock the full potential of large language models in their applications.<br>&quot;&quot;&quot;</pre><p>Also, I encourage you guys to check the graph in LangSmith, as it makes everything clearer too. LangSmith provides a great interface for visualizing and debugging LangGraph workflows, which can be really helpful, especially when dealing with complex multi-agent systems.</p><p>Take a peek:</p><figure><img alt="This image is a screenshot of a LangGraph trace viewed in the LangSmith interface." src="https://cdn-images-1.medium.com/max/556/0*6ijp-eEvaZAnuBuu" /><figcaption>LangGraph Trace in LangSmith: Detailed Visualization and Debugging of Multi-Agent Workflows</figcaption></figure><p>LangSmith shows us the conditional logic to ensure the content meets the desired quality, looping between research and editing until the content is ready.</p><p><strong>That’s all folks!</strong> I’m sure this simple tutorial will help you all start building some awesome things with LangGraph.</p><p>You can leverage the basic knowledge we covered here to create whatever you imagine.<strong> Have fun!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d062ce4051c3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/indiciumtech/how-to-build-a-multi-agent-content-development-team-using-langgraph-d062ce4051c3">How to build a multi-agent content development team using LangGraph</a> was originally published in <a href="https://medium.com/indiciumtech">Indicium AI Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is LangGraph and can it help you build LLM Agents?]]></title>
            <link>https://medium.com/indiciumtech/what-is-langgraph-and-can-it-help-you-build-llm-agents-c66b6def0b83?source=rss-75d40deb740f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c66b6def0b83</guid>
            <category><![CDATA[langsmith]]></category>
            <category><![CDATA[langchain-tools]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[langchain-agents]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Josias Hartmann]]></dc:creator>
            <pubDate>Fri, 21 Jun 2024 18:39:46 GMT</pubDate>
            <atom:updated>2024-06-21T18:39:46.976Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3TXtd88hJqu6ZMObQUtVHA.png" /></figure><p>Today, we are going to answer both those questions. Let’s start with the first one, and the second will naturally unfold as we go on.</p><h3>What is LangGraph?</h3><p>I’ll try to be a little less technical than others who have discussed this. We need a light read sometimes, don’t we? Sooo… LangGraph! Simply put, LangGraph is a tool that helps you build smarter applications using large language models (LLMs). Think of it as an extension to another tool called LangChain.</p><p>“What’s that?” you might ask. Well, LangChain is a tool that allows you to create sequences of actions (like a list of steps). LangGraph, on the other hand, lets you add loops to these sequences. This means you can ask your language model to repeatedly decide what to do next, making your application more interactive and capable of handling more complex tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/0*WdADQJXxW2s1cbl5" /></figure><p><strong>Still a bit fuzzy? Let me break it down further.</strong></p><p>Imagine LangChain as a beginner cook following a simple recipe. The newbie goes step-by-step, adding ingredients in a specific order until the dish is complete. They can’t go back and change anything once they’ve moved to the next step.</p><p>LangGraph, on the other hand, is like a master chef who can taste the dish at each step, adjust the seasoning, go back to add more ingredients, and tweak the cooking process as needed. The chef can keep refining the dish, going back and forth between steps, until it’s perfect. This flexibility allows the chef to adapt and improve the dish continuously, just like LangGraph enables continuous decision-making and improvement in building LLM agents.</p><p>One practical and awesome use case is implementing a company chatbot that can loop over a variety of tools. For example, it can filter off-topic questions, schedule meetings by integrating with your calendar system, send follow-up emails and confirmations to potential clients, qualify visitors based on their interactions and responses, and recommend relevant company services based on the conversation. The possibilities are endless.</p><p>In essence, LangGraph is a step up from LangChain. While LangChain does the job, LangGraph will take your projects to a whole new level. Honestly? It’s the tool you didn’t know you needed until you see what it can do.</p><p>Now, let’s dive into a simple example that will clear things up while taking us deeper into LangGraph. We’ll create a simple chatbot that will respond directly to user messages. Although simple, it will serve the purpose to illustrate the core concepts of building with LangGraph.</p><p>Before we get started with the setup, I want to let you know that the code I’ll be showing you was originally written and tested in a Jupyter notebook. If you’d like to download and test it yourself, you can find the notebook <a href="https://github.com/techindicium/tech-blog/blob/main/GenAI/2024-06-14-What-is-LangGraph-and-can-it-help-you-build-LLM-Agents/what-is-langgraph-and-can-it-help-you-build-llm-agents.ipynb">here</a>.</p><h3>Setup</h3><p>First we need to install the packages required.</p><pre>%%capture --no-stderr<br>%pip install -U langgraph langsmith<br><br># Used for this tutorial; not a requirement for LangGraph<br>%pip install -U langchain_openai</pre><p>Next, let’s set the API key for OpenAI.</p><pre>import os<br>import getpass<br><br>os.environ[&quot;OPENAI_API_KEY&quot;] = getpass.getpass(&quot;OpenAI API Key:&quot;)</pre><p>Also, let’s set up our <a href="https://www.langchain.com/langsmith">LangSmith</a> key as it makes it a lot easier to see what’s going on under the hood (optional, but encouraged).</p><pre>os.environ[&quot;LANGSMITH_API_KEY&quot;] = getpass.getpass(&quot;LangSmith API Key:&quot;)<br>os.environ[&quot;LANGCHAIN_TRACING_V2&quot;] = &quot;true&quot;<br>os.environ[&quot;LANGCHAIN_PROJECT&quot;] = &quot;LangGraph Chatbot&quot;</pre><h3>Step 1: Define the State</h3><p>In this step, we define the state structure for our graph by setting up the StateGraph. This structure holds data that can change as the process runs.</p><pre>from typing import Annotated<br>from typing_extensions import TypedDict<br>from langgraph.graph.message import add_messages<br><br>class State(TypedDict):<br>    # The `add_messages` function within the annotation defines<br>    # *how* updates should be merged into the state.<br>    messages: Annotated[list, add_messages]</pre><p>For this example, the state we will track is just a list of messages. Each node will add messages to that list.</p><h3>Step 2: Create the Graph</h3><p>Next, we create a new instance of StateGraph with our State structure.</p><pre>from langgraph.graph import StateGraph<br><br>graph_builder = StateGraph(State)</pre><p>StateGraph is a class that encapsulates a graph structure. It is initialized with a state definition, which serves as a central state object that evolves over time. Nodes within the graph manipulate this state by returning operations that modify its attributes, typically using a key-value store format.</p><h3>Step 3: Define the Nodes</h3><p>In this step, we define one agent called chatbot. This agent is a function that takes the current State as input and returns an updated list of messages. The function uses a Language Model (LLM) to generate responses based on the input messages.</p><pre>from langchain_openai import ChatOpenAI<br><br># Import the necessary chatbot module<br>llm = ChatOpenAI(openai_api_key=os.environ[&quot;OPENAI_API_KEY&quot;],model=&quot;gpt-3.5-turbo&quot;)<br><br># Define the chatbot function incorporating the language model<br>def chatbot(state: State):<br>    return {&quot;messages&quot;: [llm.invoke(state[&quot;messages&quot;])]}</pre><p>Next, we add nodes using the `graph.add_node(name, value)` syntax. Nodes represent units of work, which are typically regular Python functions or <a href="https://python.langchain.com/v0.1/docs/expression_language/">runnables</a>.</p><pre># The first argument is the unique node name<br># The second argument is the function or object that will be called whenever the node is used.<br># Add the chatbot node to the graph<br>graph_builder.add_node(&quot;chatbot&quot;, chatbot)</pre><p>In this case, we’ve added a node named “chatbot” that will be responsible for handling the chatbot’s interactions. The `add_messages` function in our State will append the LLM’s response messages to the existing messages in the state.</p><h3>Step 4: Configure Entry and Exit Points</h3><p>Next, we need to set the <strong>entry point</strong>. This tells our graph where to start its work each time we run it.</p><pre>graph_builder.set_entry_point(&quot;chatbot&quot;)</pre><p>We also need to set a <strong>finish point</strong>. This instructs the graph, “any time this node is run, you can exit”.</p><pre>graph_builder.set_finish_point(&quot;chatbot&quot;)</pre><h3>Step 5: Compile</h3><p>Finally, we’ll compile our graph. This creates a `CompiledGraph` that we can use to invoke our state.</p><pre>graph = graph_builder.compile()</pre><h3>Step 6: Visualize and Run the Chatbot</h3><p>We can visualize the graph using the `get_graph` method and one of the “draw” methods, like `draw_mermaid_png`. The draw methods each require additional dependencies.</p><pre>from IPython.display import Image, display<br><br>display(Image(graph.get_graph().draw_mermaid_png()))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/98/0*n3qcITMBvI_LgW6J" /></figure><h3>Now let’s run the chatbot!</h3><p>The chatbot will continue to run in a loop until you type “quit”, “exit”, or “q”.</p><pre>while True:<br>    user_input = input(&quot;User: &quot;)<br>    # Check if the user wants to quit<br>    if user_input.lower() in [&quot;quit&quot;, &quot;exit&quot;, &quot;q&quot;]:<br>        print(&quot;Goodbye!&quot;)<br>        break<br>    # Stream events from the graph and print the assistant&#39;s response<br>    for event in graph.stream({&quot;messages&quot;: (&quot;user&quot;, user_input)}):<br>        for value in event.values():<br>            print(&quot;Assistant:&quot;, value[&quot;messages&quot;][-1].content)<br>&quot;&quot;&quot;<br>Response:<br>User: what&#39;s langgraph all about?<br>Assistant: Langgraph is a platform that aims to help language learners improve their skills through interactive activities and exercises. It offers a variety of tools such as vocabulary flashcards, grammar exercises, and language games to make learning more engaging and effective. Users can track their progress and set goals to stay motivated in their language learning journey. Langgraph also provides resources and tips to help learners practice and improve their skills outside of the platform.<br>User: q<br>Assistant: Goodbye!<br>&quot;&quot;&quot;</pre><p>As seen above, the chatbot’s responses might not always be accurate due to the limitations of the Language Model (LLM) on specific topics. To improve the chatbot’s accuracy and provide more relevant responses, we can integrate additional tools, which we will explore next.</p><h3>Visualizing the Chatbot’s Execution</h3><p>Also, check what we got from LangSmith when running the current chatbot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*Mu7B3AVfmAAfRJZ-" /></figure><p>Not much flavor, huh, chef? Let’s sprinkle in some MSG to give it that extra kick!</p><h3>Enhance the Chatbot with Tools</h3><p>Hope you are ready because now we will improve our chatbot by integrating it with a web search tool. This will allow the chatbot to fetch and use relevant information from the web to provide more accurate and helpful responses.</p><h3>Step 1: Setting Up the Web Search Tool</h3><p>Before we start, ensure you have the necessary packages installed and API keys set up. We’ll be using the <a href="https://python.langchain.com/v0.1/docs/integrations/tools/tavily_search/">Tavily Search Engine</a>. <strong>It’s super easy to register and they offer a free tier.</strong></p><pre># Prompting for the Tavily API Key and storing it in an environment variable.<br>os.environ[&quot;TAVILY_API_KEY&quot;] = getpass.getpass(&quot;Tavily API Key:&quot;)</pre><p>Let’s create and test the tool that interacts with the Tavily Search API to retrieve search results in JSON format.</p><pre>from langchain_community.tools.tavily_search import TavilySearchResults<br><br># Initializing the search tool with a maximum of 2 results per query<br>tool = TavilySearchResults(max_results=2)<br><br># Storing the tool in a list, which can be expanded with additional tools in the future<br>tools = [tool]<br><br># Invoking the tool with a query to see the type of results it returns<br>tool.invoke(&quot;What&#39;s LangGraph all about?&quot;)<br><br>&quot;&quot;&quot;<br>Response: <br>[{&#39;url&#39;: &#39;https://langchain-ai.github.io/langgraph/tutorials/introduction/&#39;,<br>  &#39;content&#39;: &#39;4. Scalability: Langgraph is designed to handle large-scale language models with billions of parameters, enabling the development of state-of-the-art NLP applications. 5. Open-Source: Langgraph is an open-source project, allowing developers and researchers to collaborate, contribute, and build upon the framework. 6.&#39;},<br> {&#39;url&#39;: &#39;https://langchain-ai.github.io/langgraph/concepts/&#39;,<br>  &#39;content&#39;: &quot;If a node has multiple out-going edges, all of those destination nodes will be executed in parallel as a part of the next superstep. State Management¶ LangGraph introduces two key ideas to state management: state schemas and reducers. The state schema defines the type of the object that is given to each of the graph&#39;s Node&#39;s.&quot;}]<br>&quot;&quot;&quot;</pre><p>The output will be page summaries that our chatbot can use to answer questions.</p><h3>Step 2: Defining our Graph</h3><p>The following steps are similar to our initial example, with the addition of binding tools to our Language Model (LLM). This allows the LLM to use the Tavily Search API to fetch information.</p><pre>from typing import Annotated<br><br>from langchain_openai import ChatOpenAI<br>from typing_extensions import TypedDict<br><br>from langgraph.graph import StateGraph<br>from langgraph.graph.message import add_messages<br><br><br>class State(TypedDict):<br>    messages: Annotated[list, add_messages]<br><br>graph_builder = StateGraph(State)<br><br># Import the necessary chatbot module and bind tools to enhance it<br>llm = ChatOpenAI(openai_api_key=os.environ[&quot;OPENAI_API_KEY&quot;],model=&quot;gpt-3.5-turbo&quot;)<br>llm_with_tools = llm.bind_tools(tools)<br><br><br># Define the chatbot function incorporating the enhanced language model<br>def chatbot_with_tools(state: State):<br>    return {&quot;messages&quot;: [llm_with_tools.invoke(state[&quot;messages&quot;])]}<br><br># Add the enhanced chatbot as a node to the graph<br>graph_builder.add_node(&quot;chatbot_with_tools&quot;, chatbot_with_tools)</pre><p>By integrating the <strong><em>Tavily Search Engine</em></strong>, your chatbot can now fetch relevant information from the web. This means it will provide more accurate and helpful responses to user questions, enhancing the overall user experience with up-to-date online resources.</p><h3>Step 3: Add a tool node to the graph for conditional routing</h3><p>To make our chatbot even more powerful, we will add a tool node to manage tool requests and utilize conditional edges to regulate the flow between tool usage and the main chatbot logic. We will use LangGraph’s prebuilt `ToolNode` and `tools_condition`, which simplifies our setup and avoids the need to build these components from scratch. This is particularly useful for beginners.</p><pre>from langgraph.prebuilt import ToolNode, tools_condition<br><br># Add a node to handle tool usage<br>tool_node = ToolNode(tools=[tool])<br>graph_builder.add_node(&quot;tools&quot;, tool_node)<br><br><br># Add conditional edges to return to the chatbot after tool usage<br>graph_builder.add_conditional_edges(<br>    &quot;chatbot_with_tools&quot;,<br>    tools_condition,<br>)<br><br># Any time a tool is called, we return to the chatbot to decide the next step<br>graph_builder.add_edge(&quot;tools&quot;, &quot;chatbot_with_tools&quot;)<br><br># Set the entry point to the enhanced chatbot node<br>graph_builder.set_entry_point(&quot;chatbot_with_tools&quot;)<br><br># Compile the graph<br>graph = graph_builder.compile()</pre><p>See, with pre-built components, setting up the graph becomes a breeze, letting us dive straight into crafting our chatbot. These handy tools take care of typical patterns and workflows, smoothing the path for newcomers. They’re like having a ready-made spice mix, making life easier as you navigate through LangGraph.</p><h3>Step 4: Visualize and Run the Graph</h3><p>Once again, let’s visualize the graph using the `get_graph` method.</p><pre>from IPython.display import Image, display<br><br>display(Image(graph.get_graph().draw_mermaid_png()))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/203/0*iGBjLhqFxO25Nz1w" /></figure><p><strong><em>NOW WE ARE COOKING!</em></strong></p><h3>Let’s run the new and improved chatbot!</h3><p>The chatbot will continue to run in a loop until you type “quit”, “exit”, or “q”.</p><pre>from langchain_core.messages import BaseMessage<br><br>while True:<br>    user_input = input(&quot;User: &quot;)<br>    if user_input.lower() in [&quot;quit&quot;, &quot;exit&quot;, &quot;q&quot;]:<br>        print(&quot;Goodbye!&quot;)<br>        break<br>    for event in graph.stream({&quot;messages&quot;: [(&quot;user&quot;, user_input)]}):<br>        for value in event.values():<br>            if isinstance(value[&quot;messages&quot;][-1], BaseMessage):<br>                print(&quot;Assistant:&quot;, value[&quot;messages&quot;][-1].content)<br><br>&quot;&quot;&quot;<br>Response:<br>User: What&#39;s LangGraph all about?<br>Assistant: [{&quot;url&quot;: &quot;https://python.langchain.com/v0.1/docs/langgraph/&quot;, &quot;content&quot;: &quot;\ud83e\udd9c\ud83d\udd78\ufe0fLangGraph. \u26a1 Building language agents as graphs \u26a1. Overview . LangGraph is a library (...)&quot;}, {&quot;url&quot;: &quot;https://blog.langchain.dev/langgraph-multi-agent-workflows/&quot;, &quot;content&quot;: &quot;As a part of the launch, we highlighted two simple runtimes:(...)&quot;}]<br>Assistant: LangGraph is a library for building stateful, multi-actor applications with LLMs. It allows you to coordinate and checkpoint multiple chains (or actors) across cyclic computational steps using regular Python functions (or JS). LangGraph is inspired by Pregel and Apache Beam, and the public interface draws inspiration from NetworkX.<br>For more information, you can visit the [LangGraph documentation](https://python.langchain.com/v0.1/docs/langgraph/).<br>Additionally, LangGraph enables the creation of LLM workflows containing cycles, which are essential for most agent runtimes. It is available in both Python and JS and is integrated into the LangChain ecosystem, offering various advantages and integrations within the LangChain platform.<br>To explore more about LangGraph and its applications, you can refer to this [article on multi-agent workflows with LangGraph](https://blog.langchain.dev/langgraph-multi-agent-workflows/).<br>User: q<br>Goodbye!<br>&quot;&quot;&quot;</pre><p>Awesome! By adding a web search tool into our chatbot loop, we’ve taken our responses from good to waaaaay better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/0*DuzmBQIwB32myCFo" /></figure><p><strong>Wrap-up:</strong> With just a simple loop, we’ve spiced up our chatbot by fetching updated information whenever necessary. LangGraph enables fine-tuning, making your applications dynamic and responsive.</p><p>Thanks for joining me on this short tutorial! Putting it together taught me a lot, and I hope you found it as fascinating as I did. As you delve into your own projects, remember to give LangGraph a try — it’s packed with some seriously cool features!</p><p>Stay tuned for future posts where we’ll explore more advanced topics and customizations with LangGraph!</p><p><strong>Happy coding!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c66b6def0b83" width="1" height="1" alt=""><hr><p><a href="https://medium.com/indiciumtech/what-is-langgraph-and-can-it-help-you-build-llm-agents-c66b6def0b83">What is LangGraph and can it help you build LLM Agents?</a> was originally published in <a href="https://medium.com/indiciumtech">Indicium AI Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>