File size: 6,299 Bytes
eee5b94 71e3d07 eee5b94 71e3d07 537576e 6ca9070 71e3d07 eee5b94 71e3d07 537576e 6ca9070 537576e 6ca9070 537576e 6ca9070 79e69f0 537576e eee5b94 79e69f0 71e3d07 eee5b94 71e3d07 eee5b94 71e3d07 eee5b94 471c532 eee5b94 71e3d07 eee5b94 71e3d07 eee5b94 71e3d07 eee5b94 79e69f0 eee5b94 79e69f0 eee5b94 537576e eee5b94 537576e eee5b94 537576e eee5b94 71e3d07 471c532 71e3d07 92f4fa6 7aa80c0 92f4fa6 eee5b94 92f4fa6 71e3d07 eee5b94 471c532 463a956 471c532 7776b2d eee5b94 471c532 eee5b94 471c532 eee5b94 471c532 eee5b94 71e3d07 eee5b94 471c532 eee5b94 471c532 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 |
import os
import gradio as gr
import aiohttp
import asyncio
import json
from datasets import Dataset, DatasetDict, load_dataset, load_from_disk
from huggingface_hub import HfApi, HfFolder
# 從環境變量中獲取 Hugging Face API 令牌和其他配置
HF_API_TOKEN = os.environ.get("HF_API_TOKEN")
LLM_API = os.environ.get("LLM_API")
LLM_URL = os.environ.get("LLM_URL")
USER_ID = "HuggingFace Space"
DATASET_NAME = os.environ.get("DATASET_NAME")
# 確保令牌不為空
if HF_API_TOKEN is None:
raise ValueError("HF_API_TOKEN 環境變量未設置。請在 Hugging Face Space 的設置中添加該環境變量。")
# 設置 Hugging Face API 令牌
HfFolder.save_token(HF_API_TOKEN)
# 定義數據集特徵
features = {
"user_input": "string",
"response": "string",
"feedback_type": "string",
"improvement": "string"
}
# 加載或創建數據集
try:
dataset = load_dataset(DATASET_NAME)
except:
dataset = DatasetDict({
"feedback": Dataset.from_dict({
"user_input": [],
"response": [],
"feedback_type": [],
"improvement": []
})
})
async def send_chat_message(user_input):
payload = {
"inputs": {},
"query": user_input,
"response_mode": "streaming",
"conversation_id": "",
"user": USER_ID,
}
print("Sending chat message payload:", payload)
async with aiohttp.ClientSession() as session:
try:
async with session.post(
url=f"{LLM_URL}/chat-messages",
headers={"Authorization": f"Bearer {LLM_API}"},
json=payload,
timeout=aiohttp.ClientTimeout(total=60)
) as response:
if response.status != 200:
print(f"Error: {response.status}")
return f"Error: {response.status}"
full_response = []
async for line in response.content:
line = line.decode('utf-8').strip()
if not line:
continue
if "data: " not in line:
continue
try:
data = json.loads(line.split("data: ")[1])
if "answer" in data:
full_response.append(data["answer"])
except (IndexError, json.JSONDecodeError) as e:
print(f"Error parsing line: {line}, error: {e}")
continue
if full_response:
return ''.join(full_response).strip()
else:
return "Error: No response found in the response"
except Exception as e:
print(f"Exception: {e}")
return f"Exception: {e}"
async def handle_input(user_input):
print(f"Handling input: {user_input}")
chat_response = await send_chat_message(user_input)
print("Chat response:", chat_response)
return chat_response
def run_sync(user_input):
print(f"Running sync with input: {user_input}")
return asyncio.run(handle_input(user_input))
def save_feedback(user_input, response, feedback_type, improvement):
feedback = {
"user_input": user_input,
"response": response,
"feedback_type": feedback_type,
"improvement": improvement
}
print(f"Saving feedback: {feedback}")
# Append to the dataset
new_data = {
"user_input": [user_input],
"response": [response],
"feedback_type": [feedback_type],
"improvement": [improvement]
}
global dataset
dataset["feedback"] = dataset["feedback"].add_item(new_data)
dataset.push_to_hub(DATASET_NAME)
def handle_feedback(response, feedback_type, improvement):
# 獲取最新的用戶輸入(假設用戶輸入保存在全局變量中)
global last_user_input
save_feedback(last_user_input, response, feedback_type, improvement)
return "感謝您的反饋!"
def handle_user_input(user_input):
print(f"User input: {user_input}")
global last_user_input
last_user_input = user_input # 保存最新的用戶輸入
return run_sync(user_input)
# 讀取並顯示反饋內容的函數
def show_feedback():
try:
feedbacks = dataset["feedback"].to_pandas().to_dict(orient="records")
return feedbacks
except Exception as e:
return f"Error: {e}"
TITLE = """<h1 align="center">大型語言模型 (LLM) 聊天界面 💬</h1>"""
# 添加示例
examples = [
["AlCoCrFeNi HEA coating 可用怎樣的實驗方法做到 ?"],
["請問high entropy nitride coatings的形成,主要可透過那些元素來讓這個材料形成熱穩定?"]
]
with gr.Blocks() as iface:
gr.HTML(TITLE)
with gr.Row():
chatbot = gr.Chatbot()
with gr.Row():
user_input = gr.Textbox(label='輸入您的問題', placeholder="在此輸入問題...")
submit_button = gr.Button("送出")
gr.Examples(examples=examples, inputs=user_input)
with gr.Row():
like_button = gr.Button("👍")
dislike_button = gr.Button("👎")
improvement_input = gr.Textbox(label='請輸入改進建議', placeholder='請輸入如何改進模型回應的建議')
with gr.Row():
feedback_output = gr.Textbox(label='反饋結果', interactive=False)
with gr.Row():
show_feedback_button = gr.Button("查看所有反饋")
feedback_display = gr.JSON(label='所有反饋')
def chat(user_input, history):
response = handle_user_input(user_input)
history.append((user_input, response))
return history, history
submit_button.click(fn=chat, inputs=[user_input, chatbot], outputs=[chatbot, chatbot])
like_button.click(
fn=lambda response, improvement: handle_feedback(response, "like", improvement),
inputs=[chatbot, improvement_input],
outputs=feedback_output
)
dislike_button.click(
fn=lambda response, improvement: handle_feedback(response, "dislike", improvement),
inputs=[chatbot, improvement_input],
outputs=feedback_output
)
show_feedback_button.click(fn=show_feedback, outputs=feedback_display)
iface.launch()
|