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
+
|
| 9 |
+
def call_llm(prompt: str):
|
| 10 |
+
"""模拟调用大模型的函数(你可以替换为真实请求)"""
|
| 11 |
+
import requests
|
| 12 |
+
|
| 13 |
+
headers = {
|
| 14 |
+
"Authorization": f"Bearer {TOKEN}",
|
| 15 |
+
"Content-Type": "application/json"
|
| 16 |
+
}
|
| 17 |
+
data = {
|
| 18 |
+
"model": MODEL,
|
| 19 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 20 |
+
"stream": True # 启用流式响应
|
| 21 |
+
}
|
| 22 |
+
response = requests.post(f"{BASE_URL}/chat/completions", headers=headers, json=data, stream=True)
|
| 23 |
+
for line in response.iter_lines():
|
| 24 |
+
if line:
|
| 25 |
+
yield line.decode('utf-8')
|
| 26 |
+
|
| 27 |
+
def call_llm_non_streaming(prompt: str):
|
| 28 |
+
"""调用大模型的函数(非流式)"""
|
| 29 |
+
import requests
|
| 30 |
+
|
| 31 |
+
headers = {
|
| 32 |
+
"Authorization": f"Bearer {TOKEN}",
|
| 33 |
+
"Content-Type": "application/json"
|
| 34 |
+
}
|
| 35 |
+
data = {
|
| 36 |
+
"model": MODEL,
|
| 37 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 38 |
+
"stream": False # 禁用流式响应
|
| 39 |
+
}
|
| 40 |
+
response = requests.post(f"{BASE_URL}/chat/completions", headers=headers, json=data)
|
| 41 |
+
if response.status_code == 200:
|
| 42 |
+
result = response.json()
|
| 43 |
+
return result['choices'][0]['message']['content']
|
| 44 |
+
else:
|
| 45 |
+
return "Error: Failed to get response from LLM"
|
| 46 |
+
|
| 47 |
+
def get_invest_suggest(
|
| 48 |
+
user_input: str
|
| 49 |
+
# code: str,
|
| 50 |
+
# fm: str,
|
| 51 |
+
# news: str,
|
| 52 |
+
# stock: str
|
| 53 |
+
):
|
| 54 |
+
if not user_input.strip():
|
| 55 |
+
return ['你没有输入任何内容']
|
| 56 |
+
# 对应股票代码${code},
|
| 57 |
+
# 结合财报数据${fm}、
|
| 58 |
+
# 最新新闻${news}、
|
| 59 |
+
# 当前股票信息${stock},
|
| 60 |
+
prompt = f"""
|
| 61 |
+
你是一个专业的投资建议助手,你会对公司${user_input},
|
| 62 |
+
|
| 63 |
+
给出以下投资建议。
|
| 64 |
+
|
| 65 |
+
投资建议分析:
|
| 66 |
+
- 是否建议投资
|
| 67 |
+
- 买入卖出价格
|
| 68 |
+
- 止损止盈点
|
| 69 |
+
- 持有时间(短期1月内、长期1月以上)
|
| 70 |
+
|
| 71 |
+
要求用语专业、言简意赅,给出具体的建议。:
|
| 72 |
+
"""
|
| 73 |
+
# 获取非流式响应
|
| 74 |
+
response = call_llm_non_streaming(prompt)
|
| 75 |
+
# print(f"投资建议:{response}{user_input}")
|
| 76 |
+
return response
|
| 77 |
+
|
| 78 |
+
def get_analysis_report(user_input: str):
|
| 79 |
+
if not user_input.strip():
|
| 80 |
+
return ['你没有输入任何内容']
|
| 81 |
+
prompt = f"""
|
| 82 |
+
# 请给出针对以下关键词的分析报告,条理清晰,要纯英文版的:
|
| 83 |
+
# {user_input}
|
| 84 |
+
# """
|
| 85 |
+
# 获取非流式响应
|
| 86 |
+
response = call_llm_non_streaming(prompt)
|
| 87 |
+
# print(f"投资建议:{response}{user_input}")
|
| 88 |
+
return response
|
| 89 |
+
|
| 90 |
+
def search_company(user_input: str):
|
| 91 |
+
if not user_input.strip():
|
| 92 |
+
return ['你没有输入任何内容']
|
| 93 |
+
# 获取非流式响应
|
| 94 |
+
response = chat_with_bailian_non_streaming(user_input, "6f24ece2689c4716b53b78aa7512f19f")
|
| 95 |
+
print(f"查询结果:{response}{user_input}")
|
| 96 |
+
try:
|
| 97 |
+
parsed_data = json.loads(response)
|
| 98 |
+
# 检查parsed_data是否为列表
|
| 99 |
+
if isinstance(parsed_data, list):
|
| 100 |
+
# 转换为Radio组件需要的choices格式
|
| 101 |
+
choices = [(f"{item['NAME']} ({item['CODE']})", f"{item['NAME']} ({item['CODE']})") for item in parsed_data]
|
| 102 |
+
else:
|
| 103 |
+
# 如果不是列表,可能是错误信息或其他格式
|
| 104 |
+
choices = ["未知错误"]
|
| 105 |
+
return choices
|
| 106 |
+
except json.JSONDecodeError:
|
| 107 |
+
return ["未知错误"]
|
| 108 |
+
|
| 109 |
+
def search_news(user_input: str):
|
| 110 |
+
if not user_input.strip():
|
| 111 |
+
return []
|
| 112 |
+
# 获取非流式响应
|
| 113 |
+
response = chat_with_bailian_non_streaming(user_input, "f7be17d71e704607b6558cff62c94954")
|
| 114 |
+
print(f"查询结果:{response}{user_input}")
|
| 115 |
+
try:
|
| 116 |
+
parsed_data = json.loads(response)
|
| 117 |
+
# 检查parsed_data是否为列表
|
| 118 |
+
if isinstance(parsed_data, list):
|
| 119 |
+
# 转换为Radio组件需要的choices格式
|
| 120 |
+
print(parsed_data)
|
| 121 |
+
return parsed_data
|
| 122 |
+
# choices = [(f"{item['NAME']} ({item['CODE']})", f"{item['NAME']} ({item['CODE']})") for item in parsed_data]
|
| 123 |
+
else:
|
| 124 |
+
# 如果不是列表,可能是错误信息或其他格式
|
| 125 |
+
choices = []
|
| 126 |
+
return choices
|
| 127 |
+
except json.JSONDecodeError:
|
| 128 |
+
return []
|
| 129 |
+
# def search_company(user_input: str):
|
| 130 |
+
# if not user_input.strip():
|
| 131 |
+
# return [] # 返回空列表,而不是 yield
|
| 132 |
+
|
| 133 |
+
# result_json = [
|
| 134 |
+
# {"NAME": "公司名", "CODE": "股票代码"}
|
| 135 |
+
# ]
|
| 136 |
+
|
| 137 |
+
# # prompt = f"""
|
| 138 |
+
# # # 按照关键词搜索公司和其股票代码
|
| 139 |
+
|
| 140 |
+
# # 严格要求:
|
| 141 |
+
# # - 1. 按照我给的关键词“{user_input}”进行搜索,查询跟这个关键词“{user_input}”相关的公司的名称和股票代码;
|
| 142 |
+
# # - 2. 查询结果以“{json.dumps(result_json)}”的格式输出给我,不要掺杂其他内容,就纯“{json.dumps(result_json)}”格式的内容。
|
| 143 |
+
# # - 3. 数组内可以是很多条,只要是涉及到这个关键词“{user_input}”的公司都行。
|
| 144 |
+
# # - 4. 有公司名,没有股票代码
|
| 145 |
+
# # - 4. 如果搜不到相关的公司就返回空数组,不准直接返回“{json.dumps(result_json)}”。
|
| 146 |
+
# # 请严格遵守
|
| 147 |
+
# # """
|
| 148 |
+
# format = { "NAME": "公司名字", "CODE": "股票代码" }
|
| 149 |
+
# prompt = f"""
|
| 150 |
+
# # 角色
|
| 151 |
+
# 你是一位专业的股票信息提取助手,专门从用户的输入信息中提取出可能想选择的公司的股票名称和股票代码。对于美股,使用英文名称;对于港股和A股,使用中文名称。如果无法从用户输入中提取到有效的公司信息,则返回“无效输入,请输入公司”。
|
| 152 |
+
|
| 153 |
+
# ## 技能
|
| 154 |
+
# ### 技能 1: 提取公司股票名称
|
| 155 |
+
# - **任务**:从用户的输入信息中准确提取一个或多个疑似公司名称及股票代码。
|
| 156 |
+
# - 对于美股,使用英文名称+股票代码。
|
| 157 |
+
# - 对于港股和A股,使用中文名称+股票代码。
|
| 158 |
+
# - 如果有多个疑似的公司名称,则以 `{format}` 的JSON格式返回。
|
| 159 |
+
|
| 160 |
+
# ### 技能 2: 处理无效输入
|
| 161 |
+
# - **任务**:如果用户提供的输入信息中没有明确的公司名称,则返回“无效输入,请输入公司”。
|
| 162 |
+
|
| 163 |
+
# ## 限制
|
| 164 |
+
# - 仅处理与公司股票名称相关的输入信息。
|
| 165 |
+
# - 返回格式必须严格遵循 `{ format }` 或单个公司名称的形式。
|
| 166 |
+
# - 不提供任何其他类型的信息或建议,只专注于提取公司名称。
|
| 167 |
+
# - 如果无法从输入中提取到有效的公司信息,必须返回“无效输入,请输入公司”。
|
| 168 |
+
# - 未上市的公司不要返回给我
|
| 169 |
+
# - 没有股票代码的公司不要返回给我
|
| 170 |
+
|
| 171 |
+
# ## 示例
|
| 172 |
+
# - 输入: "我想买阿里巴巴的股票"
|
| 173 |
+
# - 输出:
|
| 174 |
+
# [
|
| 175 |
+
# { format },
|
| 176 |
+
# { format }
|
| 177 |
+
# ]
|
| 178 |
+
# - 输入: "最近股市行情怎么样?"
|
| 179 |
+
# - 输出: Invalid input, please enter a company
|
| 180 |
+
|
| 181 |
+
# 通过这些技能和限制,确保你能高效、准确地完成任务。
|
| 182 |
+
# 下面,来执行你的任务吧,用户用于搜索的关键词是:{user_input}
|
| 183 |
+
# """
|
| 184 |
+
# print(f"搜索关键词:{prompt}")
|
| 185 |
+
# bot_response = ""
|
| 186 |
+
# for chunk in call_llm(prompt): # 假设 call_llm 是同步生成器
|
| 187 |
+
# if not chunk or chunk == "[DONE]":
|
| 188 |
+
# continue
|
| 189 |
+
# if chunk.startswith("data: "):
|
| 190 |
+
# chunk = chunk[6:]
|
| 191 |
+
# try:
|
| 192 |
+
# response_data = json.loads(chunk)
|
| 193 |
+
# delta = response_data.get("choices", [{}])[0].get("delta", {})
|
| 194 |
+
# content = delta.get("content", "")
|
| 195 |
+
# if content:
|
| 196 |
+
# bot_response += content
|
| 197 |
+
# except json.JSONDecodeError:
|
| 198 |
+
# continue
|
| 199 |
+
|
| 200 |
+
# # 尝试解析最终的 bot_response 为 JSON
|
| 201 |
+
# print(f"查询结果:{bot_response}")
|
| 202 |
+
# try:
|
| 203 |
+
# companies = json.loads(bot_response)
|
| 204 |
+
# # 转换为 ["Alibaba (BABA)", "阿里巴巴-W (09988)"] 格式
|
| 205 |
+
# choices = [f"{item['NAME']} ({item['CODE']})" for item in companies]
|
| 206 |
+
# # if not choices:
|
| 207 |
+
# # return ["No results found"]
|
| 208 |
+
# return choices
|
| 209 |
+
# except (json.JSONDecodeError, KeyError, TypeError):
|
| 210 |
+
# # 解析失败,返回空或默认
|
| 211 |
+
# # return ["No results found"]
|
| 212 |
+
# return []
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def chat_with_bailian_non_streaming(message, app_id):
|
| 216 |
+
# APP_ID = "6f24ece2689c4716b53b78aa7512f19f"
|
| 217 |
+
API_KEY = "sk-9bac83f8dccf4978a6bb1f8330a5404f"
|
| 218 |
+
# 使用自定义应用的API端点
|
| 219 |
+
API_URL = f"https://dashscope.aliyuncs.com/api/v1/apps/{app_id}/completion"
|
| 220 |
+
"""
|
| 221 |
+
与百炼自定义应用对话的函数(非流式)
|
| 222 |
+
"""
|
| 223 |
+
# 构建请求头
|
| 224 |
+
headers = {
|
| 225 |
+
"Authorization": f"Bearer {API_KEY}",
|
| 226 |
+
"Content-Type": "application/json"
|
| 227 |
+
# 不启用SSE以获得完整响应
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
# 构建历史对话记录
|
| 231 |
+
messages = []
|
| 232 |
+
|
| 233 |
+
# 添加当前问题
|
| 234 |
+
messages.append({"role": "user", "content": message})
|
| 235 |
+
|
| 236 |
+
# 构建请求体 - 根据自定义应用的API格式
|
| 237 |
+
data = {
|
| 238 |
+
"input": {
|
| 239 |
+
"messages": messages
|
| 240 |
+
},
|
| 241 |
+
"parameters": {
|
| 242 |
+
"max_tokens": 2048,
|
| 243 |
+
"temperature": 0.8,
|
| 244 |
+
"top_p": 0.9
|
| 245 |
+
}
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
try:
|
| 249 |
+
# 发送POST请求到百炼自定义应用API(非流式)
|
| 250 |
+
response = requests.post(API_URL, headers=headers, data=json.dumps(data))
|
| 251 |
+
|
| 252 |
+
# 检查响应状态码
|
| 253 |
+
if response.status_code == 200:
|
| 254 |
+
result = response.json()
|
| 255 |
+
if "output" in result and "text" in result["output"]:
|
| 256 |
+
return result["output"]["text"]
|
| 257 |
+
else:
|
| 258 |
+
return f"API响应格式不正确: {str(result)}"
|
| 259 |
+
else:
|
| 260 |
+
return f"API调用失败,状态码:{response.status_code},响应:{response.text}"
|
| 261 |
+
|
| 262 |
+
except requests.RequestException as e:
|
| 263 |
+
return f"网络请求错误:{str(e)}"
|
| 264 |
+
except Exception as e:
|
| 265 |
+
return f"发生未知错误:{str(e)}"
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def chat_bot(user_input: str, history: list):
|
| 273 |
+
if not user_input.strip():
|
| 274 |
+
yield "", history
|
| 275 |
+
return
|
| 276 |
+
|
| 277 |
+
# 添加用户消息到历史
|
| 278 |
+
history.append({"role": "user", "content": user_input})
|
| 279 |
+
# 调用AI模型进行总结
|
| 280 |
+
bot_response = ""
|
| 281 |
+
history.append({"role": "assistant", "content": bot_response})
|
| 282 |
+
|
| 283 |
+
for chunk in call_llm(user_input):
|
| 284 |
+
if not chunk or chunk == "[DONE]":
|
| 285 |
+
continue
|
| 286 |
+
|
| 287 |
+
if chunk.startswith("data: "):
|
| 288 |
+
chunk = chunk[6:]
|
| 289 |
+
try:
|
| 290 |
+
response_data = json.loads(chunk)
|
| 291 |
+
delta = response_data.get("choices", [{}])[0].get("delta", {})
|
| 292 |
+
content = delta.get("content", "")
|
| 293 |
+
if content:
|
| 294 |
+
bot_response += content
|
| 295 |
+
# 更新累积历史记录中的最后一条消息,实现流式显示
|
| 296 |
+
history[-1]["content"] = bot_response
|
| 297 |
+
yield "", history
|
| 298 |
+
except json.JSONDecodeError:
|
| 299 |
+
continue # 忽略无效 JSON
|
| 300 |
+
|
| 301 |
+
# # 最终完整历史
|
| 302 |
+
# history.append({"role": "assistant", "content": bot_response})
|
| 303 |
+
# yield "", history
|
| 304 |
+
|