Spaces:
Sleeping
Sleeping
File size: 3,319 Bytes
30fa119 |
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 |
import gradio as gr
import time
from typing import Iterator, List, Tuple, Any
# 模拟流式API响应
def simulate_stream_response(message: str) -> Iterator[str]:
"""模拟API的流式响应"""
response = f"收到您的问题:'{message}'。这是一个模拟的AI助手回答,一个字一个字地流式输出。我正在尝试模仿Claude的回答风格,希望这个演示能够满足您的需求。"
for char in response:
yield char
time.sleep(0.05) # 模拟打字延迟
# 修复后的流式响应函数
def stream_response(message: str, history: List[Tuple[str, str]]) -> Iterator[List[Tuple[str, Any]]]:
"""流式响应并格式化为Gradio Chatbot需要的格式"""
# 添加用户消息到历史
history = history + [(message, "")]
# 流式更新AI的回复
bot_message = ""
response_generator = simulate_stream_response(message)
for token in response_generator:
bot_message += token
# 更新最后一条消息的AI回复部分
updated_history = history.copy()
updated_history[-1] = (message, bot_message)
yield updated_history
# 创建自定义CSS样式
custom_css = """
.gradio-container {
font-family: 'Arial', sans-serif;
}
"""
# 创建Gradio界面
def create_demo():
with gr.Blocks(css=custom_css) as demo:
gr.Markdown("# AI 问答助手")
gr.Markdown("这是一个类似Claude的问答系统,会逐字流式输出回答")
chatbot = gr.Chatbot(
show_label=False,
height=500,
)
with gr.Row():
msg = gr.Textbox(
show_label=False,
placeholder="在这里输入您的问题...",
scale=9
)
submit = gr.Button("发送", scale=1)
with gr.Accordion("示例问题", open=False):
examples = gr.Examples(
examples=[
["材料管道中的数据预处理步骤有哪些?"],
["如何优化材料管道的计算效率?"],
["材料管道中常用的特征工程方法有哪些?"],
["如何在材料管道中整合机器学习模型?"],
["材料管道中的高通量筛选技术有什么优势?"]
],
inputs=msg
)
# 设置提交操作
submit_event = submit.click(
fn=stream_response,
inputs=[msg, chatbot],
outputs=[chatbot],
queue=True
)
# 清空输入框
submit_event.then(
fn=lambda: "",
inputs=None,
outputs=[msg]
)
# 回车键提交
msg.submit(
fn=stream_response,
inputs=[msg, chatbot],
outputs=[chatbot],
queue=True
).then(
fn=lambda: "",
inputs=None,
outputs=[msg]
)
return demo
# 创建演示
demo = create_demo()
# 主函数
if __name__ == "__main__":
demo.queue() # 启用队列处理
demo.launch() # 移除自定义参数,Hugging Face会自动处理
else:
# 用于Hugging Face Spaces部署
demo.queue() |