
你有没有和一位从不睡觉、无需休息的数据分析师共事过?或者一位处理数字的速度比你说“数据透视表”还快的数据分析师?如果没有,那就坐稳了,因为我们即将打造这样的人!今天,我们将创建一个数据分析师人工智能代理,用于闪电般的数据分析。使用 OpenAI 的函数调用,这个人工智能自动化系统可以用简单的英语解释你提出的问题,并在几秒钟内给出所需的输出。
如果一切都按照我们设想的方式设置好,你可以向代理提问,例如“上个季度我们某个部门排名最高的产品是什么?”或“向我展示营销支出和销售额之间的相关性”。作为回报,你将得到即时准确的答案和精美的图表。这就是 OpenAI 函数调用与 OpenAI 数据分析功能相结合所能为你做到的。
为什么如此激动人心?
过去数据思维存在的问题是必须了解 SQL。需要高阶思维来理解所分析数据的复杂性。否则,光是浏览各种仪表盘界面就得花上几个小时。现在,函数调用使我们能够创建 AI 代理,使其成为人类语言和数据指令之间的翻译媒介。想象一下,一位能够流利地使用“人类”和“数据库”进行交流的翻译员!

当 OpenAI 语言模型根据您的自然语言查询选择需要调用的函数时,奇迹就发生了。如果您询问趋势,它会调用时间序列分析函数。如果您请求比较,它会调用统计比较函数。AI 就像您的助手,它知道针对任何问题的正确工具。
架构:所有组件如何协同工作
我们的数据分析师 AI 是由多个主要组件组成的,它们彼此同步工作。以下是所有协同工作的组件:
- 大脑(OpenAI 的 GPT 模型):处理自然语言查询并决定调用哪些函数。您可以将其视为一位经验丰富的数据分析师,了解业务问题和技术实现难题。
- 工具箱(函数库):我们将为从统计到图形的每个不同分析创建一个独立的函数。每个函数都旨在高效地执行给定的数据操作。
- 数据层:负责加载、清理和准备所有数据集。我们将处理多种类型的数据,并确保我们的代理可以处理所有可用的杂乱数据。
- 通信接口:这将确保用户、AI 模型和功能任务之间的来回交互有效并产生有意义的结果。

