Facebook Pixel

AI Agent là gì? Hướng dẫn tạo AI Agent với LangGraph và LLM của OpenAI

18 Jan, 2025

AI Agent là một hệ thống được thiết kế để tự cảm nhận, tư duy và hành động thông qua việc sử dụng trí tuệ nhân tạo, với LLM làm nền tảng ngôn ngữ

AI Agent là gì? Hướng dẫn tạo AI Agent với LangGraph và LLM  của OpenAI

Mục Lục

Trong bài viết này, hãy cùng mình khám phá AI Agent là gì và mối liên hệ giữa AI Agent với các Mô hình Ngôn ngữ Lớn (LLM). Sau đó, chúng ta sẽ xây dựng một hệ thống AI Agent (Multi-Agent) với khả năng phân tích tài liệu của công ty, trích xuất các thông tin quan trọng như danh sách sản phẩm/dịch vụ, điểm nổi bật, và nhiều thông tin khác. Cuối cùng, hệ thống này sẽ tạo ra một email marketing cá nhân hóa hoàn chỉnh. Hãy cùng bắt đầu nhé!

1. AI Agent là gì?

Trước khi đề cập đến AI Agent thì chúng ta sẽ bàn về LLM, có thể gọi là "bộ não" đằng sau tất cả các AI Agent. Các bạn đã không còn xa lạ với các công cụ như ChatGPT, Gemini, Copilot rồi đúng không vậy thì bạn sẽ thấy chúng có thể làm được những điều sau đây:

  1. Hiểu ngữ cảnh (Contextual Understanding): Trong câu Tôi đánh rơi chìa khóa khi đang chạy vào nhà mô hình hiểu rằng "chìa khóa" không phải là cùng nghĩa với từ "chìa khóa thành công", trong ngữ cảnh này nó vật thể.
  2. Tạo ngôn ngữ tự nhiên (Natural Language Generation): Bạn có thể yêu cầu LLM viết một bài thơ về công nghệ AI theo phong cách Shakespeare.
  3. Tóm tắt thông tin (Summarization): Với bài báo nghiên cứu khoa học dài 20 trang, LLM có thể rút gọn thành một đoạn tóm tắt 200 từ.
  4. Dịch ngôn ngữ (Language Translation): Dịch tài liệu kỹ thuật từ tiếng Anh sang tiếng Nhật.
  5. Trả lời câu hỏi (Question Answering): Bạn đưa vào câu hỏi Tốc độ ánh sáng là bao nhiêu? Mô hình trả lời 299,792 km/s.
  6. Trích xuất thông tin (Information Extraction): Từ đoạn văn "Cuộc họp sẽ diễn ra vào 15:00 ngày 20/01/2025 tại Phòng A," LLM có thể trích xuất các thông tin: thời gian (15:00), ngày (20/01/2025), địa điểm (Phòng A).
  7. Phát hiện ý định (Intent Recognition): Với câu "Tôi cần một chuyến bay từ Hà Nội đến TP.HCM vào ngày mai," mô hình sẽ xác định ý định đặt vé máy bay và có thể tự động khởi tạo các đề xuất phù hợp.
  8. Phân loại văn bản (Text Classification): Phân tích email để xác định xem đó là thư rác (spam) hay thư hợp lệ, hoặc xác định cảm xúc trong một bài đánh giá sản phẩm (tích cực, tiêu cực, trung lập).
  9. Suy luận ngôn ngữ (Language Reasoning): Khi được hỏi, "Nếu hôm nay là thứ Hai, vậy ngày kia là thứ mấy?" mô hình sẽ trả lời "Thứ Tư" mà không cần thêm dữ kiện.
  10. Transfer Learning: Mô hình được huấn luyện với ngôn ngữ tiếng Anh nhưng vẫn có thể thực hiện tốt các tác vụ ngôn ngữ khác như phân tích cảm xúc trong tiếng Đức.
  11. Sáng tạo đa ngôn ngữ (Multilingual Creativity): Viết một bài báo giới thiệu sản phẩm bằng tiếng Anh nhưng có tiêu đề và đoạn mở đầu bằng tiếng Việt.
  12. Tương tác đa phương thức (Multimodal Integration): Bạn tải lên một hình ảnh biểu đồ doanh số và yêu cầu mô hình tóm tắt xu hướng trong dữ liệu.

Vậy AI Agent là gì? AI Agent là một hệ thống tự động được thiết kế để cảm nhận, tư duy và hành động thông qua việc sử dụng trí tuệ nhân tạo, với LLM làm nền tảng ngôn ngữ, từ đó giải quyết các vấn đề thực tế một cách hiệu quả và sáng tạo.

AI Agent sử dụng LLM như một "bộ não" để thực hiện các tác vụ phức tạp hơn. Mình có thể khẳng định nếu không có LLM thì sẽ không có AI Agent ra đời, mà chỉ là những Agent thực hiện công việc dựa theo các lệnh đã lập trình sẵn như một cỗ máy.

2. Hướng dẫn tạo AI Agent với LangGraph và LLM của OpenAI

LangGraph là một công cụ giúp bạn tạo ra các workflows có trạng thái và điều kiện. Với LangGraph, bạn có thể định nghĩa các nodes (các bước xử lý thông tin) và edges (các quy tắc kết nối giữa các bước). Bằng cách kết hợp nodes và edges, bạn dễ dàng xây dựng các quy trình ra quyết định hoặc chuỗi xử lý dành cho các ứng dụng AI.

Cài đặt các thư viện cần thiết:

Bash
pip install langchain langchain-community langgraph chromadb pypdf python-dotenv openai tiktoken

2.1 Xây dựng Agent thông thường với LangGraph

State là phần cốt lõi của LangGraph. Nó lưu trữ tất cả thông tin được truyền giữa các nodes. Chúng ta sẽ định nghĩa nó dưới dạng một dictionary bằng cách sử dụng TypedDict của Python để cung cấp gợi ý về kiểu dữ liệu.

Python
from typing_extensions import TypedDict

class State(TypedDict):
    message: str
    sentiment: str

Cấu trúc state bao gồm:

  • message: Tin nhắn đầu vào của người dùng.
  • sentiment: Kết quả sau khi phân tích.

Nodes là các hàm Python dùng để xử lý state. Mỗi node nhận state làm đầu vào và cập nhật nó.

Python
def analyze_sentiment(state):
    print("---Analyzing Sentiment---")
    text = state["message"].lower()
    
    # Simple sentiment analysis
    if any(word in text for word in ["good", "great", "happy"]):
        return {"sentiment": "positive"}
    if any(word in text for word in ["bad", "sad", "terrible"]):
        return {"sentiment": "negative"}
    return {"sentiment": "neutral"}

def positive_response(state):
    print("---Positive Response---")
    return {"message": "Thank you for the positive feedback! 😊"}

def negative_response(state):
    print("---Negative Response---")
    return {"message": "We’re sorry to hear that. How can we improve? 😞"}

Edges định nghĩa flow giữa các nodes. Một edge có điều kiện sẽ xác định node tiếp là gì theo dựa trên logic.

Python
from typing import Literal

def sentiment_router(state) -> Literal["positive_response", "negative_response"]:
    if state["sentiment"] == "positive":
        return "positive_response"
    return "negative_response"

Bây giờ, chúng ta sử dụng StateGraph của LangGraph để xây dựng Agent.

Python
from langgraph.graph import StateGraph, START, END

# Initialize graph
builder = StateGraph(State)

# Add nodes
builder.add_node("analyze_sentiment", analyze_sentiment)
builder.add_node("positive_response", positive_response)
builder.add_node("negative_response", negative_response)

# Add edges
builder.add_edge(START, "analyze_sentiment")
builder.add_conditional_edges("analyze_sentiment", sentiment_router)
builder.add_edge("positive_response", END)
builder.add_edge("negative_response", END)

# Compile graph
graph = builder.compile()

Kiểm tra graph với tin nhắn như bên dưới.

Python
# Invoke the graph with input
result = graph.invoke({"message": "I had a great experience!"})

print(result)

2.2 Xây dựng AI Agent với LangGraph và LLM của OpenAI

Ở ví dụ trên các bạn thấy là demo về một Agent không được "thông minh" lắm, nó sẽ làm theo những gì mà mình đã hardcode, vậy bây giờ hãy cùng mình xây dựng một ứng dụng Multi-Agent có khả năng đọc danh sách sản phẩm, dịch vụ của công ty bạn, trích xuất những điểm nổi bật và tạo ra Email MKT hoàn chỉnh như thế nào nhé.

Những Agent tham gia vào quá trình này bao gồm:

  • ResearchAgent: Phân tích tài liệu để trích xuất thông tin như Sản phẩm/dịch vụ của công ty, đặc điểm nổi bật, case studies hoặc các thành công đạt được.
  • StrategyAgent: Lên kế hoạch chiến lược cho email bao gồm: Thông điệp chính, giọng văn và cách tiếp cận, các điểm cụ thể cần đưa vào, cấu trúc email.
  • WriterAgent: Viết nội dung email dựa trên chiến lược và nghiên cứu, tiêu đề phải thu hút, lời chào cá nhân hóa, nội dung hấp dẫn.

Bước 1: Upload file html vào thư mục docs, đây là file mẫu của mình, các bạn có thể đổi code để phù hợp với định dạng file pdf hay word nhé.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Thông tin khóa học 200Lab</title>
</head>
<body>
    <p>Sản phẩm: Hiện tại 200Lab có các khóa học sau: DevOps, Backend, Frontend với giá lần lượt là 10$, 20$, và 30$ ở hình thức học Online. Offline thì cộng thêm 10$ trên giá Online.</p>
    <p>Các hình thức thanh toán bao gồm: thẻ tín dụng, chuyển khoản và trả góp.</p>
    <p>Điểm nổi trội: Khoá học tập trung vào các bài toán thực tế mà các bạn hay gặp phải trong doanh nghiệp. Mentor là những người đã có nhiều năm kinh nghiệm</p>
</body>
</html>

Bước 2: Tạo file python với nội dung sau trong cùng thư mục chứa folder docs.

Python
import os
from typing import TypedDict, Annotated, Sequence, Union, List
from langgraph.graph import Graph, StateGraph
from langchain_core.messages import HumanMessage, AIMessage
from langchain.document_loaders import DirectoryLoader, TextLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import Chroma
from langchain.chat_models import ChatOpenAI
from langchain.chains import RetrievalQA
from langchain_core.output_parsers import JsonOutputParser
from dotenv import load_dotenv
import json
from typing import TypedDict, List

import os
os.environ['OPENAI_API_KEY'] = 'your_open_ai_key'

def load_documents(folder_path='docs'):
    loader = DirectoryLoader(folder_path, glob="./*.html", loader_cls=lambda path: TextLoader(path, encoding="utf-8"))
    documents = loader.load()
    return documents
    
def create_vector_store(documents,db_directory = 'db'):
    text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
    documents = text_splitter.split_documents(documents)

    embedding = OpenAIEmbeddings(model="text-embedding-ada-002")


    vectorstore = Chroma.from_documents(
       documents=documents,
       embedding=embedding,
       persist_directory=db_directory
    )
    return vectorstore
# Define state schema
# Initialize agents
llm = ChatOpenAI(temperature=0.7)
class AgentState(TypedDict):
    messages: List[str]
    topic: str
    recipient_type: str
    research_findings: str
    email_strategy: str
    final_email: str
    current_agent: str
    next_agent: str
    done: bool
    
class ResearchAgent:
    def __init__(self, vectorstore):
        self.retriever = vectorstore.as_retriever()
        self.qa_chain = RetrievalQA.from_chain_type(
            llm=llm,
            chain_type="stuff",
            retriever=self.retriever,
            return_source_documents=True
        )

    def __call__(self, state: AgentState) -> dict:
        print("Research Agent: Analyzing documents...")

        query = f"""
        Analyze the provided documents and extract key information about:
        1. Our company's services/products
        2. Key selling points
        3. Relevant case studies or success stories
        4. Any specific information related to {state['topic']}

        Format the findings in a clear, structured way.
        """

        response = self.qa_chain.invoke({"query": query})
        state['research_findings'] = response['result']
        state['current_agent'] = 'research'
        state['next_agent'] = 'strategy'
        return state
class StrategyAgent:
    def __init__(self):
        self.llm = llm

    def __call__(self, state: AgentState) -> dict:
        print("Strategy Agent: Planning email approach...")

        prompt = f"""
        Based on the research findings below, develop a strategy for the marketing email:

        Research Findings:
        {state['research_findings']}

        Target Recipient: {state['recipient_type']}
        Topic Focus: {state['topic']}

        Create a strategic plan that includes:
        1. Key messages to emphasize
        2. Recommended tone and approach
        3. Specific points from the research to include
        4. Suggested structure for maximum impact
        """

        messages = [HumanMessage(content=prompt)]
        response = self.llm.invoke(messages)

        state['email_strategy'] = response.content
        state['current_agent'] = 'strategy'
        state['next_agent'] = 'writer'
        return state  
class WriterAgent:
    def __init__(self):
        self.llm = llm

    def __call__(self, state: AgentState) -> dict:
        print("Writer Agent: Composing email...")

        prompt = f"""
        Create a compelling marketing email in Vietnamese using the research and strategy below:

        Research Findings:
        {state['research_findings']}

        Email Strategy:
        {state['email_strategy']}

        Topic Focus: {state['topic']}
        Target Recipient: {state['recipient_type']}

        Generate a professional email that includes:
        1. Attention-grabbing subject line
        2. Personalized greeting
        3. Compelling body content
        4. Clear call to action
        5. Professional signature

        Make sure to incorporate specific details from the research and follow the recommended strategy.
        """

        messages = [HumanMessage(content=prompt)]
        response = self.llm.invoke(messages)

        state['final_email'] = response.content
        state['current_agent'] = 'writer'
        state['done'] = True
        return state
    
def create_agent_graph(vectorstore):
    # Initialize agents
    research_agent = ResearchAgent(vectorstore)
    strategy_agent = StrategyAgent()
    writer_agent = WriterAgent()

    # Create workflow graph
    workflow = StateGraph(AgentState)

    # Add agent nodes
    workflow.add_node('research', research_agent)
    workflow.add_node('strategy', strategy_agent)
    workflow.add_node('writer', writer_agent)

    # Define edges
    workflow.add_edge('research', 'strategy')
    workflow.add_edge('strategy', 'writer')

    # Set entry point
    workflow.set_entry_point('research')

    # Add conditional edge for completion
    workflow.add_conditional_edges(
        'writer',
        should_continue
    )

    # Set end point
    workflow.add_node("end", lambda x: x)

    # Compile workflow
    return workflow.compile()

def should_continue(state: AgentState) -> str:
    """Determine if the workflow should continue or end."""
    if state['done']:
        return "end"
    return state['next_agent']

# documents = load_documents()
# vectorstore = create_vector_store(documents)


def main():
    print("Welcome to the Multi-Agent Email Generator!")
    print("Please ensure your files are uploaded to the 'docs' folder.")

    try:
        # Load documents and create vector store
        print("\nLoading documents...")
        documents = load_documents()
        vectorstore = create_vector_store(documents)

        # Create agent workflow
        workflow = create_agent_graph(vectorstore)

        while True:
            # Get user input
            print("\nWhat would you like to focus on in the email?")
            topic = input("Enter topic (or 'quit' to exit): ")

            if topic.lower() == 'quit':
                break

            recipient_type = input("Who is the target recipient? ")

            # Initialize state
            state = AgentState(
                messages=[],
                topic=topic,
                recipient_type=recipient_type,
                research_findings="",
                email_strategy="",
                final_email="",
                current_agent="",
                next_agent="research",
                done=False
            )

            # Run workflow
            print("\nGenerating email using multi-agent system...")
            final_state = workflow.invoke(state)

            # Display results
            print("\nGenerated Email:")
            print("-" * 50)
            print(final_state['final_email'])
            print("-" * 50)

            continue_gen = input("\nWould you like to generate another email? (yes/no): ")
            if continue_gen.lower() != 'yes':
                break

    except Exception as e:
        print(f"An error occurred: {str(e)}")

if __name__ == "__main__":
    main()

Bước 3: chạy câu lệnh bên dưới và nhập theo gợi ý của mình

Python
python mkt_agent.py

Ứng dụng sẽ hỏi bạn các thông tin sau:

  • What would you like to focus on in the email? -> introduce all my courses
  • Who is the target recipient? => test@gmail.com

Và đây là kết quả mà mình nhận được, theo mình đánh giá thì kết quả không được tốt lắm, theo kinh nghiệm dùng ChatGPT của mình thì bạn cần phải cho nó xem mẫu email mà bạn tâm đắt, để nó học (train) theo văn phong đó thì kết quả mới tốt được, điều này có nghĩa là bạn cần viết thêm một Agent nữa.

Text
Subject: Nâng cao kỹ năng với các khóa học thực tế từ 200Lab

Chào bạn test@gmail.com,

Chúng tôi là 200Lab, một tổ chức cung cấp ba khóa học chính: DevOps, Backend và Frontend. Với mỗi khóa học, chúng tôi tập trung vào giải quyết các vấn đề thực tế mà bạn thường gặp phải trong thế giới kinh doanh. Điều đặc biệt là các mentor của chúng tôi đều có kinh nghiệm rộng lớn trong lĩnh vực này.

Chúng tôi xin giới thiệu giá của các khóa học như sau:
- DevOps: $10 cho học trực tuyến, $20 cho học trực tiếp
- Backend: $20 cho học trực tuyến, $30 cho học trực tiếp
- Frontend: $30 cho học trực tuyến, $40 cho học trực tiếp
Chúng tôi chấp nhận thanh toán bằng thẻ tín dụng, chuyển khoản ngân hàng và trả góp.

Chúng tôi rất mong bạn sẽ tham gia một trong những khóa học của chúng tôi để nâng cao kỹ năng của mình. Để biết thêm thông tin và đăng ký, vui lòng truy cập website của chúng tôi.

Cảm ơn bạn đã dành thời gian quan tâm đến các khóa học của 200Lab.

Trân trọng,
[Your Name]
200Lab Team

3. Kết luận

Lại thêm một bài viết nữa được hoàn thành trong Series AI For Developer, mình hy vọng sẽ nhận được sự ủng hộ và góp ý của mọi người để có thể làm tốt hơn trong tương lai.

Các bài viết liên quan:

Bài viết liên quan

Lập trình backend expressjs

xây dựng hệ thống microservices
  • Kiến trúc Hexagonal và ứng dụng
  • TypeScript: OOP và nguyên lý SOLID
  • Event-Driven Architecture, Queue & PubSub
  • Basic scalable System Design

Đăng ký nhận thông báo

Đừng bỏ lỡ những bài viết thú vị từ 200Lab