JC321 commited on
Commit
83e5dd0
·
verified ·
1 Parent(s): 34df737

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -7
app.py CHANGED
@@ -2,8 +2,17 @@ import gradio as gr
2
  import requests
3
  import json
4
  import os
 
5
  from huggingface_hub import InferenceClient
6
 
 
 
 
 
 
 
 
 
7
  # ========== MCP 工具简化定义(符合MCP协议标准) ==========
8
  MCP_TOOLS = [
9
  {"type": "function", "function": {"name": "advanced_search_company", "description": "Search US companies", "parameters": {"type": "object", "properties": {"company_input": {"type": "string"}}, "required": ["company_input"]}}},
@@ -36,7 +45,14 @@ print(f"✅ LLM initialized: Qwen/Qwen2.5-72B-Instruct:novita")
36
  print(f"📊 MCP Services: {len(MCP_SERVICES)} services, {len(MCP_TOOLS)} tools")
37
 
38
  # ========== 系统提示词(简化) ==========
39
- SYSTEM_PROMPT = """You are a financial analysis assistant. Use tools to get data on company financials (past 5-year reports), current stock prices, market news, and company news. Provide data-driven insights."""
 
 
 
 
 
 
 
40
 
41
  # ============================================================
42
  # MCP 服务调用核心代码区
@@ -141,7 +157,7 @@ def _call_gradio_api(service_url, tool_name, arguments):
141
  def chatbot_response(message, history):
142
  """AI 助手主函数(流式输出,性能优化)"""
143
  try:
144
- messages = [{"role": "system", "content": SYSTEM_PROMPT}]
145
 
146
  # 添加历史(最近5轮)
147
  if history:
@@ -204,12 +220,28 @@ def chatbot_response(message, history):
204
  # 构建响应前缀(简化版)
205
  response_prefix = ""
206
 
207
- # 显示工具调用(简单文本)
208
  if tool_calls_log:
209
  response_prefix += "**🛠️ Tools Used:**\n\n"
210
- for tool_call in tool_calls_log:
211
- response_prefix += f"- `{tool_call['name']}` {json.dumps(tool_call['arguments'], ensure_ascii=False)}\n"
212
- response_prefix += "\n---\n\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
 
214
  # 流式输出最终答案
215
  yield response_prefix
@@ -255,9 +287,21 @@ with gr.Blocks(title="Financial AI Assistant") as demo:
255
 
256
  # 启动应用
257
  if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
258
  demo.launch(
259
  server_name="0.0.0.0",
260
  server_port=7860,
261
  show_error=True,
262
- ssr_mode=False
 
263
  )
 
2
  import requests
3
  import json
4
  import os
5
+ import warnings
6
  from huggingface_hub import InferenceClient
7
 
8
+ # 抑制 asyncio 警告
9
+ warnings.filterwarnings('ignore', category=DeprecationWarning)
10
+ os.environ['PYTHONWARNINGS'] = 'ignore'
11
+
12
+ # 如果在 GPU 环境但不需要 GPU,禁用 CUDA
13
+ if 'CUDA_VISIBLE_DEVICES' not in os.environ:
14
+ os.environ['CUDA_VISIBLE_DEVICES'] = ''
15
+
16
  # ========== MCP 工具简化定义(符合MCP协议标准) ==========
17
  MCP_TOOLS = [
18
  {"type": "function", "function": {"name": "advanced_search_company", "description": "Search US companies", "parameters": {"type": "object", "properties": {"company_input": {"type": "string"}}, "required": ["company_input"]}}},
 
45
  print(f"📊 MCP Services: {len(MCP_SERVICES)} services, {len(MCP_TOOLS)} tools")
46
 
47
  # ========== 系统提示词(简化) ==========
48
+ from datetime import datetime
49
+
50
+ def get_system_prompt():
51
+ """生成包含当前日期的系统提示词"""
52
+ current_date = datetime.now().strftime("%Y-%m-%d")
53
+ return f"""You are a financial analysis assistant. Use tools to get data on company financials (past 5-year reports), current stock prices, market news, and company news. Provide data-driven insights.
54
+
55
+ IMPORTANT: Today's date is {current_date}. When querying news or time-sensitive data, use recent dates relative to today."""
56
 
57
  # ============================================================
58
  # MCP 服务调用核心代码区
 
157
  def chatbot_response(message, history):
158
  """AI 助手主函数(流式输出,性能优化)"""
159
  try:
160
+ messages = [{"role": "system", "content": get_system_prompt()}]
161
 
162
  # 添加历史(最近5轮)
163
  if history:
 
220
  # 构建响应前缀(简化版)
221
  response_prefix = ""
222
 
223
+ # 显示工具调用(简单文本+可展开输出)
224
  if tool_calls_log:
225
  response_prefix += "**🛠️ Tools Used:**\n\n"
226
+ for idx, tool_call in enumerate(tool_calls_log):
227
+ # 工具名称和输入
228
+ response_prefix += f"**{idx+1}. `{tool_call['name']}`**\n"
229
+ response_prefix += f"- 📥 Input: `{json.dumps(tool_call['arguments'], ensure_ascii=False)}`\n"
230
+
231
+ # 输出(可展开)
232
+ if 'result' in tool_call:
233
+ result_str = json.dumps(tool_call['result'], ensure_ascii=False, indent=2)
234
+ # 截断过长结果
235
+ if len(result_str) > 500:
236
+ result_preview = result_str[:500] + "..."
237
+ else:
238
+ result_preview = result_str
239
+
240
+ response_prefix += f"<details>\n<summary>📤 Output (click to expand)</summary>\n\n```json\n{result_preview}\n```\n</details>\n\n"
241
+ else:
242
+ response_prefix += "\n"
243
+
244
+ response_prefix += "---\n\n"
245
 
246
  # 流式输出最终答案
247
  yield response_prefix
 
287
 
288
  # 启动应用
289
  if __name__ == "__main__":
290
+ import sys
291
+ import asyncio
292
+
293
+ # 修复 asyncio 事件循环问题
294
+ if sys.platform == 'linux':
295
+ try:
296
+ import asyncio
297
+ asyncio.set_event_loop_policy(asyncio.DefaultEventLoopPolicy())
298
+ except:
299
+ pass
300
+
301
  demo.launch(
302
  server_name="0.0.0.0",
303
  server_port=7860,
304
  show_error=True,
305
+ ssr_mode=False,
306
+ quiet=False
307
  )