binary-husky commited on
Commit
e7080e6
2 Parent(s): 43e6478 b0c2e2d

Merge pull request #746 from Rid7/claude

Browse files

接入Claude in Slack服务,暂时不支持历史消息设置(单个slack实例,多人使用请谨慎隐私风险)

config.py CHANGED
@@ -44,9 +44,10 @@ WEB_PORT = -1
44
  # 如果OpenAI不响应(网络卡顿、代理失败、KEY失效),重试的次数限制
45
  MAX_RETRY = 2
46
 
47
- # OpenAI模型选择是(gpt4现在只对申请成功的人开放,体验gpt-4可以试试api2d)
48
  LLM_MODEL = "gpt-3.5-turbo" # 可选 ↓↓↓
49
- AVAIL_LLM_MODELS = ["gpt-3.5-turbo", "api2d-gpt-3.5-turbo", "gpt-4", "api2d-gpt-4", "chatglm", "moss", "newbing"]
 
50
 
51
  # 本地LLM模型如ChatGLM的执行方式 CPU/GPU
52
  LOCAL_MODEL_DEVICE = "cpu" # 可选 "cuda"
@@ -75,3 +76,7 @@ NEWBING_STYLE = "creative" # ["creative", "balanced", "precise"]
75
  NEWBING_COOKIES = """
76
  your bing cookies here
77
  """
 
 
 
 
 
44
  # 如果OpenAI不响应(网络卡顿、代理失败、KEY失效),重试的次数限制
45
  MAX_RETRY = 2
46
 
47
+ # 模型选择是
48
  LLM_MODEL = "gpt-3.5-turbo" # 可选 ↓↓↓
49
+ AVAIL_LLM_MODELS = ["gpt-3.5-turbo", "api2d-gpt-3.5-turbo", "gpt-4", "api2d-gpt-4", "chatglm", "moss", "newbing", "stack-claude"]
50
+ # P.S. 其他可用的模型还包括 ["jittorllms_rwkv", "jittorllms_pangualpha", "jittorllms_llama"]
51
 
52
  # 本地LLM模型如ChatGLM的执行方式 CPU/GPU
53
  LOCAL_MODEL_DEVICE = "cpu" # 可选 "cuda"
 
76
  NEWBING_COOKIES = """
77
  your bing cookies here
78
  """
79
+
80
+ # Slack Claude bot, 使用教程详情见 request_llm/README.md
81
+ SLACK_CLAUDE_BOT_ID = ''
82
+ SLACK_CLAUDE_USER_TOKEN = ''
request_llm/README.md CHANGED
@@ -13,6 +13,31 @@ LLM_MODEL = "chatglm"
13
  `python main.py`
14
  ```
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  ---
18
  ## Text-Generation-UI (TGUI,调试中,暂不可用)
 
13
  `python main.py`
14
  ```
15
 
16
+ ## Claude-Stack
17
+
18
+ - 请参考此教程获取 https://zhuanlan.zhihu.com/p/627485689
19
+ - 1、SLACK_CLAUDE_BOT_ID
20
+ - 2、SLACK_CLAUDE_USER_TOKEN
21
+
22
+ - 把token加入config.py
23
+
24
+ ## Newbing
25
+
26
+ - 使用cookie editor获取cookie(json)
27
+ - 把cookie(json)加入config.py (NEWBING_COOKIES)
28
+
29
+ ## Moss
30
+ - 使用docker-compose
31
+
32
+ ## RWKV
33
+ - 使用docker-compose
34
+
35
+ ## LLAMA
36
+ - 使用docker-compose
37
+
38
+ ## 盘古
39
+ - 使用docker-compose
40
+
41
 
42
  ---
43
  ## Text-Generation-UI (TGUI,调试中,暂不可用)
request_llm/bridge_all.py CHANGED
@@ -130,6 +130,7 @@ model_info = {
130
  "tokenizer": tokenizer_gpt35,
131
  "token_cnt": get_token_num_gpt35,
132
  },
 
