Zero Labs
Industry News / AI

Building an OCR ReAct Agent from Scratch with LangGraph and Gemini

Source · Towards AI By Kader Miyanyedi

From the publisher’s feed, collected in the ZeroLabs newsroom.

Hello everyone! Over the past few years, AI and LLMs have improved rapidly and the concept of agents has become a part of our lives. In this article, we will explore how agents work and learn how to build our own agents from scratch using LangGraph.In this article, we will cover the following topics:What is LangGraph?What are LangGraph components? (Such as state, node and more..)Let’s write our first graph applicationWhat is the ReAct?What are the Tools?What is the OCR?Let’s write our OCR supported ReAct Agent✨ What is LangGraph?LanGraph is an open source framework developed by the LangChain team and announced in 2024. It is built around LLMs and helps developers create agentic workflows. With LangGraph, we can build agents that can think, make decisions and use tools when needed.✨ What are LangGraph components?We need 5 core components to build our own agent with LangGraph.StateYou can think of the state as a notebook. During the day, we write down notes, plans and important information in this notebook. An agent stores the information that it learnt in previous steps inside the state. In the next step, it decides how to procceed based on this information.You can see a simple state structure bellow:from typing import TypedDict, Listclass AgentState(TypedDict): messages: list[str]TypedDict allows us to define the structure of a dictionary by specifying its keys and the types of their values.NodeA node is a single task that an agent performs. Each task is clearly defined and completed by the agent. For example, when we order a coffee, taking the order, making the coffee and delivering it are separate steps. In LangGraph, each steps called a node. The agents runs these nodes one by one to complete the procces.Bellow you can see an example node definition. After each step is completed, the state is updated and the agent continues to the new steps using this updated state. This way, the agent to access outputs from previous steps and perform actions based on them.def add_message_node(state: AgentState) -> AgentState: state["messages"] = state["messages"] + "Hello from this node!" return stateEdge & Conditional EdgesAn edge represents the connection between nodes. You can think of it as a a path or part of a workflow. It determines which steps should run after a node is completed.If we think about a cooking recipe we know that after cutting the onions we should put them in the pan. Similarly, agents know what to do next after a task is completed using this connections.A conditional edge determines which step should run next based on the current state after a task is completed. For example, in a cooking recipe, we add the other ingredients when the onions are browned enough. Similarly an agent looks at the current information and selects the next node using conditional edges.GraphA graph is a structure that shows how different tasks are connected to each other. It acts like a roadmap for agent, showing the order in which steps should be executed.For example, if we think about a subway map each station is a node, the lines between stations are edges. The connections show which station comes next. The same logic applies in LangGraph, each node represents a task and edges determine the order and conditions for these tasks. The agent moves through this graph step by step to reach its goal.You can see a simple graph example bellow:from langgraph.graph import StateGraphgraph = StateGraph(AgentState)graph.add_node("start", start_node)graph.add_node("end", end_node)graph.add_edge("start", "end")✨ Let’s write our first graph applicationNow that we have learned the core components, we can write our first graph structure using this informations. Even though this example doesn’t use LLm directly, it is important to understand how the structure and flow work in LangGraph.from typing import TypedDictfrom langgraph.graph import StateGraph, END, STARTclass AgentState(TypedDict): number: int result: int | Nonedef get_number(state: AgentState): state["number"] = int(input("Enter a number: ")) return statedef square_number(state: AgentState): state["result"] = state["number"] ** 2 print(f"Even number detected. Result: {state['result']}") return statedef cube_number(state: AgentState): state["result"] = state["number"] ** 3 print(f"Odd number detected. Result: {state['result']}") return statedef should_continue(state: AgentState): if state["number"] % 2 == 0: return "even" return "odd"graph = StateGraph(AgentState)graph.add_node("get_number", get_number)graph.add_node("square", square_number)graph.add_node("cube", cube_number)graph.add_conditional_edges( "get_number", should_continue, { "even": "square", "odd": "cube", },)graph.add_edge(START, "get_number")graph.add_edge("square", END)graph.add_edge("cube", END)app = graph.compile()app.invoke({"number": 0, "result": None})In this example we define a graph structure that takes a number from user and calculate its square if it’s even or its cuve if it’s odd. Let’s examine each step:We need to keep number we get from the user and the result of calculated from it. That’s why we define an AgentState to store this informations.When creating an graph, we provide this state to the StateGraph, allowing the agent to share this information during the workflow.Getting a number, calculating its square and calculating its cube are all tasks and we define a node for each of these tasks. Then we add these nodes to our graph using add_node.We use a conditional edge to decide whether to square or cube a number. First, we specify the node to check after get_number. The should_continue function performs the check. We pass it as the second parameter, and the third parameter is a dictionary that maps the function’s result to the next node. The key is the function’s output, and the value is the next node for the agent to execute.Our application needs a start and an end point. LangGraph provides two special nodes for this purpose: START and END. Using these nodes, we can clearly define where the graph begins and where it finishes.After creating the graph and defining all nodes, edges, and conditions, we need to make the graph executable. To do this, we use the compile method. The compile method validates the entire graph structure and turns it into a runnable application. After this step, the graph can no longer be modified, it can only be executed. If we want to make changes, we need to update the code and compile the graph again.We use the invoke method to run our applications. The same method is also used to call an LLM and it triggers a model call. In LangGraph invoke method start agent workflow.We can also define start and end points using set_entry_point and set_finish_point instead of the START and END nodes. These methods are ideal for simple graphs with a single start and end point. However, when more flexible workflows or multiple end points are needed, using the special START and END nodes is a better approach.When we run our application, we get the following results:Visualizing the Graph (IPython)We can easily visualize the graph we create in LangGraph using an IPython or Jupyter Notebook environment. This allows us to clearly see nodes, edges, and conditional flows. After compiling the graph, we can use the following code to render the structure.After compiling the graph, we can use the following code to draw the structure:from IPython.display import Image, displaydisplay(Image(app.get_graph().draw_mermaid_png()))✨ What is the ReAct (Reasoning and Acting)?ReAct was introduced in a 2022 paper on ArXiv. It is a prompt engineering method that shows how agents can work.This approach lets a language model combine thinking and actions. Unlike traditional methods, the model does not only give the final answer. It looks at the problem step by step and uses tools when needed. Based on what it finds, it decides the next step.Below, you can see how a language model behaves using the ReAct approach. Before ReAct, models usually tried to answer questions in a single step, relying only on what they learned during training. This often led to outdated, incorrect, or invalid answers.Before the ReAct approach, different solutions were tried. For example, if only reasoning was added, the model could think step by step but was still limited to its training data. In action focused approaches, the model could access external resources, but it had no thinking process to decide why or what to look for. As a result, it struggled to turn the collected information into meaningful and consistent answers.With ReAct, the model first identifies what it doesn’t know. Then it thinks about how to fill the gap and performs the appropriate action, such as calling a tool. It evaluates the results and repeats this process if needed. This loop allows the model to reach correct and sufficient information, producing more reliable results and reducing hallucinations. Also, making the reasoning process visible helps us understand the model’s logic and spot errors.ReAct works as a 3-step loop:Thought: The model analyzes the current state and decides what to do next.Action: The model uses a tool, such as performing a web search or querying a database.Observation: The model evaluates the result from the action step. If the information is enough, it generates an answer. If not, it goes back to the Thought step. This loop continues until the problem is solved.✨ What are the Tools?Throughout this article, we have talked about tools. But what exactly are tools? As we mentioned, models are limited by their training data, so their capabilities are restricted. However, we can give models extra powers by allowing them to access real-world data or applications to get new information. The code we write to enable this is what we call a tool.from langchain.tools import tool@tooldef add_numbers(number1: int, number2: int) -> int: """ Adds two numbers. Use this tool when the user wants to perform an addition. Args: number1: The first number to add number2: The second number to add Returns: The sum of the two numbers """ return number1 + number2We use the tool decorator from langchain when we want to define a tool. It converts our functions into tools that the model can understand and call.Note: In different versions of LangChain, the import path for tool may change. If it is under langchain_core, you should import it like this:from langchain_core.tools import toolWhen defining a tool, there are a few key things to remember. These rules are not specific to any library. Even if you use a different library, like HuggingFace SmolAgents instead of LangGraph, you still need to follow them:Docstring: Always add a docstring to explain what the tool does and when it should be used. The model looks at these explanations when deciding which tool to call. Writing a clear and simple docstring helps the model choose the right tool.Argument and Return Types: Define the argument types and return type for the tool. This tells the model what inputs it should provide and what kind of output to expect. Without these definitions, the model may send data in the wrong format or misinterpret the results.✨ What is the OCR?Have you ever had to type a book by hand into a computer and spent hours doing it? Or have you wanted to edit an old document but realized it was only available as a PDF? OCR is a technology that helps in exactly these situations.OCR (Optical Character Recognition) is a technology that reads text from images and converts it into a format that computers can understand. Just like we look at a page and read the letters, OCR “sees” the characters in an image and turns them into digital text.The OCR process consists of three main steps:Pre-processing: The image quality is improved, noise is reduced, and the text becomes clearer. At this stage, the image is usually converted to a black-and-white (binary) format so the text can be separated from the background more easily.Recognition: The software analyzes the characters one by one and matches them with known letters and numbers.Post-processing: The recognized text is validated, errors are corrected, and the final output is generated in the desired format.✨Let’s write our OCR supported ReAct AgentNow that we have learned all the required basics, we can build our OCR-supported ReAct agent. Together, we will create an agent that extracts information from invoice images, saves the data to Excel, and answers questions about the invoices. While building this agent, we will use the Gemini 2.5 model.There are many models trained specifically for OCR tasks (for example, DeepSeek-OCR). You can find these models on platforms like HuggingFace or GitHub. I chose the Gemini model to keep this blog simple. However, for a production-ready application, using models specialized for OCR instead of Gemini would be a better choice in terms of both performance and cost.Define a Statefrom typing import Annotated, TypedDictfrom langchain_core.messages import AnyMessagefrom langgraph.graph.message import add_messagesclass AgentState(TypedDict): """State container for the ReAct agent. Attributes: messages: Conversation history with automatic message merging. Uses add_messages reducer to handle message updates. """ messages: Annotated[list[AnyMessage], add_messages]We mentioned earlier that we define a state so the agent can know what it has done in previous steps. But how do tools like ChatGPT or Gemini remember your past conversations?Actually LLMs can’t remember the past. Every request starts from scratch. To manage a conversation without losing context, the conversation history is sent to the model again with each new message. For the same reason, our agents also need to store the conversation history and pass it to the model at every step. This is where 3 main message types come into play:Human Message: Messages sent by the user, such as “What is the weather today?” or “Tell me a joke.”System Message: Instructions that define how the model should behave. For example, “You are a helpful assistant” or “Keep your answers short and clear.”AI Message: Responses generated by the model. The answers you receive from the agent fall into this category.The state can store all three message types. For this reason, we use AnyMessage in the type definition, which allows us to keep Human, System, and AI messages in the same list. When updating the state, we must not lose the previous messages. Instead, we should preserve the existing data and add new updates on top of it.To achieve this, we can write code like the following:state["messages"] = state["messages"] + "Hello world!"With this approach, we can update the state without losing previous data. However, it may cause a lot of code repetition and increase the risk of errors. For this reason, we use a reducer called add_messages to update the state safely.A reducer is a function that defines how old and new values should be merged when the state is updated. This way, we don’t need to manually write code like state["messages"] = state["messages"] + [new_message]LangGraph automatically handles the following:Keeps the existing messagesAppends new messages to the end of the listUpdates messages with the same ID instead of duplicating themMaintains the correct message orderDefine a ToolAfter analyzing an invoice image, we want to save the extracted information to an Excel file. Let’s create a tool to do this.@tooldef save_invoice_to_excel(invoice_data: dict[str, Any]) -> str: """Save analyzed invoice data to an Excel file. Args: invoice_data: Invoice dictionary with the following structure: { "vendor": "Company name (e.g., Migros)", "date": "YYYY-MM-DD", "items": [{"name": "Item", "quantity": 1, "unit_price": 10.0, "total": 10.0}], "subtotal": 10.0, "tax": 1.8, "total": 11.8, "currency": "TRY" } Returns: Confirmation message with saved file path. """ data = invoice_data # Create or load workbook if EXCEL_FILE.exists(): wb = load_workbook(EXCEL_FILE) ws = wb.active else: wb = Workbook() ws = wb.active ws.title = "Invoices" # Add headers headers = ["ID","Date Added","Vendor", "Invoice Date","Items","Subtotal", "Tax", "Total","Currency" ] ws.append(headers) next_id = ws.max_row items_str = "" if data.get("items"): items_str = "; ".join( f"{item.get('name', 'N/A')} x{item.get('quantity', 1)}" for item in data["items"] ) # Add row row = [next_id,datetime.now().strftime("%Y-%m-%d %H:%M"), data.get("vendor", "N/A"),data.get("date", "N/A"), items_str,data.get("subtotal"),data.get("tax"), data.get("total"),data.get("currency", "N/A"), ] ws.append(row) # Auto-adjust column widths for column in ws.columns: max_length = 0 column_letter = column[0].column_letter for cell in column: if cell.value: max_length = max(max_length, len(str(cell.value))) ws.column_dimensions[column_letter].width = min(max_length + 2, 50) wb.save(EXCEL_FILE) return f"Invoice saved to {EXCEL_FILE.absolute()} (ID: {next_id})"To be able to answer questions about the invoices we saved, let’s create another tool that reads data from the Excel file.@tooldef read_invoices_from_excel() -> str: """Read all invoices from the Excel file. Use this tool to retrieve previously saved invoice data for answering questions about past invoices. Returns: JSON string containing all invoice records. """ if not EXCEL_FILE.exists(): return json.dumps({"error": "No invoices file found", "invoices": []}) wb = load_workbook(EXCEL_FILE) ws = wb.active rows = list(ws.iter_rows(values_only=True)) if len(rows) return json.dumps({"message": "No invoices recorded yet", "invoices": []}) headers = rows[0] invoices = [] for row in rows[1:]: invoice = dict(zip(headers, row)) invoices.append(invoice) return json.dumps({"count": len(invoices), "invoices": invoices}, indent=2)Define a NodeFirst, let’s define a node for our tools. A node is a point in the graph that performs a specific task. To run our tools, we will use ToolNode, which is already available in LangGraph.from langgraph.prebuilt import ToolNode# We provide our tools as a list.all_tools = [save_invoice_to_excel, read_invoices_from_excel]# ToolNode automatically handles tool calls.tool_node = ToolNode(all_tools)ToolNode automatically understands which tool the agent wants to call and runs it. If you want to control how the tools are called, you can create your own custom ToolNode using the following code snippet:all_tools = [save_invoice_to_excel, read_invoices_from_excel]tools_by_name = {tool.name: tool for tool in all_tools}def tool_node(state: AgentState): messages = state["messages"] last_message = messages[-1] # Son mesajda tool çağrısı var mı kontrol ediyoruz. if hasattr(last_message, "tool_calls") and last_message.tool_calls: tool_call = last_message.tool_calls[0] # We find the tool and execute it. tool = tools_by_name[tool_call["name"]] tool_result = tool.invoke(tool_call["args"]) # We add the result as a ToolMessage. tool_message = ToolMessage( content=result, tool_call_id=tool_call["id"] ) return {"messages": [tool_message]} return {"messages": []}Next, let’s define a node that will call our LLM model. This node will handle sending prompts to the model and receiving its responses.model = ChatGoogleGenerativeAI( model="gemini-2.5-flash", temperature=0,)model = model.bind_tools(all_tools)def call_model(state: AgentState) -> dict: """Invoke the LLM with the current conversation state. This node sends the conversation history to Gemini and receives a response that may include tool calls. Args: state: Current agent state containing message history. Returns: Dict with 'messages' key containing the AI response. """ messages = [SystemMessage(content=SYSTEM_PROMPT)] + state["messages"] response = model.invoke(messages) return {"messages": [response]}First, we define our model. Then, we connect the tools we wrote to the model using the bind_tools() method. This creates a bridge between the model and the tools. It is an important step so the model knows which tools are available and can run them.The call_model function is the agent’s decision-making center. Each time this node is called, it does the following:Adds a SystemMessage to tell the model its role and behavior rules.Adds all conversation history from the state so the model knows everything that has been discussed.Calls the model. Based on the question, the model either calls a tool or responds using its own knowledge.Finally, we define a node called should_continue, which decides what the agent should do next. This node determines whether the agent should give the final answer to the user or call a tool.def should_continue(state: AgentState) -> Literal["tools", "end"]: """Determine whether to continue with tool execution or end.""" last_message = state["messages"][-1] if isinstance(last_message, AIMessage) and last_message.tool_calls: return "tools" return "end"Now that we have created all the pieces, we can write our graph.from langgraph.graph import END, START, StateGraphfrom langgraph.graph.state import CompiledStateGraphdef create_agent() -> CompiledStateGraph: graph = StateGraph(AgentState) # We add the tool and model nodes to the graph. graph.add_node("model", call_model) graph.add_node("tools", tool_node) # Let’s define our starting point. graph.add_edge(START, "model") # Let’s use a conditional edge to decide whether the model # should call a tool or return a response to the user. graph.add_conditional_edges( "model", should_continue, { "tools": "tools", "end": END, }, ) graph.add_edge("tools", "model") return graph.compile()✨Test Time!agent = create_agent() image_data, mime_type = _load_image_as_base64(image_path) message = "Analyze this invoice and save it to Excel." message = HumanMessage( content=[ {"type": "text", "text": query}, { "type": "image_url", "image_url": {"url": f"data:{mime_type};base64,{image_data}"}, }, ] ) result = agent.invoke({"messages": [message]}) print(result["messages"][-1].content)LLMs cannot process files directly, so if we ask our model to analyze the invoice.png file, it won’t be able to do so.For this reason, we convert our images to base64 format and provide them to the model for analyzing the content. The model then interprets the image using the text-based data.There are models that support OCR or have image processing capabilities, but in this article, we use the Gemini 2.5-flash model. This is why the image must be converted to base64 format.LLM messages need to follow a defined format. Merging the user query and the image into one text is not recommended. Instead, send them as separate parts of the same message, as the model expects. This way, the model can understand the question and read the image correctly.When we run our agent on the invoice example above, we get the following output:In this article, we learned how to build an OCR-supported agent from scratch. Even if you use different libraries, the core concepts remain largely the same. The full source code is available on GitHub. I hope you found this tutorial both enjoyable and useful. See you in the next post! ^^If you want to build production-ready OCR-supported agents, you can check out the Upsonic project. Upsonic is an open-source project that provides agents with Safety Engine and OCR capabilities.✨ Resources[1] https://ai.google.dev/gemini-api/docs/langgraph-example[2] https://docs.langchain.com/oss/python/langchain/agents[3] https://www.ibm.com/think/topics/optical-character-recognition[4] https://github.com/iamvaibhavmehra/LangGraph-Course-freeCodeCampBuilding an OCR ReAct Agent from Scratch with LangGraph and Gemini was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.