- January 9, 2025
- Posted by: Krishnan Srinivasan
- Category: AI/ML
Introduction
In Part 1 and Part 2 of the Agentic AI series, we explored Logistics optimization with CrewAI and a Travel Planner with Autogen respectively. In Part 3, we will explore another key Agentic AI framework – LangGraph.
LangGraph, a graph-based workflow system built on LangChain, enables the seamless integration of stateful logic and cutting-edge language models like OpenAI’s GPT series.
LangGraph integrates natural language processing (NLP) capabilities with graph databases, allowing users to intuitively interact with data, uncover patterns, and derive meaningful insights. It structures data as a graph of interconnected nodes and edges, where Nodes represent the what (entities or items) and Edges represent the how (relationships or connections).
As businesses increasingly turn to AI for automation and insights, LangGraph emerges as a pivotal framework, providing robust support for designing intelligent workflows.
This blog explores how Agentic AI, coupled with LangGraph, can address real-world challenges such as competitor analysis. Specifically, we will demonstrate its application in the retail sector, focusing on a clothing store’s need to identify competitors, understand their strategies, and gain actionable insights.
Objective: Competitor Analysis for a Fashion Store Using LangGraph
To develop an Agentic AI pipeline using LangGraph that enables businesses to monitor and analyze nearby competitors in high-traffic areas. The solution will provide real-time insights on competitor footfall, peak hours, and market trends, empowering the fashion store owners, marketing teams, and analysts to optimize strategies, improve customer engagement, and make data-driven decisions for business growth and market positioning.
Stepwise Execution:
Step 1: Import API Keys
The first step involves importing necessary API Keys. -OPEN AI and TAVILY API keys and configurations, which are required for secure, efficient LLM execution and web search respectively.
Step 2: Import LangGraph Components
The import include stategraph, messages etc from langraph.graph for graph-based logic and to manage the states in langraph, ChatOpenAI for referencing the large language, ToolNode for a node that will be responsible for a search tool that we will build and Tavily for performing the search to conduct competitor analysis. The Tavily search API performs research tasks by scraping, filtering, and aggregating data across the internwt. We will leverage these results for our competitor analysis.
Step 3: Initialize the ChatOpenAI Model
We setup theLLM here. The ChatOpenAI instance is initialized with the model ‘gpt-4o’ and a temperature of 0, ensuring deterministic responses for consistent analysis.
Step 4: Define a Function to Determine Workflow Continuation
It takes in message state that contains the list of messages that will be stored throughout the flow for tracking purposes. We will then access the message the state currently contains. If the last message was a tool call we will return tools, which is the id for the node responsible for the search. If not ,it will return END, signifying the end of execution of the graph. Basically, it returns ‘tools’ if further processing is needed; otherwise, END.
Step 5: Define the State Graph for Competitor Analysis
This function will invoke the LLM that we setup earlier on those messages. call_model, takes a MessagesState object, retrieves the current list of messages, and sends them to an LLM (language model) for a response. The LLM will now hold all the context from the messages and will return a dictionary with those messages, appending new response to existing messages.
Step 6: Initialize the State graph
The command initializes a state graph using MessagesState as its core, creating a workflow structure where states and transitions can be managed. It sets up the foundation for handling message-based interactions or events within the graph.
We will be adding two nodes: one for performing the competitor analysis using TavilySearchResults, and another as a terminal node signaling the end of the workflow.
Step 7: Add the Agent node
Here we add the agent node and associate it with our call_model function
Step 8: Setup Search Tool
We setup the Tavily search to perfom the web search for competitor analysis
Edges define transitions between the states in the graph: from START to ‘tools’ for analysis, and from ‘tools’ to ‘END’ to terminate the process.
Step 9: Setup the Tools list
We setup the tools list and assign it to the tool_node.
Step-10: Create the graph and add this node
We add the tool node to the graph, establishing the ‘tools’ node as part of the graph’s structure.
Step-11: Add edges
We set the start of the execution flow to the agent in the first command
We then add a conditional edge between the agent and the should_continue function which determines whether it should perform a search or return a result.
A direct edge is then added between the tools and the agent so that after the tool executes the search, it returns it to the agent which compiles that as a response to the user
Step-12: Compile the graph
The graph is compiled. This ensures that the graph’s nodes, edges, and associated logic are validated, streamlined, and prepared for efficient execution.
Step 13: Visualize the Graph
This diagram represents LangGraph’s architecture, showcasing the process flow.
The graph is visualized to provide a clear representation of the workflow structure, which is useful for debugging or presentations. It executes and draws a mermaid graph as PNG using provided syntax. The draw_mermaid_png() renders the graph in a png format.
Step 14: Execute the Graph and view the results
output = graph_compiled.invoke({‘messages’: [ (‘user’, ‘generate a detailed report on nearby clothing store competitors. Use the search tool understand data on competitors, including store footfall and busiest times, giving actionable insights to enhance business strategies for Intended Beneficiaries . The intended beneficiaries are – Business Owners and Managers, Marketing and Strategy Teams, Real Estate and Location Analysts, Investors and Market Analysts.’)]})
We pass the custom user message and run the graph. It runs the graph, collects the final state, and prints the results of the competitor analysis task. Our goal is to obtain insights on the clothing store’s competitors so the beneficiaries are able to strategize. We accordingly draft the user message. An extract of the result is in the screen shot below.
Step 15: Visualize the results with Markdown
We now see a neatly formatted report on competitor analysis. A screenshot of the markdown output(s) is given below.
As seen above, the report provides a well-structured and comprehensive analysis along with actionable insights. The use case illustrates how LangGraph’s state-driven approach can address competitor analysis challenges in the retail sector by structuring tasks and leveraging advanced AI models.
With the LangGraph framework, businesses can uncover actionable insights such as pricing strategies and market positioning. As the adoption of Agentic AI accelerates, tools like LangGraph will play a central role in shaping the future of intelligent automation, enabling businesses to thrive in a competitive landscape.
We provide a comprehensive suite of services in the data and AI domain, tailored to empower your business. Do reach out to us for your development needs.