这种架构的美妙之处在于它的简洁性。只需编写几个新函数并将它们注册到 AI 中即可。需要新的数据源?只需插入新的数据连接器即可。无需人工数据分析师,即可实现无限的扩展!
设置您的开发环境
首先,我们需要为我们寻求的 AI 驱动的数据科学搭建一个工作区。操作方法如下。
- 必要的依赖项:您需要 OpenAI 的 Python 包用于 API 调用。您还需要 pandas 用于数据处理(因为 pandas 就像数据科学中的瑞士军刀),matplotlib 和 seaborn 用于绘图,以及 numpy 用于数字运算。
- API 配置:从 OpenAI 获取您的 API 密钥。此外,我们将添加一些带有速率限制的错误处理功能,以确保工作顺利进行。
- 数据准备工具:安装用于 CSV、JSON、Excel 文件的库,如果您有雄心壮志,甚至可以安装数据库连接!
核心功能:AI分析师的核心
我们希望开发一套基本功能,赋予我们的 AI 代理强大的分析能力:
- 加载和检查:从各种格式/来源加载数据,并初步了解其结构、数据类型和基本统计数据。这些功能是 AI 熟悉数据的阶段。
- 统计分析:这些功能提供数据的数学解释,涵盖从基本的描述性统计到更复杂的相关性分析。它们旨在以适合 AI 解释和用户组件描述的格式呈现结果。
- 可视化:这些功能将在 AI 确定分析结果时生成图表、图形和曲线图。它们必须足够灵活,能够处理各种数据类型,并生成人类可读的输出。
过滤和数据转换:通过这些功能,AI 可以根据用户查询对数据进行剪切、切块和重塑。
函数调用的魔力
事情变得非常有趣。当你问“我们月销售额的趋势是什么?”这样的问题时,AI 不会给出一个泛泛而谈的答案。相反,它会执行以下操作:
- 首先,它会分析问题,准确理解你的需求。它会识别“趋势”和“每月”等词语。然后,它会将这些词语与一些合适的分析方法联系起来。
- 基于这种理解,它会决定调用哪些函数以及调用顺序。它可能会决定首先调用加载数据函数,然后应用基于时间的过滤、趋势分析,最后创建可视化效果。
- AI 会按顺序执行这些函数,并在执行过程中穿插一些数据传递。每个函数都会提供结构化的输出,供 AI 进行处理和构建。
- 总而言之,AI 会将多个分析阶段的所有输出整合成一个连贯的解释。然后,它会将这些信息返回给最终用户,并提供洞察、可视化效果和行动建议。
实践项目:构建你的数据分析师AI代理
让我们更进一步,构建一个完整的数据分析师 AI 代理,它能够处理真实的业务数据并提供切实可行的洞察。为此,我们将设计一个 AI 代理来分析电商销售数据。该代理将能够回答有关产品性能、客户行为、季节性趋势以及提升收入的领域等问题。
1. 安装所需软件包
!pip install openai pandas matplotlib seaborn numpy plotly
2. 导入库并设置
import openai
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, timedelta
import json
import warnings
warnings.filterwarnings('ignore')
# Set your OpenAI API key here
openai.api_key = "your-openai-api-key-here" # Replace with your actual API key
print(" All libraries imported successfully!")
3. 生成示例电子商务数据
def generate_sample_data():
"""Generate realistic e-commerce sales data for demonstration"""
np.random.seed(42)
# Product categories and names
categories = ['Electronics', 'Clothing', 'Books', 'Home & Garden', 'Sports']
products = {
'Electronics': ['Smartphone', 'Laptop', 'Headphones', 'Tablet', 'Smart Watch'],
'Clothing': ['T-Shirt', 'Jeans', 'Sneakers', 'Jacket', 'Dress'],
'Books': ['Fiction Novel', 'Science Book', 'Cookbook', 'Biography', 'Self-Help'],
'Home & Garden': ['Coffee Maker', 'Plant Pot', 'Lamp', 'Pillow', 'Rug'],
'Sports': ['Running Shoes', 'Yoga Mat', 'Dumbbell', 'Basketball', 'Tennis Racket']
}
# Generate data for the last 12 months
start_date = datetime.now() - timedelta(days=365)
dates = pd.date_range(start=start_date, end=datetime.now(), freq='D')
data = []
customer_id = 1000
for date in dates:
# Simulate seasonal patterns
month = date.month
seasonal_multiplier = 1.2 if month in [11, 12] else (1.1 if month in [6, 7] else 1.0)
# Generate 10-50 orders per day
daily_orders = np.random.poisson(25 * seasonal_multiplier)
for _ in range(daily_orders):
category = np.random.choice(categories, p=[0.3, 0.25, 0.15, 0.15, 0.15])
product = np.random.choice(products[category])
# Price based on category
price_ranges = {
'Electronics': (50, 1000),
'Clothing': (15, 200),
'Books': (10, 50),
'Home & Garden': (20, 300),
'Sports': (25, 250)
}
price = np.random.uniform(*price_ranges[category])
quantity = np.random.choice([1, 2, 3], p=[0.7, 0.2, 0.1])
data.append({
'date': date,
'customer_id': customer_id,
'product_name': product,
'category': category,
'quantity': quantity,
'unit_price': round(price, 2),
'total_amount': round(price * quantity, 2)
})
customer_id += 1
return pd.DataFrame(data)
# Generate and display sample data
df = generate_sample_data()
print(f" Generated {len(df)} sales records")
print("\n Sample Data Preview:")
print(df.head())
print(f"\n Date Range: {df['date'].min()} to {df['date'].max()}")
print(f" Total Revenue: ${df['total_amount'].sum():,.2f}")
4. 定义分析函数
class DataAnalyzer:
def __init__(self, dataframe):
self.df = dataframe.copy()
self.df['date'] = pd.to_datetime(self.df['date'])
def get_revenue_summary(self, period='monthly'):
"""Calculate revenue summary by time period"""
try:
if period == 'daily':
grouped = self.df.groupby(self.df['date'].dt.date)
elif period == 'weekly':
grouped = self.df.groupby(self.df['date'].dt.isocalendar().week)
elif period == 'monthly':
grouped = self.df.groupby(self.df['date'].dt.to_period('M'))
else:
return {"error": "Invalid period. Use 'daily', 'weekly', or 'monthly'"}
revenue_data = grouped['total_amount'].sum().reset_index()
revenue_data.columns = ['period', 'revenue']
return {
"success": True,
"data": revenue_data.to_dict('records'),
"total_revenue": float(self.df['total_amount'].sum()),
"average_revenue": float(revenue_data['revenue'].mean()),
"period": period
}
except Exception as e:
return {"error": str(e)}
def get_top_products(self, limit=10, metric='revenue'):
"""Get top performing products"""
try:
if metric == 'revenue':
top_products = self.df.groupby('product_name')['total_amount'].sum().sort_values(ascending=False).head(limit)
elif metric == 'quantity':
top_products = self.df.groupby('product_name')['quantity'].sum().sort_values(ascending=False).head(limit)
else:
return {"error": "Invalid metric. Use 'revenue' or 'quantity'"}
return {
"success": True,
"data": [{"product": prod, "value": float(val)} for prod, val in top_products.items()],
"metric": metric,
"limit": limit
}
except Exception as e:
return {"error": str(e)}
def get_category_performance(self):
"""Analyze performance by product category"""
try:
category_stats = self.df.groupby('category').agg({
'total_amount': ['sum', 'mean'],
'quantity': 'sum',
'customer_id': 'nunique'
}).round(2)
category_stats.columns = ['total_revenue', 'avg_order_value', 'total_quantity', 'unique_customers']
category_stats = category_stats.reset_index()
return {
"success": True,
"data": category_stats.to_dict('records')
}
except Exception as e:
return {"error": str(e)}
def get_customer_insights(self):
"""Analyze customer behavior patterns"""
try:
customer_stats = self.df.groupby('customer_id').agg({
'total_amount': 'sum',
'date': ['min', 'max', 'nunique']
}).round(2)
customer_stats.columns = ['total_spent', 'first_purchase', 'last_purchase', 'purchase_frequency']
insights = {
"total_customers": len(customer_stats),
"avg_customer_value": float(customer_stats['total_spent'].mean()),
"avg_purchase_frequency": float(customer_stats['purchase_frequency'].mean()),
"top_spenders": customer_stats.nlargest(5, 'total_spent')['total_spent'].to_dict()
}
return {"success": True, "data": insights}
except Exception as e:
return {"error": str(e)}
def create_visualization(self, chart_type, data_params):
"""Create various types of visualizations"""
try:
plt.figure(figsize=(12, 6))
if chart_type == 'revenue_trend':
# Monthly revenue trend
monthly_data = self.df.groupby(self.df['date'].dt.to_period('M'))['total_amount'].sum()
plt.plot(range(len(monthly_data)), monthly_data.values, marker='o', linewidth=2)
plt.title('Monthly Revenue Trend', fontsize=16, fontweight='bold')
plt.xlabel('Month')
plt.ylabel('Revenue ($)')
plt.xticks(range(len(monthly_data)), [str(x) for x in monthly_data.index], rotation=45)
plt.grid(True, alpha=0.3)
elif chart_type == 'category_pie':
# Category revenue distribution
category_revenue = self.df.groupby('category')['total_amount'].sum()
plt.pie(category_revenue.values, labels=category_revenue.index, autopct='%1.1f%%', startangle=90)
plt.title('Revenue Distribution by Category', fontsize=16, fontweight='bold')
elif chart_type == 'top_products_bar':
# Top products bar chart
top_products = self.df.groupby('product_name')['total_amount'].sum().sort_values(ascending=False).head(10)
plt.barh(range(len(top_products)), top_products.values)
plt.yticks(range(len(top_products)), top_products.index)
plt.title('Top 10 Products by Revenue', fontsize=16, fontweight='bold')
plt.xlabel('Revenue ($)')
plt.tight_layout()
plt.show()
return {"success": True, "message": f"Created {chart_type} visualization"}
except Exception as e:
return {"error": str(e)}
# Initialize analyzer
analyzer = DataAnalyzer(df)
print(" Data Analyzer initialized successfully!")
5. OpenAI的函数定义
def get_revenue_summary(period='monthly'):
"""Get revenue summary by time period (daily, weekly, monthly)"""
return analyzer.get_revenue_summary(period)
def get_top_products(limit=10, metric='revenue'):
"""Get top performing products by revenue or quantity"""
return analyzer.get_top_products(limit, metric)
def get_category_performance():
"""Analyze performance metrics by product category"""
return analyzer.get_category_performance()
def get_customer_insights():
"""Get insights about customer behavior and patterns"""
return analyzer.get_customer_insights()
def create_visualization(chart_type, data_params=None):
"""Create visualizations (revenue_trend, category_pie, top_products_bar)"""
return analyzer.create_visualization(chart_type, data_params or {})
def get_basic_stats():
"""Get basic statistics about the dataset"""
return {
"success": True,
"data": {
"total_records": len(analyzer.df),
"date_range": {
"start": str(analyzer.df['date'].min().date()),
"end": str(analyzer.df['date'].max().date())
},
"total_revenue": float(analyzer.df['total_amount'].sum()),
"unique_products": analyzer.df['product_name'].nunique(),
"unique_customers": analyzer.df['customer_id'].nunique(),
"categories": analyzer.df['category'].unique().tolist()
}
}
6. OpenAI函数模式
functions = [
{
"name": "get_revenue_summary",
"description": "Get revenue summary grouped by time period",
"parameters": {
"type": "object",
"properties": {
"period": {
"type": "string",
"enum": ["daily", "weekly", "monthly"],
"description": "Time period for grouping revenue data"
}
},
"required": ["period"]
}
},
{
"name": "get_top_products",
"description": "Get top performing products by revenue or quantity",
"parameters": {
"type": "object",
"properties": {
"limit": {
"type": "integer",
"description": "Number of top products to return (default: 10)"
},
"metric": {
"type": "string",
"enum": ["revenue", "quantity"],
"description": "Metric to rank products by"
}
},
"required": ["metric"]
}
},
{
"name": "get_category_performance",
"description": "Analyze performance metrics by product category including revenue, quantity, and customers",
"parameters": {
"type": "object",
"properties": {}
}
},
{
"name": "get_customer_insights",
"description": "Get insights about customer behavior, spending patterns, and purchase frequency",
"parameters": {
"type": "object",
"properties": {}
}
},
{
"name": "create_visualization",
"description": "Create data visualizations like charts and graphs",
"parameters": {
"type": "object",
"properties": {
"chart_type": {
"type": "string",
"enum": ["revenue_trend", "category_pie", "top_products_bar"],
"description": "Type of chart to create"
},
"data_params": {
"type": "object",
"description": "Additional parameters for the chart"
}
},
"required": ["chart_type"]
}
},
{
"name": "get_basic_stats",
"description": "Get basic statistics and overview of the dataset",
"parameters": {
"type": "object",
"properties": {}
}
}
]
print(" Function schemas defined successfully!")
7. 主要的AI代理类
class DataAnalystAI:
def __init__(self, api_key):
self.client = openai.OpenAI(api_key=api_key)
self.functions = {
"get_revenue_summary": get_revenue_summary,
"get_top_products": get_top_products,
"get_category_performance": get_category_performance,
"get_customer_insights": get_customer_insights,
"create_visualization": create_visualization,
"get_basic_stats": get_basic_stats
}
self.conversation_history = []
def process_query(self, user_query):
"""Process user query and return AI response with function calls"""
try:
# Add user message to conversation
messages = [
{
"role": "system",
"content": """You are a helpful data analyst AI assistant. You can analyze e-commerce sales data and create visualizations.
Always provide clear, actionable insights. When showing numerical data, format it nicely with commas for large numbers.
If you create visualizations, mention that the chart has been displayed.
Be conversational and explain your findings in business terms."""
},
{"role": "user", "content": user_query}
]
# Add conversation history
messages = messages[:-1] + self.conversation_history + messages[-1:]
# Call OpenAI API with function calling
response = self.client.chat.completions.create(
model="gpt-3.5-turbo",
messages=messages,
functions=functions,
function_call="auto",
temperature=0.7
)
message = response.choices[0].message
# Handle function calls
if message.function_call:
function_name = message.function_call.name
function_args = json.loads(message.function_call.arguments)
print(f" Calling function: {function_name} with args: {function_args}")
# Execute the function
function_result = self.functions[function_name](**function_args)
# Get AI's interpretation of the results
messages.append({
"role": "assistant",
"content": None,
"function_call": {
"name": function_name,
"arguments": message.function_call.arguments
}
})
messages.append({
"role": "function",
"name": function_name,
"content": json.dumps(function_result)
})
# Get final response from AI
final_response = self.client.chat.completions.create(
model="gpt-3.5-turbo",
messages=messages,
temperature=0.7
)
ai_response = final_response.choices[0].message.content
# Update conversation history
self.conversation_history.append({"role": "user", "content": user_query})
self.conversation_history.append({"role": "assistant", "content": ai_response})
return ai_response
else:
# No function call needed
ai_response = message.content
self.conversation_history.append({"role": "user", "content": user_query})
self.conversation_history.append({"role": "assistant", "content": ai_response})
return ai_response
except Exception as e:
return f" Error processing query: {str(e)}"
# Initialize the AI agent
ai_agent = DataAnalystAI("your-openai-api-key-here") # Replace with your API key
print(" AI Data Analyst Agent initialized successfully!")
8.交互式查询界面
def ask_ai(query):
"""Simple interface to ask questions to the AI agent"""
print(f" Question: {query}")
print(" AI Response:")
response = ai_agent.process_query(query)
print(response)
print("\n" + "="*80 + "\n")
return response
# Cell 9: Example Queries - Run these to test your agent!
print(" Let's test our AI Data Analyst Agent with some example queries:\n")
# Test basic stats
ask_ai("Give me an overview of our sales data")
# Test revenue analysis
ask_ai("Show me the monthly revenue trend")
# Test product analysis
ask_ai("What are our top 5 products by revenue?")
# Test category performance
ask_ai("How are different product categories performing?")
# Test customer insights
ask_ai("Tell me about our customer behavior patterns")
# Test visualization
ask_ai("Create a pie chart showing revenue distribution by category")
# Test comparative analysis
ask_ai("Which product category generates the highest average order value?")
print(" All tests completed! Your AI Data Analyst Agent is ready to use!")
输出

