Rename app.py to analyze_corporate_finance.py

#537
by AtmanLi - opened
Files changed (2) hide show
  1. analyze_corporate_finance.py +475 -0
  2. app.py +0 -69
analyze_corporate_finance.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
2
+ import datetime
3
+ import requests
4
+ import pytz
5
+ import yaml
6
+ import pandas as pd
7
+ import matplotlib.pyplot as plt
8
+ import seaborn as sns
9
+ import numpy as np
10
+ from datetime import datetime, timedelta
11
+ from typing import Dict, List, Optional, Tuple
12
+ import io
13
+ import base64
14
+ from enum import Enum
15
+ from tools.final_answer import FinalAnswerTool
16
+ from Gradio_UI import GradioUI
17
+
18
+ # 基础工具定义
19
+ @tool
20
+ def my_custom_tool(arg1: str, arg2: int) -> str:
21
+ """A tool that does nothing yet
22
+ Args:
23
+ arg1: the first argument
24
+ arg2: the second argument
25
+ """
26
+ return "What magic will you build ?"
27
+
28
+ @tool
29
+ def get_current_time_in_timezone(timezone: str) -> str:
30
+ """A tool that fetches the current local time in a specified timezone.
31
+ Args:
32
+ timezone: A string representing a valid timezone (e.g., 'America/New_York').
33
+ """
34
+ try:
35
+ tz = pytz.timezone(timezone)
36
+ local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
37
+ return f"The current local time in {timezone} is: {local_time}"
38
+ except Exception as e:
39
+ return f"Error fetching time for timezone '{timezone}': {str(e)}"
40
+
41
+ # 公司收支数据分析工具
42
+ class AnalysisType(Enum):
43
+ OVERVIEW = "overview"
44
+ TREND = "trend"
45
+ CATEGORY = "category"
46
+ BUDGET = "budget"
47
+ CASH_FLOW = "cash_flow"
48
+ DEPARTMENT = "department"
49
+
50
+ @tool
51
+ def analyze_corporate_finance(data_source: str,
52
+ analysis_type: str = "overview",
53
+ period: Optional[str] = None,
54
+ department: Optional[str] = None,
55
+ export_format: str = "text") -> str:
56
+ """
57
+ 公司收支数据分析工具 - 专业财务分析系统
58
+
59
+ Args:
60
+ data_source: 数据源路径(CSV/Excel)或JSON格式的财务数据
61
+ analysis_type: 分析类型 - overview, trend, category, budget, cash_flow, department
62
+ period: 时间周期筛选,如 '2024-Q1:2024-Q4' 或 'last_12_months'
63
+ department: 部门筛选,如 '销售部', '技术部'
64
+ export_format: 输出格式 - text, detailed, visual
65
+ """
66
+ try:
67
+ # 加载和预处理数据
68
+ df = load_financial_data(data_source)
69
+ df = preprocess_financial_data(df)
70
+
71
+ # 应用筛选条件
72
+ df = apply_filters(df, period, department)
73
+
74
+ if len(df) == 0:
75
+ return "没有找到符合条件的数据,请检查筛选条件"
76
+
77
+ # 执行分析
78
+ if analysis_type == AnalysisType.OVERVIEW.value:
79
+ result = generate_financial_overview(df)
80
+ elif analysis_type == AnalysisType.TREND.value:
81
+ result = analyze_financial_trends(df)
82
+ elif analysis_type == AnalysisType.CATEGORY.value:
83
+ result = analyze_category_performance(df)
84
+ elif analysis_type == AnalysisType.BUDGET.value:
85
+ result = analyze_budget_variance(df)
86
+ elif analysis_type == AnalysisType.CASH_FLOW.value:
87
+ result = analyze_cash_flow(df)
88
+ elif analysis_type == AnalysisType.DEPARTMENT.value:
89
+ result = analyze_department_performance(df)
90
+ else:
91
+ return "不支持的分析类型,请选择: overview, trend, category, budget, cash_flow, department"
92
+
93
+ # 根据输出格式调整结果
94
+ if export_format == "visual":
95
+ chart_url = generate_financial_charts(df, analysis_type)
96
+ return f"{result}\n\n![财务分析图表]({chart_url})"
97
+ elif export_format == "detailed":
98
+ return generate_detailed_report(df, analysis_type)
99
+ else:
100
+ return result
101
+
102
+ except Exception as e:
103
+ return f"财务分析过程中出现错误: {str(e)}"
104
+
105
+ def load_financial_data(data_source: str) -> pd.DataFrame:
106
+ """加载财务数据,支持多种格式"""
107
+ try:
108
+ if data_source.endswith('.csv'):
109
+ return pd.read_csv(data_source)
110
+ elif data_source.endswith(('.xlsx', '.xls')):
111
+ return pd.read_excel(data_source)
112
+ else:
113
+ # 尝试解析为JSON
114
+ return pd.read_json(io.StringIO(data_source))
115
+ except Exception as e:
116
+ raise Exception(f"数据加载失败: {str(e)}")
117
+
118
+ def preprocess_financial_data(df: pd.DataFrame) -> pd.DataFrame:
119
+ """财务数据清洗和预处理"""
120
+ # 基本列名标准化
121
+ column_mapping = {
122
+ '日期': 'date', '时间': 'date', '交易日期': 'date',
123
+ '金额': 'amount', '收支金额': 'amount', '交易金额': 'amount',
124
+ '类型': 'type', '收支类型': 'type', '交易类型': 'type',
125
+ '类别': 'category', '分类': 'category', '收支类别': 'category',
126
+ '部门': 'department', '所属部门': 'department'
127
+ }
128
+
129
+ df.columns = [column_mapping.get(col, col) for col in df.columns]
130
+
131
+ # 确保必要列存在
132
+ required_columns = ['date', 'amount', 'type']
133
+ for col in required_columns:
134
+ if col not in df.columns:
135
+ raise Exception(f"缺少必要列: {col}")
136
+
137
+ # 日期处理
138
+ df['date'] = pd.to_datetime(df['date'], errors='coerce')
139
+ df = df.dropna(subset=['date'])
140
+
141
+ # 数值处理
142
+ df['amount'] = pd.to_numeric(df['amount'], errors='coerce')
143
+ df['amount'] = df['amount'].fillna(0)
144
+
145
+ # 分类字段处理
146
+ if 'category' not in df.columns:
147
+ df['category'] = '未分类'
148
+ else:
149
+ df['category'] = df['category'].fillna('未分类')
150
+
151
+ if 'department' not in df.columns:
152
+ df['department'] = '通用部门'
153
+ else:
154
+ df['department'] = df['department'].fillna('通用部门')
155
+
156
+ # 添加时间维度
157
+ df['year'] = df['date'].dt.year
158
+ df['month'] = df['date'].dt.month
159
+ df['quarter'] = df['date'].dt.quarter
160
+ df['year_month'] = df['date'].dt.to_period('M')
161
+ df['day_of_week'] = df['date'].dt.day_name()
162
+
163
+ return df
164
+
165
+ def apply_filters(df: pd.DataFrame, period: Optional[str],
166
+ department: Optional[str]) -> pd.DataFrame:
167
+ """应用时间和部门筛选"""
168
+ if period:
169
+ if period == 'last_12_months':
170
+ cutoff_date = datetime.now() - timedelta(days=365)
171
+ df = df[df['date'] >= cutoff_date]
172
+ elif ':' in period:
173
+ start_str, end_str = period.split(':')
174
+ start_date = pd.to_datetime(start_str)
175
+ end_date = pd.to_datetime(end_str)
176
+ df = df[(df['date'] >= start_date) & (df['date'] <= end_date)]
177
+
178
+ if department:
179
+ df = df[df['department'] == department]
180
+
181
+ return df
182
+
183
+ def generate_financial_overview(df: pd.DataFrame) -> str:
184
+ """生成财务概览报告"""
185
+ total_income = df[df['type'] == '收入']['amount'].sum()
186
+ total_expense = df[df['type'] == '支出']['amount'].sum()
187
+ net_profit = total_income - total_expense
188
+
189
+ # 基本统计
190
+ total_transactions = len(df)
191
+ avg_transaction_amount = df['amount'].mean()
192
+
193
+ # 时间范围
194
+ date_range = f"{df['date'].min().strftime('%Y-%m-%d')} 至 {df['date'].max().strftime('%Y-%m-%d')}"
195
+
196
+ # 部门统计
197
+ dept_stats = df.groupby('department').agg({
198
+ 'amount': ['sum', 'count']
199
+ }).round(2)
200
+
201
+ overview = f"""
202
+ 🏢 **公司财务概览报告**
203
+ **分析时间范围:** {date_range}
204
+
205
+ 📊 **核心财务指标:**
206
+ • 总收入: ¥{total_income:,.2f}
207
+ • 总支出: ¥{total_expense:,.2f}
208
+ • 净利润: ¥{net_profit:,.2f}
209
+ • 利润率: {net_profit/total_income*100 if total_income > 0 else 0:.1f}%
210
+
211
+ 📈 **交易统计:**
212
+ • 总交易笔数: {total_transactions}笔
213
+ • 平均交易金额: ¥{avg_transaction_amount:,.2f}
214
+ • 收入交易: {len(df[df['type'] == '收入'])}笔
215
+ • 支出交易: {len(df[df['type'] == '支出'])}笔
216
+
217
+ 👥 **部门贡献概览:**
218
+ {dept_stats.to_string()}
219
+ """
220
+
221
+ return overview
222
+
223
+ def analyze_financial_trends(df: pd.DataFrame) -> str:
224
+ """分析财务趋势"""
225
+ # 月度趋势分析
226
+ monthly_data = df.groupby('year_month').agg({
227
+ 'amount': ['sum', 'count', 'mean']
228
+ }).round(2)
229
+
230
+ # 收入支出对比
231
+ monthly_breakdown = df.groupby(['year_month', 'type'])['amount'].sum().unstack(fill_value=0)
232
+ monthly_breakdown['净利润'] = monthly_breakdown.get('收入', 0) - monthly_breakdown.get('支出', 0)
233
+
234
+ trend_analysis = f"""
235
+ 📈 **财务趋势分析报告**
236
+
237
+ 📅 **月度趋势指标:**
238
+ {monthly_data.to_string()}
239
+
240
+ 💰 **收入支出对比:**
241
+ {monthly_breakdown.to_string()}
242
+
243
+ 🔍 **趋势洞察:**
244
+ • 月均交易额: ¥{monthly_data[('amount', 'sum')].mean():,.2f}
245
+ • 月均交易笔数: {monthly_data[('amount', 'count')].mean():.0f}
246
+ • 增长趋势: {'上升' if monthly_breakdown['净利润'].iloc[-1] > monthly_breakdown['净利润'].iloc[0] else '平稳'}
247
+ """
248
+
249
+ return trend_analysis
250
+
251
+ def analyze_category_performance(df: pd.DataFrame) -> str:
252
+ """分析收支类别绩效"""
253
+ category_stats = df.groupby(['category', 'type']).agg({
254
+ 'amount': ['sum', 'count', 'mean']
255
+ }).round(2)
256
+
257
+ category_stats.columns = ['总金额', '交易笔数', '平均金额']
258
+ category_stats = category_stats.reset_index()
259
+
260
+ # Top类别分析
261
+ top_income = category_stats[category_stats['type'] == '收入'].nlargest(5, '总金额')
262
+ top_expense = category_stats[category_stats['type'] == '支出'].nlargest(5, '总金额')
263
+
264
+ category_analysis = f"""
265
+ 🏷️ **收支类别绩效分析**
266
+
267
+ 📊 **Top 5 收入类别:**
268
+ {top_income[['category', '总金额', '交易笔数']].to_string(index=False)}
269
+
270
+ 📊 **Top 5 支出类别:**
271
+ {top_expense[['category', '总金额', '交易笔数']].to_string(index=False)}
272
+
273
+ 💡 **效率指标:**
274
+ • 收入集中度: 前3类别占比 {top_income['总金额'].head(3).sum()/category_stats[category_stats['type']=='收入']['总金额'].sum()*100:.1f}%
275
+ • 支出集中度: 前3类别占比 {top_expense['总金额'].head(3).sum()/category_stats[category_stats['type']=='支出']['总金额'].sum()*100:.1f}%
276
+ """
277
+
278
+ return category_analysis
279
+
280
+ def analyze_budget_variance(df: pd.DataFrame) -> str:
281
+ """分析预算执行情况"""
282
+ # 这里使用模拟预算数据,实际应用中应该从数据库或配置文件中获取
283
+ budget_data = {
284
+ '销售收入': 1000000,
285
+ '技术服务': 500000,
286
+ '人力成本': 400000,
287
+ '营销费用': 200000,
288
+ '研发支出': 300000,
289
+ '行政管理': 150000
290
+ }
291
+
292
+ variance_report = "💰 **预算执行分析报告**\n\n"
293
+
294
+ actual_income = df[df['type'] == '收入'].groupby('category')['amount'].sum()
295
+ actual_expense = df[df['type'] == '支出'].groupby('category')['amount'].sum()
296
+
297
+ for category, budget in budget_data.items():
298
+ if category in actual_income.index:
299
+ actual = actual_income[category]
300
+ variance = (actual - budget) / budget * 100
301
+ status = "✅ 超额完成" if variance >= 0 else "⚠️ 未达预算"
302
+ variance_report += f"• {category}: 实际¥{actual:,.0f} / 预算¥{budget:,.0f} ({variance:+.1f}%) {status}\n"
303
+ elif category in actual_expense.index:
304
+ actual = actual_expense[category]
305
+ variance = (actual - budget) / budget * 100
306
+ status = "⚠️ 超预算" if variance > 0 else "✅ 预算内"
307
+ variance_report += f"• {category}: 实际¥{actual:,.0f} / 预算¥{budget:,.0f} ({variance:+.1f}%) {status}\n"
308
+
309
+ return variance_report
310
+
311
+ def analyze_cash_flow(df: pd.DataFrame) -> str:
312
+ """分析现金流状况"""
313
+ monthly_cash_flow = df.groupby('year_month').apply(
314
+ lambda x: x[x['type'] == '收入']['amount'].sum() -
315
+ x[x['type'] == '支出']['amount'].sum()
316
+ )
317
+
318
+ cash_flow_analysis = f"""
319
+ 💳 **现金流分析报告**
320
+
321
+ 📊 **现金流指标:**
322
+ • 月均现金流: ¥{monthly_cash_flow.mean():,.2f}
323
+ • 现金流波动率: {monthly_cash_flow.std():.2f}
324
+ • 正现金流月份: {(monthly_cash_flow > 0).sum()}个月
325
+ • 负现金流月份: {(monthly_cash_flow < 0).sum()}个月
326
+
327
+ 🔔 **现金流健康状况:**
328
+ {generate_cash_flow_health_assessment(monthly_cash_flow)}
329
+ """
330
+
331
+ return cash_flow_analysis
332
+
333
+ def analyze_department_performance(df: pd.DataFrame) -> str:
334
+ """部门绩效分析"""
335
+ dept_performance = df.groupby('department').agg({
336
+ 'amount': ['sum', 'count', 'mean']
337
+ }).round(2)
338
+
339
+ dept_performance.columns = ['总金额', '交易笔数', '平均金额']
340
+
341
+ # 部门贡献分析
342
+ dept_income = df[df['type'] == '收入'].groupby('department')['amount'].sum()
343
+ dept_expense = df[df['type'] == '支出'].groupby('department')['amount'].sum()
344
+
345
+ dept_analysis = f"""
346
+ 👥 **部门绩效分析报告**
347
+
348
+ 📊 **各部门财务表现:**
349
+ {dept_performance.to_string()}
350
+
351
+ 🎯 **部门贡献分析:**
352
+ • 收入Top部门: {dept_income.nlargest(3).to_string()}
353
+ • 支出Top部门: {dept_expense.nlargest(3).to_string()}
354
+ • 净收益最佳部门: {(dept_income - dept_expense).nlargest(3).to_string()}
355
+ """
356
+
357
+ return dept_analysis
358
+
359
+ def generate_financial_charts(df: pd.DataFrame, analysis_type: str) -> str:
360
+ """生成财务分析图表"""
361
+ plt.figure(figsize=(12, 8))
362
+
363
+ if analysis_type == AnalysisType.OVERVIEW.value:
364
+ # 收支趋势图
365
+ monthly_data = df.groupby(['year_month', 'type'])['amount'].sum().unstack()
366
+ monthly_data.plot(kind='line', ax=plt.gca())
367
+ plt.title('月度收支趋势')
368
+ plt.xticks(rotation=45)
369
+
370
+ elif analysis_type == AnalysisType.CATEGORY.value:
371
+ # 类别分布图
372
+ category_totals = df.groupby('category')['amount'].sum().nlargest(8)
373
+ plt.pie(category_totals.values, labels=category_totals.index, autopct='%1.1f%%')
374
+ plt.title('消费类别分布')
375
+
376
+ plt.tight_layout()
377
+
378
+ # 转换为base64编码图像
379
+ img_buffer = io.BytesIO()
380
+ plt.savefig(img_buffer, format='png', bbox_inches='tight')
381
+ img_buffer.seek(0)
382
+ img_str = base64.b64encode(img_buffer.read()).decode()
383
+
384
+ return f"data:image/png;base64,{img_str}"
385
+
386
+ def generate_detailed_report(df: pd.DataFrame, analysis_type: str) -> str:
387
+ """生成详细分析报告"""
388
+ base_report = ""
389
+ if analysis_type == AnalysisType.OVERVIEW.value:
390
+ base_report = generate_financial_overview(df)
391
+ # 其他类型的详细报告...
392
+
393
+ detailed_stats = f"""
394
+ 📋 **详细统计数据:**
395
+
396
+ 📈 **描述性统计:**
397
+ {df['amount'].describe().to_string()}
398
+
399
+ 📅 **时间范围统计:**
400
+ • 最早交易: {df['date'].min().strftime('%Y-%m-%d')}
401
+ • 最晚交易: {df['date'].max().strftime('%Y-%m-%d')}
402
+ • 分析天数: {(df['date'].max() - df['date'].min()).days}天
403
+ """
404
+
405
+ return base_report + detailed_stats
406
+
407
+ def generate_cash_flow_health_assessment(monthly_cash_flow: pd.Series) -> str:
408
+ """生成现金流健康评估"""
409
+ negative_months = (monthly_cash_flow < 0).sum()
410
+ total_months = len(monthly_cash_flow)
411
+
412
+ if negative_months == 0:
413
+ return "🟢 优秀: 所有月份均为正现金流,财务状况非常健康"
414
+ elif negative_months <= total_months * 0.25:
415
+ return "🟡 良好: 少数月份出现负现金流,整体状况良好"
416
+ elif negative_months <= total_months * 0.5:
417
+ return "🟠 一般: 较多月份出现负现金流,需要关注资金管理"
418
+ else:
419
+ return "🔴 风险: 大部分月份为负现金流,存在资金风险"
420
+
421
+ # 快速财务检查工具
422
+ @tool
423
+ def quick_financial_check(file_path: str) -> str:
424
+ """快速财务健康检查工具"""
425
+ try:
426
+ df = load_financial_data(file_path)
427
+ df = preprocess_financial_data(df)
428
+
429
+ overview = generate_financial_overview(df)
430
+ cash_flow = analyze_cash_flow(df)
431
+
432
+ return f"{overview}\n\n{cash_flow}"
433
+ except Exception as e:
434
+ return f"快速检查失败: {str(e)}"
435
+
436
+ # 初始化其他工具
437
+ final_answer = FinalAnswerTool()
438
+
439
+ # 配置模型
440
+ model = HfApiModel(
441
+ max_tokens=2096,
442
+ temperature=0.5,
443
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
444
+ custom_role_conversions=None,
445
+ )
446
+
447
+ # 加载其他工具
448
+ image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
449
+
450
+ # 加载提示模板
451
+ with open("prompts.yaml", 'r') as stream:
452
+ prompt_templates = yaml.safe_load(stream)
453
+
454
+ # 创建代理并集成所有工具
455
+ agent = CodeAgent(
456
+ model=model,
457
+ tools=[
458
+ final_answer,
459
+ analyze_corporate_finance, # 公司财务分析工具
460
+ quick_financial_check, # 快速检查工具
461
+ image_generation_tool,
462
+ get_current_time_in_timezone,
463
+ my_custom_tool
464
+ ],
465
+ max_steps=12, # 增加步骤限制以支持复杂分析
466
+ verbosity_level=1,
467
+ grammar=None,
468
+ planning_interval=None,
469
+ name="Corporate Finance Analyst Pro",
470
+ description="专业的企业财务分析AI助手,支持多维度收支数据分析和可视化",
471
+ prompt_templates=prompt_templates
472
+ )
473
+
474
+ # 启动Gradio界面
475
+ GradioUI(agent).launch()
app.py DELETED
@@ -1,69 +0,0 @@
1
- from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
2
- import datetime
3
- import requests
4
- import pytz
5
- import yaml
6
- from tools.final_answer import FinalAnswerTool
7
-
8
- from Gradio_UI import GradioUI
9
-
10
- # Below is an example of a tool that does nothing. Amaze us with your creativity !
11
- @tool
12
- def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
13
- #Keep this format for the description / args / args description but feel free to modify the tool
14
- """A tool that does nothing yet
15
- Args:
16
- arg1: the first argument
17
- arg2: the second argument
18
- """
19
- return "What magic will you build ?"
20
-
21
- @tool
22
- def get_current_time_in_timezone(timezone: str) -> str:
23
- """A tool that fetches the current local time in a specified timezone.
24
- Args:
25
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
26
- """
27
- try:
28
- # Create timezone object
29
- tz = pytz.timezone(timezone)
30
- # Get current time in that timezone
31
- local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
32
- return f"The current local time in {timezone} is: {local_time}"
33
- except Exception as e:
34
- return f"Error fetching time for timezone '{timezone}': {str(e)}"
35
-
36
-
37
- final_answer = FinalAnswerTool()
38
-
39
- # If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
40
- # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
41
-
42
- model = HfApiModel(
43
- max_tokens=2096,
44
- temperature=0.5,
45
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
46
- custom_role_conversions=None,
47
- )
48
-
49
-
50
- # Import tool from Hub
51
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
52
-
53
- with open("prompts.yaml", 'r') as stream:
54
- prompt_templates = yaml.safe_load(stream)
55
-
56
- agent = CodeAgent(
57
- model=model,
58
- tools=[final_answer], ## add your tools here (don't remove final answer)
59
- max_steps=6,
60
- verbosity_level=1,
61
- grammar=None,
62
- planning_interval=None,
63
- name=None,
64
- description=None,
65
- prompt_templates=prompt_templates
66
- )
67
-
68
-
69
- GradioUI(agent).launch()