Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
from typing import Optional, Dict
|
| 4 |
+
import aiohttp
|
| 5 |
+
import chainlit as cl
|
| 6 |
+
import chainlit.data as cl_data
|
| 7 |
+
import requests
|
| 8 |
+
from fastgpt_data import FastgptDataLayer, now, share_id, app_name, welcome_text
|
| 9 |
+
|
| 10 |
+
fastgpt_base_url = os.getenv("FASTGPT_BASE_URL")
|
| 11 |
+
fastgpt_api_key = os.getenv("FASTGPT_API_KEY")
|
| 12 |
+
fastgpt_api_detail = os.getenv("FASTGPT_API_DETAIL", False)
|
| 13 |
+
|
| 14 |
+
cl_data._data_layer = FastgptDataLayer()
|
| 15 |
+
cl.config.ui.name = app_name
|
| 16 |
+
|
| 17 |
+
def download_logo():
|
| 18 |
+
local_filename = "./public/favicon.svg"
|
| 19 |
+
directory = os.path.dirname(local_filename)
|
| 20 |
+
os.makedirs(directory, exist_ok=True)
|
| 21 |
+
# Streaming, so we can iterate over the response.
|
| 22 |
+
with requests.get(f"{fastgpt_base_url}/icon/logo.svg", stream=True) as r:
|
| 23 |
+
r.raise_for_status() # Check if the request was successful
|
| 24 |
+
with open(local_filename, 'wb') as f:
|
| 25 |
+
for chunk in r.iter_content(chunk_size=8192):
|
| 26 |
+
# If you have chunk encoded response uncomment if
|
| 27 |
+
# and set chunk_size parameter to None.
|
| 28 |
+
f.write(chunk)
|
| 29 |
+
|
| 30 |
+
download_logo()
|
| 31 |
+
|
| 32 |
+
@cl.on_chat_start
|
| 33 |
+
async def chat_start():
|
| 34 |
+
if welcome_text:
|
| 35 |
+
# elements = [cl.Text(content=welcomeText, display="inline")]
|
| 36 |
+
await cl.Message(content=welcome_text).send()
|
| 37 |
+
|
| 38 |
+
@cl.on_message
|
| 39 |
+
async def handle_message(message: cl.Message):
|
| 40 |
+
msg = cl.Message(content="")
|
| 41 |
+
url = f"{fastgpt_base_url}/api/v1/chat/completions"
|
| 42 |
+
print('message.thread_id', message.thread_id)
|
| 43 |
+
headers = {
|
| 44 |
+
"Authorization": f"Bearer {fastgpt_api_key}",
|
| 45 |
+
"Content-Type": "application/json"
|
| 46 |
+
}
|
| 47 |
+
data = {
|
| 48 |
+
"messages": [{"role": "user", "content": message.content}],
|
| 49 |
+
"variables": {"cTime": now},
|
| 50 |
+
"responseChatItemId": message.uiltin.id,
|
| 51 |
+
"shareId": share_id,
|
| 52 |
+
"chatId": message.thread_id,
|
| 53 |
+
"appType": "advanced",
|
| 54 |
+
"outLinkUid": cl.context.session.user.identifier,
|
| 55 |
+
"detail": fastgpt_api_detail,
|
| 56 |
+
"stream": True
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
async for data in fetch_sse(url, headers=headers, data=json.dumps(data), detail=fastgpt_api_detail):
|
| 60 |
+
delta = data['choices'][0]['delta']
|
| 61 |
+
if delta:
|
| 62 |
+
await msg.stream_token(delta['content'])
|
| 63 |
+
await msg.send()
|
| 64 |
+
|
| 65 |
+
@cl.header_auth_callback
|
| 66 |
+
def header_auth_callback(headers: Dict) -> Optional[cl.User]:
|
| 67 |
+
print(headers)
|
| 68 |
+
# 创建一个md5 hash对象
|
| 69 |
+
md5_hash = hashlib.md5()
|
| 70 |
+
user_agent_bytes = headers.get('user-agent').encode('utf-8')
|
| 71 |
+
# 更新这个hash对象的内容
|
| 72 |
+
md5_hash.update(user_agent_bytes)
|
| 73 |
+
# 获取md5哈希值的十六进制表示形式
|
| 74 |
+
md5_hex_digest = md5_hash.hexdigest()
|
| 75 |
+
out_link_uid = md5_hex_digest
|
| 76 |
+
print("MD5加密后的结果:", md5_hex_digest)
|
| 77 |
+
return cl.User(identifier=out_link_uid, display_name="visitor")
|
| 78 |
+
|
| 79 |
+
@cl.on_chat_resume
|
| 80 |
+
async def on_chat_resume():
|
| 81 |
+
pass
|
| 82 |
+
|
| 83 |
+
async def fetch_sse(url, headers, data, detail):
|
| 84 |
+
async with aiohttp.ClientSession() as session:
|
| 85 |
+
async with session.post(url, headers=headers, data=data) as response:
|
| 86 |
+
async for line in response.content:
|
| 87 |
+
if line: # 过滤掉空行
|
| 88 |
+
data = line.decode('utf-8').rstrip('\n\r')
|
| 89 |
+
# print(f"Received: {data}")
|
| 90 |
+
# 检查是否为数据行,并且是我们感兴趣的事件类型
|
| 91 |
+
if detail:
|
| 92 |
+
if data.startswith('event:'):
|
| 93 |
+
event_type = data.split(':', 1)[1].strip() # 提取事件类型
|
| 94 |
+
elif data.startswith('data:') and event_type == 'flowNodeStatus':
|
| 95 |
+
data = data.split(':', 1)[1].strip()
|
| 96 |
+
flowNodeStatus = json.loads(data)
|
| 97 |
+
current_step = cl.context.current_step
|
| 98 |
+
current_step.name = flowNodeStatus['name']
|
| 99 |
+
elif data.startswith('data:') and event_type == 'answer':
|
| 100 |
+
data = data.split(':', 1)[1].strip() # 提取数据内容
|
| 101 |
+
# 如果数据包含换行符,可能需要进一步处理(这取决于你的具体需求)
|
| 102 |
+
# 这里我们简单地打印出来
|
| 103 |
+
if data != '[DONE]':
|
| 104 |
+
yield json.loads(data)
|
| 105 |
+
else:
|
| 106 |
+
if data.startswith('data:'):
|
| 107 |
+
data = data.split(':', 1)[1].strip() # 提取数据内容
|
| 108 |
+
# 如果数据包含换行符,可能需要进一步处理(这取决于你的具体需求)
|
| 109 |
+
# 这里我们简单地打印出来
|
| 110 |
+
if data != '[DONE]':
|
| 111 |
+
yield json.loads(data)
|