iT邦幫忙

2025 iThome 鐵人賽

DAY 18
0
生成式 AI

30 天打造你的 AI Agent:LangChain × n8n 實戰系列 第 18

資料分析 Agent:讀取 CSV 並產生結論

  • 分享至 

  • xImage
  •  

今天我們讓 Agent 直接讀取結構化資料,並自動生成分析結論。


一、概念

  • 資料來源 → CSV 或 Excel
  • Agent 能力 → 計算、統計、生成結論
  • 用途 → 快速分析報表、統計數據、產生文字摘要

二、實作範例

import pandas as pd
import os
from langchain.tools import Tool
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain.agents import initialize_agent, AgentType

# -------------------------------
# 1. 生成範例 CSV
# -------------------------------
data = {
    "product": ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"],
    "sales": [120, 150, 90, 200, 175, 130, 160, 110, 140, 180]
}
df = pd.DataFrame(data)
df.to_csv("sales.csv", index=False)
print("✅ sales.csv 已生成")

# -------------------------------
# 2. 初始化 LLM
# -------------------------------
# 設定 Gemini API Key
os.environ["GOOGLE_API_KEY"] = "你的 Gemini API Key"

llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash", temperature=0)

# -------------------------------
# 3. 建立資料分析工具
# -------------------------------
def analyze_csv(query: str) -> str:
    df = pd.read_csv("sales.csv")  # 讀取 CSV
    avg_sales = df['sales'].mean()
    max_sales = df['sales'].max()
    min_sales = df['sales'].min()
    return (
        f"CSV 平均銷售額為 {avg_sales:.2f}\n"
        f"最高銷售額為 {max_sales}\n"
        f"最低銷售額為 {min_sales}"
    )

csv_tool = Tool(
    name="CSVAnalyzer",
    func=analyze_csv,
    description="分析 CSV 資料,回答統計或簡單問題"
)

# -------------------------------
# 4. 初始化 Agent
# -------------------------------
agent = initialize_agent(
    tools=[csv_tool],
    llm=llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True
)

# -------------------------------
# 5. 測試
# -------------------------------
question = "CSV 平均銷售額是多少?"
response = agent.run(question)
print("\n💡 Agent 回答:")
print(response)

範例測試結果

Action: CSVAnalyzer
Action Input: 計算 CSV 的平均銷售額
Observation: CSV 平均銷售額為 145.50
最高銷售額為 200
最低銷售額為 90
Thought:Final Answer: CSV 平均銷售額為 145.50

> Finished chain.

💡 Agent 回答:
CSV 平均銷售額為 145.50

三、今日小結

  • Agent 可以直接讀取 CSV 並回答問題
  • 可以搭配其他工具進行更複雜的數據分析
  • 為後續知識庫整合或多工具任務打下基礎

上一篇
自動摘要 Agent:幫你整理新聞或文章
下一篇
知識庫 Agent:整合外部文件(如 PDF、Docs)
系列文
30 天打造你的 AI Agent:LangChain × n8n 實戰20
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言