How to Build Your First AI Agent: A Step-by-Step Tutorial with Python & LangChain
1. Setting Up Your AI Development Environment
- Install Python 3.10+, pip, and a virtual environment (venv or conda) to isolate dependencies.
- Install core libraries:
langchain,openai,tavily-python, andpython-dotenvvia a single requirements file. - Generate and securely store API keys for OpenAI (or your LLM provider) and Tavily (for web search) in a
.envfile.
2. Understanding the Agent Architecture: Tools, LLM, and Memory
- Define the three core components: the LLM (reasoning engine), tools (external functions like search or calculator), and memory (conversation history).
- Explain how an agent loop works: observe → think → act → observe again until a final answer is reached.
- Introduce LangChain’s
AgentExecutorandcreate_openai_tools_agentas the scaffolding for our agent.
3. Building Your First Custom Tool: A Web Search Function
- Implement a
search_webfunction using Tavily’s API that returns top 3 results with titles and snippets. - Wrap the function as a LangChain
Toolobject with a name, description, and input schema so the LLM knows when and how to call it. - Test the tool standalone by calling it with a sample query (e.g., “latest AI news 2025”).
4. Assembling the Agent: Connecting LLM, Tools, and Prompt
- Create a system prompt that instructs the agent to use tools only when necessary and to cite sources.
- Initialize the LLM (e.g., GPT-4o-mini) and bind your custom tools to it using
bind_tools(). - Use
create_openai_tools_agent()to combine the LLM, tools, and prompt, then wrap it in anAgentExecutorwithhandle_parsing_errors=True.
5. Running Your Agent: Real-World Query Examples
- Execute the agent with a multi-step query: “Find the current stock price of Tesla and then summarize a recent earnings report.”
- Observe the agent’s reasoning trace (thoughts, actions, observations) printed step-by-step for debugging.
- Handle edge cases like API rate limits or empty search results by adding fallback logic in the tool.
6. Adding Memory for Context-Aware Conversations
- Implement
ConversationBufferMemoryorConversationSummaryMemoryto let the agent remember previous turns. - Modify the agent setup to pass memory into the
AgentExecutorand update the prompt to include chat history. - Test a follow-up query: after asking “What’s the weather
Related: Ai Agent: Ai Agent Frameworks Eval 2024
AI Automation Playbook
Step-by-step workflows for automating content, email, social media, and research with AI agents.


