Learn how to create your first AI agent using Python, LangChain, and LangGraph. This step-by-step guide will walk you through environment setup, API integration, tool creation, and memory incorporation for an intelligent assistant tailored to a fruit store example.
Prerequisites
To successfully follow this tutorial, ensure you have the following:
prerequisites
- Basic understanding of Python programming.
- OpenAI API key for GPT models.
- A functional Python environment (e.g., virtual environment or Jupyter Notebook).
- Libraries installed: langchain, langgraph, python-dotenv, openai.
Step 1: Setting Up the Environment
We'll start by creating the necessary programming environment.
steps
Initialize a virtual environment:
bashpython -m venv env source env/bin/activate # On Windows use `env\Scripts\activate`Install the required libraries:
bashpip install langchain langgraph python-dotenv openaiCreate critical files:
.envfor storing your API key.main.ipynbfor writing and executing your code.
Step 2: Load Environment Variables
To load your API keys securely, set up and load environment variables.
steps
Create a
.envfile and insert your API key:OPENAI_API_KEY=<your_key_here>Load these variables using
dotenvin Python:pythonfrom dotenv import load_dotenv import os load_dotenv() api_key = os.getenv('OPENAI_API_KEY') print(api_key) # Verify the key (avoid printing in production)Ensure sensitive keys are never exposed in production code.
Step 3: Import and Initialize Libraries
Import the necessary libraries and confirm dependencies are correctly installed.
steps
import os
from dotenv import load_dotenv
from langchain.chat_models import ChatOpenAI
from langchain.tools import tool
from langchain.agents import create_agent
from langgraph.memory import InMemorySaver
load_dotenv()
api_key = os.getenv('OPENAI_API_KEY')
# Initialize Chat Model
llm = ChatOpenAI(model_name="gpt-4", temperature=0.6, openai_api_key=api_key)Step 4: Define Agent Tools and Features
Define the tools that the agent will use. Tools are essential for enabling the agent to perform tasks.
steps
# Example data for fruit and reviews
fruits = {
"mango": {"price": 100, "quantity": 50, "description": "Sweet yellow mango"},
"banana": {"price": 40, "quantity": 100, "description": "Fresh ripe bananas"}
}
reviews = {
"mango": {"rating": 4.5, "comments": "Great flavor"},
"banana": {"rating": 4.0, "comments": "Good quality"}
}
# Tool for fetching fruit details
@tool
def get_fruit_details(fruit_name: str):
"""
Get details about a specific fruit given its name.
"""
return fruits.get(fruit_name, "Fruit not available.")
# Tool for fetching reviews
@tool
def get_reviews(fruit_name: str):
"""
Get reviews about a specific fruit given its name.
"""
return reviews.get(fruit_name, "No reviews available.")Step 5: Create and Configure the Agent
Initialize the AI agent with memory, tools, and system prompts.
steps
# Configure system prompt
system_prompt = """
You are a helpful assistant in a fruit store. You can assist users with obtaining fruit details,
reviews, and more.
"""
# Memory configuration
config = {
"configurable": {
"thread_id": "agent_fruit_store",
"checkpointer": InMemorySaver()
}
}
# Create agent
agent = create_agent(
model=llm,
tools=[get_fruit_details, get_reviews],
system_prompt=system_prompt,
**config
)Step 6: Execute and Verify Agent Operations
Learn how to interact with the agent and validate its operations.
steps
# Function to invoke the agent
def use_agent(user_input: str):
response = agent.invoke({"messages": [{"role": "user", "content": user_input}], "config": config})
# Extract and print response content
print(f"Agent Response: {response['messages'][-1]['content']}")
# Test interactions
use_agent("What is the price of mango?")
use_agent("Get me reviews for banana.")Integration Tips for Production Use
Takeaway
You've now created a LangChain-powered AI agent with tool integration and memory capabilities. Use this implementation as a foundation for more advanced AI agents tailored to specific domains.
FAQ
How can I add more tools to my LangChain agent?
You can define additional tools using the @tool decorator and include them in the tools list when creating the agent.
Does LangChain support persistent memory?
Yes, LangChain supports persistent memory configurations. You can use external storage solutions like databases or files to store conversation histories.
How secure is storing API keys in .env?
Storing API keys in .env is secure as long as you avoid sharing the file or exposing sensitive keys in your codebase.
Official reference: LangChain documentation.