What We Are Building
A chatbot that:
- Answers questions using the web
- Remembers what you said before
- Has a nice chat interface
- Runs in your browser
Step 1: Install Dependencies
pip install streamlit langchain langchain-openai duckduckgo-search
Step 2: Create the Chatbot
Create chatbot.py:
python
import streamlit as st
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, AIMessage
from langchain_core.tools import tool
from langgraph.prebuilt import create_react_agent
# --- Tools ---
@tool
def web_search(query: str) -> str:
"""Search the web for information"""
from duckduckgo_search import DDGS
with DDGS() as ddgs:
results = list(ddgs.text(query, max_results=3))
return "\n".join([r["body"] for r in results])
@tool
def calculate(expression: str) -> str:
"""Calculate a math expression"""
return str(eval(expression))
# --- Page Config ---
st.set_page_config(page_title="My AI Chatbot", page_icon="đ¤")
st.title("đ¤ My First AI Chatbot")
# --- Session State ---
if "messages" not in st.session_state:
st.session_state.messages = []
# --- Display Old Messages ---
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# --- Get User Input ---
if prompt := st.chat_input("Ask me anything"):
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
if "agent" not in st.session_state:
llm = ChatOpenAI(model="gpt-4o", temperature=0)
st.session_state.agent = create_react_agent(
model=llm,
tools=[web_search, calculate],
)
with st.chat_message("assistant"):
with st.spinner("Thinking..."):
history = []
for msg in st.session_state.messages[:-1]:
if msg["role"] == "user":
history.append(HumanMessage(content=msg["content"]))
else:
history.append(AIMessage(content=msg["content"]))
history.append(HumanMessage(content=prompt))
result = st.session_state.agent.invoke({"messages": history})
response = result["messages"][-1].content
st.markdown(response)
st.session_state.messages.append({"role": "assistant", "content": response})
Step 3: Run It
streamlit run chatbot.py
Open http://localhost:8501 and start chatting.
How It Works
Architecture Diagram
1. User types a question
2. Streamlit shows the question
3. Agent receives the question
4. Agent decides: search web or calculate?
5. Agent uses the tool
6. Agent formulates answer
7. Streamlit displays the answer
8. Memory saves everything
Adding More Tools
python
@tool
def get_stock_price(symbol: str) -> str:
"""Get current stock price"""
return f"{symbol} is trading at $150.25"
agent = create_react_agent(
model=llm,
tools=[web_search, calculate, get_stock_price],
)
Related Topics
| Topic | Link |
|---|---|
| LLM Fine-Tuning | Custom Models |
| RAG Systems | Document QA |
| Production Apps | Building Apps |
| GenAI Projects | Project Ideas |