🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

First Chatbot Project - Build a Working Chatbot

đŸŸĸ Free Lesson

Advertisement


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
Chatbot ArchitectureStreamlitChat UILangChainAgent + ToolsWeb SearchChat Memory

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

TopicLink
LLM Fine-TuningCustom Models
RAG SystemsDocument QA
Production AppsBuilding Apps
GenAI ProjectsProject Ideas

What to Learn Next

-> Tool Calling

Learn about more tools.

-> RAG for Beginners

Give your chatbot knowledge.

-> LangGraph

Build smarter agents.

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert AI Agents Beginner Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement