็ฆป็บฟ่ตๆ ยท 01-ai-agent-handbook/chapters/17-fullstack-project.html
ๆฌ็ซ ๅฐๆดๅๅ้ขๆๅญฆ๏ผไป้ถๆๅปบไธไธชๅฎๆด็ๅค Agent ็ ็ฉถๆฅๅ็ๆ็ณป็ปใ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ็ ็ฉถๆฅๅ็ๆ็ณป็ป โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ User Input โ
โ โ โ
โ โโโโโโโโโโโโโโโ โ
โ โ Manager โ โ ไปปๅกๅ่งฃๅๅ่ฐ โ
โ โโโโโโโโฌโโโโโโโ โ
โ โ โ
โ โโโโโโโโดโโโโโโโ โ
โ โ Researcher โ โ ๆ็ดขๅๆถ้ไฟกๆฏ โ
โ โโโโโโโโฌโโโโโโโ โ
โ โ โ
โ โโโโโโโโดโโโโโโโ โ
โ โ Analyst โ โ ๆฐๆฎๅๆๅๆดๅฏๆๅ โ
โ โโโโโโโโฌโโโโโโโ โ
โ โ โ
โ โโโโโโโโดโโโโโโโ โ
โ โ Writer โ โ ๆฅๅๆฐๅๅๆถฆ่ฒ โ
โ โโโโโโโโฌโโโโโโโ โ
โ โ โ
โ โโโโโโโโดโโโโโโโ โ
โ โ Reviewer โ โ ่ดจ้ๅฎกๆ ธๅๅ้ฆ โ
โ โโโโโโโโโโโโโโโ โ
โ โ โ
โ Final Report (Markdown/PDF) โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
research_system/
โโโ config.py # ้
็ฝฎ็ฎก็
โโโ agents/
โ โโโ base.py # Agent ๅบ็ฑป
โ โโโ researcher.py # ็ ็ฉถๅ Agent
โ โโโ analyst.py # ๅๆๅธ Agent
โ โโโ writer.py # ๅไฝ Agent
โ โโโ reviewer.py # ๅฎกๆ ธ Agent
โโโ tools/
โ โโโ search.py # ๆ็ดขๅทฅๅ
ท
โ โโโ database.py # ๆฐๆฎๅบๅทฅๅ
ท
โ โโโ format.py # ๆ ผๅผๅๅทฅๅ
ท
โโโ memory/
โ โโโ store.py # ่ฎฐๅฟๅญๅจ
โโโ output/
โ โโโ markdown.py # Markdown ่พๅบ
โ โโโ pdf.py # PDF ่พๅบ
โโโ main.py # ไธปๅ
ฅๅฃ
โโโ requirements.txt # ไพ่ต
# config.py
from pydantic import BaseModel
from typing import List, Optional
class LLMConfig(BaseModel):
model: str = "gpt-4o"
api_key: str = ""
base_url: Optional[str] = None
temperature: float = 0.3
class AgentConfig(BaseModel):
max_steps: int = 10
max_tokens: int = 4096
retry_times: int = 3
class ResearchConfig(BaseModel):
llm: LLMConfig = LLMConfig()
agent: AgentConfig = AgentConfig()
topics: List[str] = []
output_format: str = "markdown"
# agents/base.py
from abc import ABC, abstractmethod
from typing import Dict, Any, Optional
from datetime import datetime
import json
class BaseAgent(ABC):
"""Agent ๅบ็ฑป"""
def __init__(self, name: str, config: Dict[str, Any]):
self.name = name
self.config = config
self.memory = []
@abstractmethod
def run(self, input_data: Dict[str, Any]) -> Dict[str, Any]:
"""ๆง่กไปปๅก"""
pass
def add_memory(self, key: str, value: Any):
"""ๆทปๅ ่ฎฐๅฟ"""
self.memory.append({
"key": key,
"value": value,
"timestamp": datetime.now().isoformat()
})
def get_memory(self, key: str) -> Optional[Any]:
"""่ทๅ่ฎฐๅฟ"""
for item in reversed(self.memory):
if item["key"] == key:
return item["value"]
return None
# agents/researcher.py
from agents.base import BaseAgent
from tools.search import SearchTool
class ResearcherAgent(BaseAgent):
"""็ ็ฉถๅ Agent"""
def __init__(self, config):
super().__init__("Researcher", config)
self.search_tool = SearchTool()
def run(self, input_data: Dict[str, Any]) -> Dict[str, Any]:
topic = input_data.get("topic", "")
depth = input_data.get("depth", "basic")
# ๅค่ฝฎๆ็ดข
results = []
queries = self._generate_queries(topic, depth)
for query in queries:
search_result = self.search_tool.execute(query)
results.append(search_result)
self.add_memory(f"search_{query}", search_result)
return {
"topic": topic,
"results": results,
"sources": len(results)
}
def _generate_queries(self, topic: str, depth: str) -> List[str]:
"""็ๆๆ็ดขๆฅ่ฏข"""
if depth == "deep":
return [
f"{topic} ๆๆฐ็ ็ฉถ",
f"{topic} ๅธๅบ่งๆจก",
f"{topic} ็ซไบๆ ผๅฑ",
f"{topic} ๅๅฑ่ถๅฟ"
]
return [f"{topic} ๆฆ่ฟฐ"]
# agents/analyst.py
from agents.base import BaseAgent
import json
# ๅ่ฎพ call_llm ๅทฒๆณจๅ
ฅ๏ผ็คบไพ๏ผfrom llm import call_llm๏ผ
def call_llm(prompt: str):
"""็คบไพ๏ผ่ฐ็จ LLM ่ทๅๅๅบ"""
from langchain_openai import ChatOpenAI
return ChatOpenAI(model="gpt-4o-mini").invoke(prompt)
class AnalystAgent(BaseAgent):
"""ๅๆๅธ Agent"""
def __init__(self, config):
super().__init__("Analyst", config)
def run(self, input_data: Dict[str, Any]) -> Dict[str, Any]:
research_data = input_data.get("research_results", [])
analysis = {
"swot": self._analyze_swot(research_data),
"trends": self._identify_trends(research_data),
"insights": self._extract_insights(research_data)
}
return analysis
def _analyze_swot(self, data: List[dict]) -> dict:
"""SWOT ๅๆ"""
# ่ฐ็จ LLM ่ฟ่กๅๆ
prompt = f"""ๅบไบไปฅไธ็ ็ฉถๆฐๆฎ๏ผ่ฟ่ก SWOT ๅๆ๏ผ
{json.dumps(data, ensure_ascii=False)}
่พๅบ JSON ๆ ผๅผ๏ผ
{{"strengths": [...], "weaknesses": [...],
"opportunities": [...], "threats": [...]}}"""
response = call_llm(prompt)
return json.loads(response.content)
# agents/writer.py
from agents.base import BaseAgent
class WriterAgent(BaseAgent):
"""ๅไฝ Agent"""
def __init__(self, config):
super().__init__("Writer", config)
def run(self, input_data: Dict[str, Any]) -> Dict[str, Any]:
research = input_data.get("research")
analysis = input_data.get("analysis")
report = self._generate_report(research, analysis)
return {
"report": report,
"word_count": len(report)
}
def _generate_report(self, research: dict, analysis: dict) -> str:
"""็ๆๆฅๅ"""
template = """# {topic} ็ ็ฉถๆฅๅ
## ๆง่กๆ่ฆ
{executive_summary}
## ๅธๅบๅๆ
{market_analysis}
## SWOT ๅๆ
{swot_analysis}
## ่ถๅฟไธๆบไผ
{trends_and_opportunities}
## ็ป่ฎบไธๅปบ่ฎฎ
{conclusions_and_recommendations}
"""
# ๅกซๅ
ๆจกๆฟ
return template.format(**analysis)
# agents/reviewer.py
from agents.base import BaseAgent
class ReviewerAgent(BaseAgent):
"""ๅฎกๆ ธ Agent"""
def run(self, input_data: Dict[str, Any]) -> Dict[str, Any]:
report = input_data.get("report", "")
feedback = {
"quality_score": self._score_quality(report),
"issues": self._find_issues(report),
"suggestions": self._suggest_improvements(report)
}
return feedback
def _score_quality(self, report: str) -> float:
"""่ดจ้่ฏๅ"""
# ๅฎ็ฐ่ฏๅ้ป่พ
return 0.85
# main.py
from agents.researcher import ResearcherAgent
from agents.analyst import AnalystAgent
from agents.writer import WriterAgent
from agents.reviewer import ReviewerAgent
from config import ResearchConfig
class ResearchSystem:
"""็ ็ฉถๆฅๅ็ๆ็ณป็ป"""
def __init__(self, config: ResearchConfig):
self.config = config
self.researcher = ResearcherAgent(config.agent.__dict__)
self.analyst = AnalystAgent(config.agent.__dict__)
self.writer = WriterAgent(config.agent.__dict__)
self.reviewer = ReviewerAgent(config.agent.__dict__)
def run(self, topic: str) -> str:
"""่ฟ่ก็ ็ฉถ็ณป็ป"""
print(f"๐ ๅผๅง็ ็ฉถไธป้ข: {topic}")
# 1. ็ ็ฉถ้ถๆฎต
research_result = self.researcher.run({"topic": topic})
print(f"โ
็ ็ฉถๅฎๆ๏ผ่ทๅ {research_result['sources']} ไธชๆฅๆบ")
# 2. ๅๆ้ถๆฎต
analysis_result = self.analyst.run({"research_results": research_result["results"]})
print("โ
ๅๆๅฎๆ")
# 3. ๅไฝ้ถๆฎต
writing_result = self.writer.run({
"research": research_result,
"analysis": analysis_result
})
print("โ
ๆฅๅๆฐๅๅฎๆ")
# 4. ๅฎกๆ ธ้ถๆฎต
review_result = self.reviewer.run({"report": writing_result["report"]})
print(f"โ
ๅฎกๆ ธๅฎๆ๏ผ่ดจ้่ฏๅ: {review_result['quality_score']}")
# 5. ่ฟๅๆ็ปๆฅๅ
return writing_result["report"]
# ไฝฟ็จ็คบไพ
if __name__ == "__main__":
config = ResearchConfig()
system = ResearchSystem(config)
report = system.run("AI Agent ๅธๅบ")
print("\n" + "="*50)
print("ๆ็ปๆฅๅ:")
print(report)
# output/markdown.py
def save_markdown(report: str, filename: str = "report.md"):
with open(filename, 'w', encoding='utf-8') as f:
f.write(report)
print(f"ๆฅๅๅทฒไฟๅญๅฐ: {filename}")
# output/pdf.py
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas
def save_pdf(report: str, filename: str = "report.pdf"):
c = canvas.Canvas(filename, pagesize=A4)
width, height = A4
# ๅๅ
ฅๅ
ๅฎน
c.drawString(100, height - 50, report)
c.save()
print(f"PDF ๅทฒไฟๅญๅฐ: {filename}")
# web_app.py
import asyncio
from fastapi import FastAPI
from pydantic import BaseModel
from main import ResearchSystem
from config import ResearchConfig
app = FastAPI()
class ResearchRequest(BaseModel):
topic: str
depth: str = "basic"
@app.post("/research")
async def start_research(request: ResearchRequest):
system = ResearchSystem(ResearchConfig())
report = await asyncio.to_thread(system.run, request.topic)
return {"report": report}
# API ็ซฏ็น
GET /health # ๅฅๅบทๆฃๆฅ
POST /research # ๅฏๅจ็ ็ฉถ
GET /research/{id} # ๆฅ่ฏข็ ็ฉถ็ถๆ
GET /reports/{id} # ่ทๅๆฅๅ
POST /reports/{id}/export # ๅฏผๅบๆฅๅ
โ ๆๆกไบๅ จๆ Agent ็ณป็ป็่ฎพ่ฎกๆนๆณ
โ ๅญฆไผไบๅค Agent ๅไฝ็ๅฎๆๅบ็จ
โ ไบ่งฃไบ็ไบง็บง็ณป็ป็ๅ ณ้ฎ่ฆ็ด