高级技术与优化
在基础代理到位后,随着时间的推移,我们将进行多项增强:
- 函数链:这些多步骤分析步骤被链接在一起,并由人工智能辅助执行。许多多步骤分析工作流程原本需要人工协调。
- 上下文感知:为代理实现一些上下文管理,以便其跟踪已完成的分析并在此基础上进行构建。这使得对话类似于接听电话。
- 性能优化:缓存高开销的计算,并行执行任何可以独立完成的分析。这通常可以使函数实现更快、更少的内存占用。
- 错误处理:整合全面的错误捕获功能,以便优雅地处理问题。在出现数据问题、API 故障或用户意外输入时尤其有用。也有助于为用户提供合理的反馈。
实际应用和用例
您的数据分析师 AI 代理拥有无限可能:
- 商业智能:提供定期报告,让普通人能够自助分析,并为决策者提供即时洞察。
- 营销分析:使用自然语言查询,查看广告系列效果指标、客户细分和投资回报率 (ROI) 计算。
- 财务分析:监控关键绩效指标 (KPI) 和差异,并使用通俗易懂的语言提问提交财务报告。
- 运营优化:监控性能数据和瓶颈,并基于数据驱动的洞察优化流程。
小结
构建数据分析师 AI 代理不仅仅是一项技术练习——它关乎数据分析的普及,并为所有人提供洞察。您构建的工具或许有助于改变人与数据之间的交互方式,消除障碍,从而基于数据做出决策。您所学到的技术为许多其他 AI 应用奠定了基础。
函数调用是一个用途广泛的概念,可用于从客户服务自动化到复杂的工作流程编排等各种应用。请记住,最好的人工智能并非取代人类智慧,而是对其进行补充。你的数据分析师人工智能应该鼓励用户针对数据提出更深入的问题,激励他们更深入地挖掘和分析数据,并帮助他们做出更明智的决策。因此,关键不在于掌握所有答案,而在于掌握一些答案,以便找到所有其他答案。


评论留言