133
  }
134
 
135
 
@@ -186,8 +187,20 @@ if "moss" in AVAIL_LLM_MODELS:
186
  "token_cnt": get_token_num_gpt35,
187
  },
188
  })
189
-
190
-
 
 
 
 
 
 
 
 
 
 
 
 
191
 
192
 
193
  def LLM_CATCH_EXCEPTION(f):
 
130
  "tokenizer": tokenizer_gpt35,
131
  "token_cnt": get_token_num_gpt35,
132
  },
133
+
134
  }
135
 
136
 
 
187
  "token_cnt": get_token_num_gpt35,
188
  },
189
  })
190
+ if "stack-claude" in AVAIL_LLM_MODELS:
191
+ from .bridge_stackclaude import predict_no_ui_long_connection as claude_noui
192
+ from .bridge_stackclaude import predict as claude_ui
193
+ # claude
194
+ model_info.update({
195
+ "stack-claude": {
196
+ "fn_with_ui": claude_ui,
197
+ "fn_without_ui": claude_noui,
198
+ "endpoint": None,
199
+ "max_token": 8192,
200
+ "tokenizer": tokenizer_gpt35,
201
+ "token_cnt": get_token_num_gpt35,
202
+ }
203
+ })
204
 
205
 
206
  def LLM_CATCH_EXCEPTION(f):
request_llm/bridge_newbing.py CHANGED
@@ -153,7 +153,7 @@ class NewBingHandle(Process):
153
  # 进入任务等待状态
154
  asyncio.run(self.async_run())
155
  except Exception:
156
- tb_str = '```\n' + trimmed_format_exc() + '```'
157
  self.child.send(f'[Local Message] Newbing失败 {tb_str}.')
158
  self.child.send('[Fail]')
159
  self.child.send('[Finish]')
 
153
  # 进入任务等待状态
154
  asyncio.run(self.async_run())
155
  except Exception:
156
+ tb_str = '\n```\n' + trimmed_format_exc() + '\n```\n'
157
  self.child.send(f'[Local Message] Newbing失败 {tb_str}.')
158
  self.child.send('[Fail]')
159
  self.child.send('[Finish]')
