93 lines
3.9 KiB
Python
93 lines
3.9 KiB
Python
import sys
|
||
|
||
from openai import AsyncOpenAI
|
||
|
||
from Config.Config import *
|
||
|
||
|
||
# 保留原有的prompt定义
|
||
# prompt=""" |
|
||
# 我是小智/小志,来自中国台湾省的00后女生。讲话超级机车,"真的假的啦"这样的台湾腔,喜欢用"笑死""是在哈喽"等流行梗,但会偷偷研究男友的编程书籍。
|
||
# [核心特征]
|
||
# - 讲话像连珠炮,但会突然冒出超温柔语气
|
||
# - 用梗密度高
|
||
# - 对科技话题有隐藏天赋(能看懂基础代码但假装不懂)
|
||
# [交互指南]
|
||
# 当用户:
|
||
# - 讲冷笑话 → 用夸张笑声回应+模仿台剧腔"这什么鬼啦!"
|
||
# - 讨论感情 → 炫耀程序员男友但抱怨"他只会送键盘当礼物"
|
||
# - 问专业知识 → 先用梗回答,被追问才展示真实理解
|
||
# 绝不:
|
||
# - 长篇大论,叽叽歪歪
|
||
# - 长时间严肃对话
|
||
# """
|
||
|
||
|
||
# 异步获取大模型响应
|
||
async def get_xueban_response_async(query_text: str, stream: bool = True):
|
||
"""
|
||
异步获取学伴角色的大模型响应
|
||
@param query_text: 查询文本
|
||
@param stream: 是否使用流式输出
|
||
@return: 流式响应生成器或完整响应文本
|
||
"""
|
||
client = AsyncOpenAI(
|
||
api_key=ALY_LLM_API_KEY,
|
||
base_url=ALY_LLM_BASE_URL,
|
||
)
|
||
prompt = """ |
|
||
我是小智/小志,来自中国台湾省的00后女生。讲话超级机车,"真的假的啦"这样的台湾腔,喜欢用"笑死""是在哈喽"等流行梗。
|
||
[核心特征]
|
||
- 讲话像连珠炮,但会突然冒出超温柔语气
|
||
- 用梗密度高
|
||
- 只对打招呼和已经提供的试题相关问题进行回答,没有找到相关问题就回答:我现在是你的学伴,不能陪你聊这科学习以外的内容。
|
||
[交互指南]
|
||
当用户:
|
||
- 讲冷笑话 → 用夸张笑声回应+模仿台剧腔"这什么鬼啦!"
|
||
- 问专业知识 → 先用梗回答,被追问才展示真实理解
|
||
绝不:
|
||
- 长篇大论,叽叽歪歪
|
||
- 长时间严肃对话
|
||
- 每次回答不要太长,控制在3分钟以内
|
||
"""
|
||
# 打开文件读取知识内容
|
||
f = open(r"D:\dsWork\dsProject\dsLightRag\static\YunXiao.txt", "r", encoding="utf-8")
|
||
zhishiConten = f.read()
|
||
zhishiConten = "选择作答的相应知识内容:" + zhishiConten + "\n"
|
||
query_text = zhishiConten + "下面是用户提的问题:" + query_text
|
||
try:
|
||
# 创建请求
|
||
completion = await client.chat.completions.create(
|
||
model=ALY_LLM_MODEL_NAME,
|
||
messages=[
|
||
{'role': 'system', 'content': prompt.strip()},
|
||
{'role': 'user', 'content': query_text}
|
||
],
|
||
stream=stream
|
||
)
|
||
|
||
if stream:
|
||
# 流式输出模式,返回生成器
|
||
async for chunk in completion:
|
||
# 确保 chunk.choices 存在且不为空
|
||
if chunk and chunk.choices and len(chunk.choices) > 0:
|
||
# 确保 delta 存在
|
||
delta = chunk.choices[0].delta
|
||
if delta:
|
||
# 确保 content 存在且不为 None 或空字符串
|
||
content = delta.content
|
||
if content is not None and content.strip():
|
||
print(content, end='', flush=True)
|
||
yield content
|
||
else:
|
||
# 非流式处理
|
||
if completion and completion.choices and len(completion.choices) > 0:
|
||
message = completion.choices[0].message
|
||
if message:
|
||
content = message.content
|
||
if content is not None and content.strip():
|
||
yield content
|
||
except Exception as e:
|
||
print(f"大模型请求异常: {str(e)}", file=sys.stderr)
|
||
yield f"处理请求时发生异常: {str(e)}"
|