Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import json | |
| import requests | |
| import openai | |
| def chat_with_bot(message, history, system_prompt): | |
| # 构建请求数据 | |
| messages = [] | |
| # 添加系统提示词 | |
| if system_prompt: | |
| messages.append({"role": "system", "content": system_prompt}) | |
| # 添加历史对话 | |
| for human, assistant in history: | |
| messages.append({"role": "user", "content": human}) | |
| messages.append({"role": "assistant", "content": assistant.replace('<br>', '\n')}) | |
| # 添加当前消息 | |
| messages.append({"role": "user", "content": message}) | |
| # 输出这轮的消息输入 | |
| print("Current messages:") | |
| for msg in messages: | |
| print(f"{msg['role']}: {msg['content']}") | |
| # 发送请求 | |
| try: | |
| client = openai.OpenAI( | |
| base_url="https://masterful-torch-2650-5069.east4.casdao.com/v1", | |
| api_key="not_needed" | |
| ) | |
| response = client.chat.completions.create( | |
| messages=messages, | |
| model="customer_model", # 或其他适用的模型 | |
| frequency_penalty=1.05, | |
| temperature=0.7, | |
| top_p=0.8, | |
| max_tokens=1000 | |
| ) | |
| bot_message = response.choices[0].message.content | |
| # 处理所有可能的换行符情况 | |
| bot_message = bot_message.replace('\r\n', '<br>').replace('\\n', '<br>').replace('\n', '<br>').replace('\r', '<br>') | |
| # 输出bot的返回值 | |
| print("Bot response:") | |
| print(f"assistant: {bot_message}") | |
| return bot_message | |
| except Exception as e: | |
| return f"Error: {str(e)}" | |
| # 创建Gradio界面 | |
| with gr.Blocks() as demo: | |
| gr.Markdown("# FlowAsk\n这是一个流程图问答助手") | |
| system_prompt_state = gr.State("") | |
| with gr.Row(): | |
| with gr.Column(): | |
| system_prompt_input = gr.Textbox( | |
| label="系统提示词", | |
| placeholder="请输入系统提示词,用于设定AI助手的行为和角色...", | |
| lines=2, | |
| value="" | |
| ) | |
| def update_prompt(prompt): | |
| system_prompt_state.value = prompt | |
| return prompt | |
| system_prompt_input.change( | |
| fn=update_prompt, | |
| inputs=[system_prompt_input], | |
| outputs=[system_prompt_state] | |
| ) | |
| def chat_wrapper(message, history): | |
| return chat_with_bot(message, history, system_prompt_state.value) | |
| chatbot = gr.ChatInterface( | |
| fn=chat_wrapper, | |
| title="", | |
| description="", | |
| ) | |
| # 启动应用 | |
| if __name__ == "__main__": | |
| demo.launch() |