request_llm/bridge_stackclaude.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .bridge_newbing import preprocess_newbing_out, preprocess_newbing_out_simple
2
+ from multiprocessing import Process, Pipe
3
+ from toolbox import update_ui, get_conf, trimmed_format_exc
4
+ import threading
5
+ import importlib
6
+ import logging
7
+ import time
8
+ from toolbox import get_conf
9
+ import asyncio
10
+ load_message = "正在加载Claude组件,请稍候..."
11
+
12
+ try:
13
+ """
14
+ ========================================================================
15
+ 第一部分:Slack API Client
16
+ https://github.com/yokonsan/claude-in-slack-api
17
+ ========================================================================
18
+ """
19
+
20
+ from slack_sdk.errors import SlackApiError
21
+ from slack_sdk.web.async_client import AsyncWebClient
22
+
23
+ class SlackClient(AsyncWebClient):
24
+ """SlackClient类用于与Slack API进行交互,实现消息发送、接收等功能。
25
+
26
+ 属性:
27
+ - CHANNEL_ID:str类型,表示频道ID。
28
+
29
+ 方法:
30
+ - open_channel():异步方法。通过调用conversations_open方法打开一个频道,并将返回的频道ID保存在属性CHANNEL_ID中。
31
+ - chat(text: str):异步方法。向已打开的频道发送一条文本消息。
32
+ - get_slack_messages():异步方法。获取已打开频道的最新消息并返回消息列表,目前不支持历史消息查询。
33
+ - get_reply():异步方法。循环监听已打开频道的消息,如果收到"Typing…_"结尾的消息说明Claude还在继续输出,否则结束循环。
34
+
35
+ """
36
+ CHANNEL_ID = None
37
+
38
+ async def open_channel(self):
39
+ response = await self.conversations_open(users=get_conf('SLACK_CLAUDE_BOT_ID')[0])
40
+ self.CHANNEL_ID = response["channel"]["id"]
41
+
42
+ async def chat(self, text):
43
+ if not self.CHANNEL_ID:
44
+ raise Exception("Channel not found.")
45
+
46
+ resp = await self.chat_postMessage(channel=self.CHANNEL_ID, text=text)
47
+ self.LAST_TS = resp["ts"]
48
+
49
+ async def get_slack_messages(self):
50
+ try:
51
+ # TODO:暂时不支持历史消息,因为在同一个频道里存在多人使用时历史消息渗透问题
52
+ resp = await self.conversations_history(channel=self.CHANNEL_ID, oldest=self.LAST_TS, limit=1)
53
+ msg = [msg for msg in resp["messages"]
54
+ if msg.get("user") == get_conf('SLACK_CLAUDE_BOT_ID')[0]]
55
+ return msg
56
+ except (SlackApiError, KeyError) as e:
57
+ raise RuntimeError(f"获取Slack消息失败。")
58
+
59
+ async def get_reply(self):
60
+ while True:
61
+ slack_msgs = await self.get_slack_messages()
62
+ if len(slack_msgs) == 0:
63
+ await asyncio.sleep(0.5)
64
+ continue
65
+
66
+ msg = slack_msgs[-1]
67
+ if msg["text"].endswith("Typing…_"):
68
+ yield False, msg["text"]
69
+ else:
70
+ yield True, msg["text"]
71
+ break
72
+ except:
73
+ pass
74
+
75
+ """
76
+ ========================================================================
77
+ 第二部分:子进程Worker(调用主体)
78
+ ========================================================================
79
+ """
80
+
81
+
82
+ class ClaudeHandle(Process):
83
+ def __init__(self):
84
+ super().__init__(daemon=True)
85
+ self.parent, self.child = Pipe()
86
+ self.claude_model = None
87
+ self.info = ""
88
+ self.success = True
89
+ self.local_history = []
90
+ self.check_dependency()
91
+ if self.success:
92
+ self.start()
93
+ self.threadLock = threading.Lock()
94
+
95
+ def check_dependency(self):
96
+ try:
97
+ self.success = False
98
+ import slack_sdk
99
+ self.info = "依赖检测通过,等待Claude响应。注意目前不能多人同时调用Claude接口(有线程锁),否则将导致每个人的Claude问询历史互相渗透。调用Claude时,会自动使用已配置的代理。"
100
+ self.success = True
101
+ except:
102
+ self.info = "缺少的依赖,如果要使用Claude,除了基础的pip依赖以外,您还需要运行`pip install -r request_llm/requirements_slackclaude.txt`安装Claude的依赖,然后重启程序。"
103
+ self.success = False
104
+
105
+ def ready(self):
106
+ return self.claude_model is not None
107
+
108
+ async def async_run(self):
109
+ await self.claude_model.open_channel()
110
+ while True:
111
+ # 等待
112
+ kwargs = self.child.recv()
113
+ question = kwargs['query']
114
+ history = kwargs['history']
115
+ # system_prompt=kwargs['system_prompt']
116
+
117
+ # 是否重置
118
+ if len(self.local_history) > 0 and len(history) == 0:
119
+ # await self.claude_model.reset()
120
+ self.local_history = []
121
+
122
+ # 开始问问题
123
+ prompt = ""
124
+ # Slack API最��不要添加系统提示
125
+ # if system_prompt not in self.local_history:
126
+ # self.local_history.append(system_prompt)
127
+ # prompt += system_prompt + '\n'
128
+
129
+ # 追加历史
130
+ for ab in history:
131
+ a, b = ab
132
+ if a not in self.local_history:
133
+ self.local_history.append(a)
134
+ prompt += a + '\n'
135
+ # if b not in self.local_history:
136
+ # self.local_history.append(b)
137
+ # prompt += b + '\n'
138
+
139
+ # 问题
140
+ prompt += question
141
+ self.local_history.append(question)
142
+ print('question:', prompt)
143
+ # 提交
144
+ await self.claude_model.chat(prompt)
145
+ # 获取回复
146
+ # async for final, response in self.claude_model.get_reply():
147
+ # await self.handle_claude_response(final, response)
148
+ async for final, response in self.claude_model.get_reply():
149
+ if not final:
150
+ print(response)
151
+ self.child.send(str(response))
152
+ else:
153
+ # 防止丢失最后一条消息
154
+ slack_msgs = await self.claude_model.get_slack_messages()
155
+ last_msg = slack_msgs[-1]["text"] if slack_msgs and len(slack_msgs) > 0 else ""
156
+ if last_msg:
157
+ self.child.send(last_msg)
158
+ print('-------- receive final ---------')
159
+ self.child.send('[Finish]')
160
+
161
+ def run(self):
162
+ """
163
+ 这个函数运行在子进程
164
+ """
165
+ # 第一次运行,加载参数
166
+ self.success = False
167
+ self.local_history = []
168
+ if (self.claude_model is None) or (not self.success):
169
+ # 代理设置
170
+ proxies, = get_conf('proxies')
171
+ if proxies is None:
172
+ self.proxies_https = None
173
+ else:
174
+ self.proxies_https = proxies['https']
175
+
176
+ try:
177
+ SLACK_CLAUDE_USER_TOKEN, = get_conf('SLACK_CLAUDE_USER_TOKEN')
178
+ self.claude_model = SlackClient(token=SLACK_CLAUDE_USER_TOKEN, proxy=self.proxies_https)
179
+ print('Claude组件初始化成功。')
180
+ except:
181
+ self.success = False
182
+ tb_str = '\n```\n' + trimmed_format_exc() + '\n```\n'
183
+ self.child.send(f'[Local Message] 不能加载Claude组件。{tb_str}')
184
+ self.child.send('[Fail]')
185
+ self.child.send('[Finish]')
186
+ raise RuntimeError(f"不能加载Claude组件。")
187
+
188
+ self.success = True
189
+ try:
190
+ # 进入任务等待状态
191
+ asyncio.run(self.async_run())
192
+ except Exception:
193
+ tb_str = '\n```\n' + trimmed_format_exc() + '\n```\n'
194
+ self.child.send(f'[Local Message] Claude失败 {tb_str}.')
195
+ self.child.send('[Fail]')
196
+ self.child.send('[Finish]')
197
+
198
+ def stream_chat(self, **kwargs):
199
+ """
200
+ 这个函数运行在主进程
201
+ """
202
+ self.threadLock.acquire()
203
+ self.parent.send(kwargs) # 发送请求到子进程
204
+ while True:
205
+ res = self.parent.recv() # 等待Claude回复的片段
206
+ if res == '[Finish]':
207
+ break # 结束
208
+ elif res == '[Fail]':
209
+ self.success = False
210
+ break
211
+ else:
212
+ yield res # Claude回复的片段
213
+ self.threadLock.release()
214
+
215
+
216
+ """
217
+ ========================================================================
218
+ 第三部分:主进程统一调用函数接口
219
+ ========================================================================
220
+ """
221
+ global claude_handle
222
+ claude_handle = None
223
+
224
+
225
+ def predict_no_ui_long_connection(inputs, llm_kwargs, history=[], sys_prompt="", observe_window=None, console_slience=False):
226
+ """
227
+ 多线程方法
228
+ 函数的说明请见 request_llm/bridge_all.py
229
+ """
230
+ global claude_handle
231
+ if (claude_handle is None) or (not claude_handle.success):
232
+ claude_handle = ClaudeHandle()
233
+ observe_window[0] = load_message + "\n\n" + claude_handle.info
234
+ if not claude_handle.success:
235
+ error = claude_handle.info
236
+ claude_handle = None
237
+ raise RuntimeError(error)
238
+
239
+ # 没有 sys_prompt 接口,因此把prompt加入 history
240
+ history_feedin = []
241
+ for i in range(len(history)//2):
242
+ history_feedin.append([history[2*i], history[2*i+1]])
243
+
244
+ watch_dog_patience = 5 # 看门狗 (watchdog) 的耐心, 设置5秒即可
245
+ response = ""
246
+ observe_window[0] = "[Local Message]: 等待Claude响应中 ..."
247
+ for response in claude_handle.stream_chat(query=inputs, history=history_feedin, system_prompt=sys_prompt, max_length=llm_kwargs['max_length'], top_p=llm_kwargs['top_p'], temperature=llm_kwargs['temperature']):
248
+ observe_window[0] = preprocess_newbing_out_simple(response)
249
+ if len(observe_window) >= 2:
250
+ if (time.time()-observe_window[1]) > watch_dog_patience:
251
+ raise RuntimeError("程序终止。")
252
+ return preprocess_newbing_out_simple(response)
253
+
254
+
255
+ def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_prompt='', stream=True, additional_fn=None):
256
+ """
257
+ 单线程方法
258
+ 函数的说明请见 request_llm/bridge_all.py
259
+ """
260
+ chatbot.append((inputs, "[Local Message]: 等待Claude响应中 ..."))
261
+
262
+ global claude_handle
263
+ if (claude_handle is None) or (not claude_handle.success):
264
+ claude_handle = ClaudeHandle()
265
+ chatbot[-1] = (inputs, load_message + "\n\n" + claude_handle.info)
266
+ yield from update_ui(chatbot=chatbot, history=[])
267
+ if not claude_handle.success:
268
+ claude_handle = None
269
+ return
270
+
271
+ if additional_fn is not None:
272
+ import core_functional
273
+ importlib.reload(core_functional) # 热更新prompt
274
+ core_functional = core_functional.get_core_functions()
275
+ if "PreProcess" in core_functional[additional_fn]:
276
+ inputs = core_functional[additional_fn]["PreProcess"](
277
+ inputs) # 获取预处理函数(如果有的话)
278
+ inputs = core_functional[additional_fn]["Prefix"] + \
279
+ inputs + core_functional[additional_fn]["Suffix"]
280
+
281
+ history_feedin = []
282
+ for i in range(len(history)//2):
283
+ history_feedin.append([history[2*i], history[2*i+1]])
284
+
285
+ chatbot[-1] = (inputs, "[Local Message]: 等待Claude响应中 ...")
286
+ response = "[Local Message]: 等待Claude响应中 ..."
287
+ yield from update_ui(chatbot=chatbot, history=history, msg="Claude响应缓慢,尚未完成全部响应,请耐心完成后再提交新问题。")
288
+ for response in claude_handle.stream_chat(query=inputs, history=history_feedin, system_prompt=system_prompt):
289
+ chatbot[-1] = (inputs, preprocess_newbing_out(response))
290
+ yield from update_ui(chatbot=chatbot, history=history, msg="Claude响应缓慢,尚未完成全部响应,请耐心完成后再提交新问题。")
291
+ if response == "[Local Message]: 等待Claude响应中 ...":
292
+ response = "[Local Message]: Claude响应异常,请刷新界面重试 ..."
293
+ history.extend([inputs, response])
294
+ logging.info(f'[raw_input] {inputs}')
295
+ logging.info(f'[response] {response}')
296
+ yield from update_ui(chatbot=chatbot, history=history, msg="完成全部响应,请提交新问题。")
request_llm/requirements_slackclaude.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ slack-sdk==3.21.3