DEV Community

Cover image for Building Intelligent Agents with LangChain and OpenAI: A Developer's Guide
es404020
es404020

Posted on

3

Building Intelligent Agents with LangChain and OpenAI: A Developer's Guide

As artificial intelligence advances, developers are exploring ways to integrate intelligence into everyday workflows. One such approach involves building agents capable of executing tasks autonomously, combining reasoning with action. In this article, we’ll explore how to create intelligent agents using LangChain, OpenAI’s GPT-4, and LangChain’s experimental tools. These agents will be able to execute Python code, interact with CSV files, and answer complex queries. Let’s dive in!


Why LangChain?

LangChain is a powerful framework for building applications that leverage language models. It’s particularly useful for creating modular and reusable components, such as agents, that can:

  • Execute Python code.

  • Analyze and interact with data files.

  • Perform reasoning and decision-making tasks using tools.

By combining LangChain’s capabilities with OpenAI’s GPT-4, we can create agents tailored to specific use cases, like data analysis, debugging, and more.


Getting Started

Before we dive into the code, ensure your environment is set up with the necessary tools. Here’s what you’ll need:

  • Install Python libraries:
pip install langchain langchain-openai python-dotenv
Enter fullscreen mode Exit fullscreen mode
  • Create a .env file to securely store your OpenAI API key:
OPENAI_API_KEY=your_api_key_here
Enter fullscreen mode Exit fullscreen mode

Building the Python Execution Agent

One of the key capabilities of our agent is executing Python code. This is achieved using LangChain’s PythonREPLTool. Let’s start by defining the agent.

Instruction Design

The agent operates based on a set of instructions. Here’s the prompt we’ll use:

instruction = """
You are an agent designed to write and execute Python code to answer questions.
You have access to Python REPL, which you can use to execute Python code.
If you get an error, debug your code and try again.
Only use the output of your code to answer the question.
If you cannot write code to answer the question, return 'I don't know' as the answer.
Enter fullscreen mode Exit fullscreen mode

Setting Up the Agent

We’ll use LangChain’s REACT framework to build this agent:

from langchain import hub
from langchain_openai import ChatOpenAI
from langchain_experimental.tools import PythonREPLTool
from langchain.agents import create_react_agent, AgentExecutor

base_prompt = hub.pull("langchain-ai/react-agent-template")
prompt = base_prompt.partial(instructions=instruction)

tools = [PythonREPLTool()]
python_agent = create_react_agent(
    prompt=prompt,
    llm=ChatOpenAI(temperature=0, model="gpt-4-turbo"),
    tools=tools,
)
python_executor = AgentExecutor(agent=python_agent, tools=tools, verbose=True)

Enter fullscreen mode Exit fullscreen mode

This agent can now execute Python code and return the results.


Enhancing the Agent with CSV Analysis

Data analysis is a common use case for AI agents. By integrating LangChain’s create_csv_agent, we can enable our agent to query and process data from CSV files.

Setting Up the CSV Agent

Here’s how to add CSV capabilities to the agent:


from langchain_experimental.agents.agent_toolkits import create_csv_agent

csv_agent = create_csv_agent(
    llm=ChatOpenAI(temperature=0, model="gpt-4-turbo"),
    path="episode-info.csv",
    verbose=True,
    allow_dangerous_code=True,
)

Enter fullscreen mode Exit fullscreen mode

This agent can now answer questions about the contents of episode-info.csv, such as:

  • How many rows and columns does the file have?

  • What season has the most episodes?


Combining Tools into a Unified Agent

To create a versatile agent, we’ll combine the Python execution and CSV analysis capabilities into a single entity. This allows the agent to seamlessly switch between tools based on the task.

Defining the Unified Agent

from langchain.agents import Tool

def python_executor_wrapper(prompt: str):
    python_executor.invoke({"input": prompt})

tools = [
    Tool(
        name="Python Agent",
        func=python_executor_wrapper,
        description="""
        Useful for transforming natural language to Python code and executing it.
        DOES NOT ACCEPT CODE AS INPUT.
        """
    ),
    Tool(
        name="CSV Agent",
        func=csv_agent.invoke,
        description="""
        Useful for answering questions about episode-info.csv by running pandas calculations.
        """
    ),
]

grant_agent = create_react_agent(
    prompt=base_prompt.partial(instructions=""),
    llm=ChatOpenAI(temperature=0, model="gpt-4-turbo"),
    tools=tools,
)
grant_agent_executor = AgentExecutor(agent=grant_agent, tools=tools, verbose=True)



Enter fullscreen mode Exit fullscreen mode

This combined agent is now capable of answering questions about both Python logic and CSV data analysis.


Practical Example: Analyzing TV Show Episodes

Let’s see the unified agent in action by querying episode-info.csv.

print(
    grant_agent_executor.invoke({
        "input": "What season has the most episodes?"
    })
)
Enter fullscreen mode Exit fullscreen mode

The agent will analyze the CSV file and return the season with the highest episode count, leveraging pandas under the hood.


Next Steps

  • Experiment with additional tools and datasets.

  • Explore LangChain’s documentation to build even more powerful agents.

LangChain opens the door to creating highly customized, intelligent agents that can simplify complex workflows. With tools like the Python REPL and CSV agent, the possibilities are endless—from automating data analysis to debugging code and beyond. Start building your intelligent agent today!

Billboard image

Synthetic monitoring. Built for developers.

Join Vercel, Render, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay