mirror of
https://github.com/xszyou/Fay.git
synced 2026-03-12 17:51:28 +08:00
chat页面使用”主人“替代默认用户标识;认知不隔离时使用多用户对话上下文 。
This commit is contained in:
@@ -212,6 +212,26 @@ class Content_Db:
|
||||
rows.reverse()
|
||||
return rows
|
||||
|
||||
@synchronized
|
||||
def get_recent_messages_all(self, limit=30):
|
||||
"""获取所有用户的最近消息(不按用户隔离)"""
|
||||
conn = sqlite3.connect("memory/fay.db")
|
||||
conn.text_factory = str
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT type, content, username
|
||||
FROM T_Msg
|
||||
ORDER BY id DESC
|
||||
LIMIT ?
|
||||
""",
|
||||
(limit,),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
conn.close()
|
||||
rows.reverse()
|
||||
return rows
|
||||
|
||||
@synchronized
|
||||
def get_previous_user_message(self, msg_id):
|
||||
conn = sqlite3.connect("memory/fay.db")
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 8.7 KiB After Width: | Height: | Size: 8.7 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 8.7 KiB After Width: | Height: | Size: 8.7 KiB |
@@ -113,8 +113,8 @@
|
||||
</button>
|
||||
<div class="menu" ref="menuContainer">
|
||||
<div class="tag" v-for="user in userList" :key="user[0]" :class="{'selected': selectedUser && selectedUser[0] === user[0]}" @click="selectUser(user)">
|
||||
[[ user[1] ]]
|
||||
</div>
|
||||
[[ user[1] === 'User' ? '主人' : user[1] ]]
|
||||
</div>
|
||||
</div>
|
||||
<button id="nextButton">
|
||||
<img src="{{ url_for('static',filename='images/scrollright.png') }}" alt="向右滑动">
|
||||
|
||||
@@ -1542,33 +1542,73 @@ def question(content, username, observation=None):
|
||||
"请始终以符合以上人设的身份和语气与用户交流。\n\n"
|
||||
)
|
||||
|
||||
# 根据配置决定是否按用户隔离历史消息
|
||||
try:
|
||||
history_records = content_db.new_instance().get_recent_messages_by_user(username=username, limit=30)
|
||||
cfg.load_config()
|
||||
isolate_by_user = cfg.config.get("memory", {}).get("isolate_by_user", False)
|
||||
except Exception:
|
||||
isolate_by_user = False
|
||||
|
||||
try:
|
||||
if isolate_by_user:
|
||||
history_records = content_db.new_instance().get_recent_messages_by_user(username=username, limit=30)
|
||||
else:
|
||||
history_records = content_db.new_instance().get_recent_messages_all(limit=30)
|
||||
except Exception as exc:
|
||||
util.log(1, f"加载历史消息失败: {exc}")
|
||||
history_records = []
|
||||
|
||||
messages_buffer: List[ConversationMessage] = []
|
||||
|
||||
def append_to_buffer(role: str, text_value: str) -> None:
|
||||
if not text_value:
|
||||
return
|
||||
messages_buffer.append({"role": role, "content": text_value})
|
||||
if len(messages_buffer) > 60:
|
||||
del messages_buffer[:-60]
|
||||
if isolate_by_user:
|
||||
# 按用户隔离:使用传统的 user/assistant 角色区分
|
||||
def append_to_buffer(role: str, text_value: str) -> None:
|
||||
if not text_value:
|
||||
return
|
||||
messages_buffer.append({"role": role, "content": text_value})
|
||||
if len(messages_buffer) > 60:
|
||||
del messages_buffer[:-60]
|
||||
|
||||
for msg_type, msg_text in history_records:
|
||||
role = 'assistant'
|
||||
if msg_type and msg_type.lower() in ('member', 'user'):
|
||||
role = 'user'
|
||||
append_to_buffer(role, msg_text)
|
||||
for record in history_records:
|
||||
msg_type, msg_text = record
|
||||
role = 'assistant'
|
||||
if msg_type and msg_type.lower() in ('member', 'user'):
|
||||
role = 'user'
|
||||
append_to_buffer(role, msg_text)
|
||||
|
||||
if (
|
||||
not messages_buffer
|
||||
or messages_buffer[-1]['role'] != 'user'
|
||||
or messages_buffer[-1]['content'] != content
|
||||
):
|
||||
append_to_buffer('user', content)
|
||||
# 检查是否需要添加当前消息
|
||||
if (
|
||||
not messages_buffer
|
||||
or messages_buffer[-1]['role'] != 'user'
|
||||
or messages_buffer[-1]['content'] != content
|
||||
):
|
||||
messages_buffer.append({"role": "user", "content": content})
|
||||
else:
|
||||
# 不隔离:所有消息合并成一个对话文本块
|
||||
history_lines = []
|
||||
for record in history_records:
|
||||
msg_type, msg_text, msg_username = record
|
||||
if not msg_text:
|
||||
continue
|
||||
if msg_type and msg_type.lower() in ('member', 'user'):
|
||||
display_name = "主人" if msg_username == "User" else msg_username
|
||||
history_lines.append(f"{display_name}:{msg_text}")
|
||||
else:
|
||||
history_lines.append(f"Fay:{msg_text}")
|
||||
|
||||
# 添加当前用户消息
|
||||
current_display_name = "主人" if username == "User" else username
|
||||
current_line = f"{current_display_name}:{content}"
|
||||
if not history_lines or history_lines[-1] != current_line:
|
||||
history_lines.append(current_line)
|
||||
|
||||
# 限制历史记录数量
|
||||
if len(history_lines) > 60:
|
||||
history_lines = history_lines[-60:]
|
||||
|
||||
# 合并成一个 user 消息
|
||||
if history_lines:
|
||||
messages_buffer.append({"role": "user", "content": "\n".join(history_lines)})
|
||||
|
||||
messages = [SystemMessage(content=system_prompt), HumanMessage(content=content)]
|
||||
|
||||
|
||||
BIN
readme/chat.png
BIN
readme/chat.png
Binary file not shown.
|
Before Width: | Height: | Size: 82 KiB After Width: | Height: | Size: 83 KiB |
@@ -1,52 +1,52 @@
|
||||
import requests
|
||||
import json
|
||||
|
||||
def test_gpt(prompt):
|
||||
url = 'http://127.0.0.1:5000/v1/chat/completions' # 替换为您的接口地址
|
||||
headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': f'Bearer YOUR_API_KEY', # 如果您的接口需要身份验证
|
||||
}
|
||||
data = {
|
||||
'model': 'fay-streaming',
|
||||
'messages': [
|
||||
{'role': 'user', 'content': prompt}
|
||||
],
|
||||
'stream': True # 启用流式传输
|
||||
}
|
||||
|
||||
response = requests.post(url, headers=headers, data=json.dumps(data), stream=True)
|
||||
|
||||
if response.status_code != 200:
|
||||
print(f"请求失败,状态码:{response.status_code}")
|
||||
print(f"响应内容:{response.text}")
|
||||
return
|
||||
|
||||
# 处理流式响应
|
||||
for line in response.iter_lines(decode_unicode=True):
|
||||
if line:
|
||||
if line.strip() == 'data: [DONE]':
|
||||
print("\n流式传输完成")
|
||||
break
|
||||
# 每一行数据以 'data: ' 开头,去掉这个前缀
|
||||
if line.startswith('data:'):
|
||||
line = line[5:].strip()
|
||||
# 将 JSON 字符串解析为字典
|
||||
try:
|
||||
data = json.loads(line)
|
||||
# 从数据中提取生成的内容
|
||||
choices = data.get('choices')
|
||||
if choices:
|
||||
delta = choices[0].get('delta', {})
|
||||
content = delta.get('content', '')
|
||||
print(content, end='', flush=True)
|
||||
except json.JSONDecodeError:
|
||||
print(f"\n无法解析的 JSON 数据:{line}")
|
||||
else:
|
||||
print(f"\n收到未知格式的数据:{line}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
user_input = "你好"
|
||||
print("GPT 的回复:")
|
||||
test_gpt(user_input)
|
||||
print("\n请求完成")
|
||||
import requests
|
||||
import json
|
||||
|
||||
def test_gpt(prompt):
|
||||
url = 'http://127.0.0.1:5000/v1/chat/completions' # 替换为您的接口地址
|
||||
headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': f'Bearer YOUR_API_KEY', # 如果您的接口需要身份验证
|
||||
}
|
||||
data = {
|
||||
'model': 'fay-streaming',
|
||||
'messages': [
|
||||
{'role': '张三', 'content': prompt}
|
||||
],
|
||||
'stream': True # 启用流式传输
|
||||
}
|
||||
|
||||
response = requests.post(url, headers=headers, data=json.dumps(data), stream=True)
|
||||
|
||||
if response.status_code != 200:
|
||||
print(f"请求失败,状态码:{response.status_code}")
|
||||
print(f"响应内容:{response.text}")
|
||||
return
|
||||
|
||||
# 处理流式响应
|
||||
for line in response.iter_lines(decode_unicode=True):
|
||||
if line:
|
||||
if line.strip() == 'data: [DONE]':
|
||||
print("\n流式传输完成")
|
||||
break
|
||||
# 每一行数据以 'data: ' 开头,去掉这个前缀
|
||||
if line.startswith('data:'):
|
||||
line = line[5:].strip()
|
||||
# 将 JSON 字符串解析为字典
|
||||
try:
|
||||
data = json.loads(line)
|
||||
# 从数据中提取生成的内容
|
||||
choices = data.get('choices')
|
||||
if choices:
|
||||
delta = choices[0].get('delta', {})
|
||||
content = delta.get('content', '')
|
||||
print(content, end='', flush=True)
|
||||
except json.JSONDecodeError:
|
||||
print(f"\n无法解析的 JSON 数据:{line}")
|
||||
else:
|
||||
print(f"\n收到未知格式的数据:{line}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
user_input = "你好"
|
||||
print("GPT 的回复:")
|
||||
test_gpt(user_input)
|
||||
print("\n请求完成")
|
||||
|
||||
Reference in New Issue
Block a user