drsai 0.5.6__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. drsai-0.5.6/PKG-INFO +313 -0
  2. drsai-0.5.6/README.md +279 -0
  3. drsai-0.5.6/drsai/__init__.py +141 -0
  4. drsai-0.5.6/drsai/backend/__init__.py +0 -0
  5. drsai-0.5.6/drsai/backend/app_worker.py +194 -0
  6. drsai-0.5.6/drsai/backend/owebui_pipeline/__init__.py +0 -0
  7. drsai-0.5.6/drsai/backend/owebui_pipeline/api.py +16 -0
  8. drsai-0.5.6/drsai/backend/owebui_pipeline/pipelines/__init__.py +0 -0
  9. drsai-0.5.6/drsai/backend/owebui_pipeline/pipelines/blueprints/__init__.py +0 -0
  10. drsai-0.5.6/drsai/backend/owebui_pipeline/pipelines/blueprints/function_calling_blueprint.py +173 -0
  11. drsai-0.5.6/drsai/backend/owebui_pipeline/pipelines/config.py +20 -0
  12. drsai-0.5.6/drsai/backend/owebui_pipeline/pipelines/main.py +793 -0
  13. drsai-0.5.6/drsai/backend/owebui_pipeline/pipelines/schemas.py +31 -0
  14. drsai-0.5.6/drsai/backend/owebui_pipeline/pipelines/utils/__init__.py +0 -0
  15. drsai-0.5.6/drsai/backend/owebui_pipeline/pipelines/utils/pipelines/__init__.py +0 -0
  16. drsai-0.5.6/drsai/backend/owebui_pipeline/pipelines/utils/pipelines/auth.py +65 -0
  17. drsai-0.5.6/drsai/backend/owebui_pipeline/pipelines/utils/pipelines/main.py +153 -0
  18. drsai-0.5.6/drsai/backend/owebui_pipeline/pipelines/utils/pipelines/misc.py +35 -0
  19. drsai-0.5.6/drsai/backend/run.py +338 -0
  20. drsai-0.5.6/drsai/configs/__init__.py +3 -0
  21. drsai-0.5.6/drsai/configs/constant.py +43 -0
  22. drsai-0.5.6/drsai/dr_sai.py +468 -0
  23. drsai-0.5.6/drsai/modules/__init__.py +0 -0
  24. drsai-0.5.6/drsai/modules/baseagent/__init__.py +0 -0
  25. drsai-0.5.6/drsai/modules/baseagent/drsaiagent.py +384 -0
  26. drsai-0.5.6/drsai/modules/baseagent/toolagent.py +204 -0
  27. drsai-0.5.6/drsai/modules/components/LLMClient.py +360 -0
  28. drsai-0.5.6/drsai/modules/components/__init__.py +0 -0
  29. drsai-0.5.6/drsai/modules/components/tools/__init__.py +0 -0
  30. drsai-0.5.6/drsai/modules/components/tools/mcps_std.py +13 -0
  31. drsai-0.5.6/drsai/modules/groupchat/__init__.py +0 -0
  32. drsai-0.5.6/drsai/modules/groupchat/_base_group_chat.py +142 -0
  33. drsai-0.5.6/drsai/modules/groupchat/_round_robin_group_chat.py +249 -0
  34. drsai-0.5.6/drsai/modules/groupchat/_selector_group_chat.py +62 -0
  35. drsai-0.5.6/drsai/modules/groupchat/_swarm_group_chat.py +34 -0
  36. drsai-0.5.6/drsai/modules/managers/__init__.py +0 -0
  37. drsai-0.5.6/drsai/modules/managers/assistants_manager.py +253 -0
  38. drsai-0.5.6/drsai/modules/managers/base_assistant.py +170 -0
  39. drsai-0.5.6/drsai/modules/managers/base_pages.py +16 -0
  40. drsai-0.5.6/drsai/modules/managers/base_run.py +171 -0
  41. drsai-0.5.6/drsai/modules/managers/base_run_step.py +84 -0
  42. drsai-0.5.6/drsai/modules/managers/base_thread.py +124 -0
  43. drsai-0.5.6/drsai/modules/managers/base_thread_message.py +314 -0
  44. drsai-0.5.6/drsai/modules/managers/threads_manager.py +597 -0
  45. drsai-0.5.6/drsai/utils/__init__.py +3 -0
  46. drsai-0.5.6/drsai/utils/async_process.py +15 -0
  47. drsai-0.5.6/drsai/utils/base_json_saver.py +176 -0
  48. drsai-0.5.6/drsai/utils/event_collector.py +162 -0
  49. drsai-0.5.6/drsai/utils/fastapi2tools.py +259 -0
  50. drsai-0.5.6/drsai/utils/logger.py +80 -0
  51. drsai-0.5.6/drsai/utils/message_convert.py +48 -0
  52. drsai-0.5.6/drsai/utils/oai_stream_event.py +54 -0
  53. drsai-0.5.6/drsai/version.py +6 -0
  54. drsai-0.5.6/drsai.egg-info/PKG-INFO +313 -0
  55. drsai-0.5.6/drsai.egg-info/SOURCES.txt +58 -0
  56. drsai-0.5.6/drsai.egg-info/dependency_links.txt +1 -0
  57. drsai-0.5.6/drsai.egg-info/requires.txt +12 -0
  58. drsai-0.5.6/drsai.egg-info/top_level.txt +1 -0
  59. drsai-0.5.6/setup.cfg +4 -0
  60. drsai-0.5.6/setup.py +71 -0
drsai-0.5.6/PKG-INFO ADDED
@@ -0,0 +1,313 @@
1
+ Metadata-Version: 2.2
2
+ Name: drsai
3
+ Version: 0.5.6
4
+ Summary: A development framework for single and multi-agent collaborative systems developed by the Dr.Sai team at the IHEP, CAS.
5
+ Home-page: https://code.ihep.ac.cn/hepai/drsai/
6
+ Author: hepai
7
+ Author-email: xiongdb@ihep.ac.cn
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ Requires-Dist: hepai==1.1.34
14
+ Requires-Dist: autogen-agentchat==0.5.5
15
+ Requires-Dist: autogen-core==0.5.5
16
+ Requires-Dist: autogen-ext==0.5.5
17
+ Requires-Dist: schedule==1.2.2
18
+ Requires-Dist: tiktoken==0.9.0
19
+ Requires-Dist: passlib==1.7.4
20
+ Requires-Dist: jwt==1.3.1
21
+ Requires-Dist: aiohttp==3.11.11
22
+ Requires-Dist: mcp==1.4.1
23
+ Requires-Dist: python-multipart==0.0.18
24
+ Requires-Dist: json_schema_to_pydantic==0.2.4
25
+ Dynamic: author
26
+ Dynamic: author-email
27
+ Dynamic: classifier
28
+ Dynamic: description
29
+ Dynamic: description-content-type
30
+ Dynamic: home-page
31
+ Dynamic: requires-dist
32
+ Dynamic: requires-python
33
+ Dynamic: summary
34
+
35
+ # OpenDrSai
36
+
37
+ 由高能物理研究所Dr.Sai团队开发的智能体与多智能体协同系统快速开发框架,可快速地开发和部署自己的智能体与多智能体协作系统后端服务。
38
+
39
+ <div align="center">
40
+ <p>
41
+ <img width="80%" src="assets/drsai.png" alt="适配逻辑图">
42
+ </p>
43
+ </div>
44
+
45
+ ## 1.特色
46
+
47
+ - 1.可基于[HepAI平台](https://ai.ihep.ac.cn/)进行智能体基座模型的灵活切换。
48
+ - 2.为智能体设计了感知、思考、记忆、执行等行为功能,并进行了插件化设计,可灵活扩展,满足多种应用场景。
49
+ - 3.为智能体和多智能体协作系统交互提供了兼容OpenAI Chat和OpenAI ASSISTANTS(**正在开发**)的标准后端接口,可与兼容OpenAI输出的前端进行无缝对接,从而可将智能体和多智能体协作系统作为模型或智能体服务进行部署。
50
+
51
+ ## 2.快速开始
52
+
53
+ ### 2.1.安装OpenDrSai
54
+
55
+ #### pip 安装
56
+
57
+ ```shell
58
+ conda create -n drsai python=>3.11
59
+ conda activate drsai
60
+ pip install drsai -U
61
+ ```
62
+
63
+ #### 从源码安装和配置OpenDrSai运行环境
64
+
65
+ 创建[code.ihep.ac.cn](https://code.ihep.ac.cn/)账号,克隆OpenDrSai仓库到本地:
66
+ ```shell
67
+ git clone https://code.ihep.ac.cn/hepai/drsai.git drsai
68
+ cd drsai
69
+ ```
70
+
71
+ 配置conda环境,安装依赖包:
72
+ ```shell
73
+ conda create -n drsai python>=3.11
74
+ conda activate drsai
75
+ pip install -e . # 以开发者模式安装,任何仓库内的修改会直接生效 ,无需重新安装。
76
+ ```
77
+
78
+ #### 配置HepAI平台的API访问密钥
79
+
80
+ 配置[HepAI](https://ai.ihep.ac.cn)DDF2平台的API访问密钥等环境变量(Based on bash):
81
+
82
+ linux/mac平台:
83
+ ```shell
84
+ vi ~/.bashrc
85
+ export HEPAI_API_KEY=your_api_key
86
+ source ~/.bashrc
87
+ ```
88
+ windows平台:
89
+ ```shell
90
+ setx "HEPAI_API_KEY" "your_api_key"
91
+ # 注意 windows环境变量需要重启电脑才会生效
92
+ ```
93
+
94
+ ### 2.2.创建一个可以使用函数作为工具的简单智能体
95
+
96
+ ```python
97
+ from drsai import AssistantAgent, HepAIChatCompletionClient
98
+ import os
99
+ import asyncio
100
+
101
+ # 创建一个工厂函数,用于并发访问时确保后端使用的Agent实例是隔离的。
102
+ def create_agent() -> AssistantAgent:
103
+
104
+ # Define a model client. You can use other model client that implements
105
+ # the `ChatCompletionClient` interface.
106
+ model_client = HepAIChatCompletionClient(
107
+ model="openai/gpt-4o",
108
+ api_key=os.environ.get("HEPAI_API_KEY"),
109
+ # base_url = "http://192.168.32.148:42601/apiv2"
110
+ )
111
+
112
+ # Define a simple function tool that the agent can use.
113
+ # For this example, we use a fake weather tool for demonstration purposes.
114
+ async def get_weather(city: str) -> str:
115
+ """Get the weather for a given city."""
116
+ return f"The weather in {city} is 73 degrees and Sunny."
117
+
118
+ # Define an AssistantAgent with the model, tool, system message, and reflection enabled.
119
+ # The system message instructs the agent via natural language.
120
+ return AssistantAgent(
121
+ name="weather_agent",
122
+ model_client=model_client,
123
+ tools=[get_weather],
124
+ system_message="You are a helpful assistant.",
125
+ reflect_on_tool_use=False,
126
+ model_client_stream=True, # Enable streaming tokens from the model client.
127
+ )
128
+
129
+ from drsai import run_console
130
+ asyncio.run(run_console(agent_factory=create_agent, task="What is the weather in New York?"))
131
+ ```
132
+
133
+ ## 3.自定义智能体开发案例
134
+
135
+ ### 3.1.使用简单的RAG函数作为智能体的记忆层
136
+
137
+ ```python
138
+ from drsai import AssistantAgent, HepAIChatCompletionClient, LLMMessage, CancellationToken
139
+
140
+ import os
141
+ import asyncio
142
+ from typing import List, Dict, Union
143
+
144
+ # 创建一个工厂函数,用于并发访问时确保后端使用的Agent实例是隔离的。
145
+ def create_agent() -> AssistantAgent:
146
+
147
+ # Define a model client. You can use other model client that implements
148
+ # the `ChatCompletionClient` interface.
149
+ model_client = HepAIChatCompletionClient(
150
+ model="openai/gpt-4o",
151
+ # api_key=os.environ.get("HEPAI_API_KEY"),
152
+ )
153
+
154
+ # Define a simple rag-demo for the assistant.
155
+ async def rag_demo(
156
+ oai_messages: List[Dict],
157
+ llm_messages: List[LLMMessage],
158
+ model_client: HepAIChatCompletionClient,
159
+ cancellation_token: CancellationToken,
160
+ agent_name: str,
161
+ **kwargs):
162
+ query = oai_messages[-1]["content"] # Select the last message of the chat history as the RAG query statement.
163
+ retrieve_txt = "1. Humans will be destroyed by AI in 2050;\n2. Humans are destroyed by AI due to their arrogance and conceit."
164
+ last_txt = f"""The following are some reference materials, and you must refer to these materials to answer the question:\n{retrieve_txt}. My question is: {query}"""
165
+ oai_messages[-1]["content"] = last_txt
166
+ return oai_messages
167
+
168
+ # Define an AssistantAgent with the model, tool, system message, and reflection enabled.
169
+ # The system message instructs the agent via natural language.
170
+ return AssistantAgent(
171
+ name="weather_agent",
172
+ model_client=model_client,
173
+ memory_function=rag_demo,
174
+ system_message="You are a helpful assistant.",
175
+ reflect_on_tool_use=False,
176
+ model_client_stream=True, # Enable streaming tokens from the model client.
177
+ )
178
+
179
+ from drsai import run_console
180
+ asyncio.run(run_console(agent_factory=create_agent, task="Why will humans be destroyed"))
181
+ ```
182
+
183
+ ### 3.2.自定义智能体的回复逻辑
184
+
185
+ ```python
186
+
187
+ from drsai import AssistantAgent, HepAIChatCompletionClient
188
+ import os
189
+ import asyncio
190
+ from autogen_core import CancellationToken
191
+ from autogen_core.tools import BaseTool
192
+ from autogen_core.models import (
193
+ LLMMessage,
194
+ ChatCompletionClient,
195
+ )
196
+ from typing import List, Dict, Any, Union, AsyncGenerator
197
+
198
+ # 创建一个工厂函数,用于并发访问时确保后端使用的Agent实例是隔离的。
199
+ def create_agent() -> AssistantAgent:
200
+
201
+ # Define a model client. You can use other model client that implements
202
+ # the `ChatCompletionClient` interface.
203
+ model_client = HepAIChatCompletionClient(
204
+ model="openai/gpt-4o",
205
+ # api_key=os.environ.get("HEPAI_API_KEY"),
206
+ )
207
+
208
+ # Address the messages and return the response. Must accept messages and return a string, or a generator of strings.
209
+ async def interface(
210
+ oai_messages: List[str], # OAI messages
211
+ agent_name: str, # Agent name
212
+ llm_messages: List[LLMMessage], # AutoGen LLM messages
213
+ model_client: ChatCompletionClient, # AutoGen LLM Model client
214
+ tools: List[BaseTool[Any, Any]], # AutoGen tools
215
+ cancellation_token: CancellationToken, # AutoGen cancellation token,
216
+ **kwargs) -> Union[str, AsyncGenerator[str, None]]:
217
+ """Address the messages and return the response."""
218
+ yield "test_worker reply"
219
+
220
+
221
+ # Define an AssistantAgent with the model, tool, system message, and reflection enabled.
222
+ # The system message instructs the agent via natural language.
223
+ return AssistantAgent(
224
+ name="weather_agent",
225
+ model_client=model_client,
226
+ reply_function=interface,
227
+ system_message="You are a helpful assistant.",
228
+ reflect_on_tool_use=False
229
+ )
230
+
231
+ from drsai import run_console
232
+ asyncio.run(run_console(agent_factory=create_agent, task="Why will humans be destroyed"))
233
+ ```
234
+
235
+ ## 4.将OpenDrSai部署为OpenAI格式的后端模型服务或者HepAI woker服务
236
+
237
+ ### 4.1.部署为OpenAI格式的后端模型服务/HepAI worker服务
238
+ ```python
239
+ from drsai import run_backend, run_hepai_worker
240
+ import asyncio
241
+ asyncio.run(run_backend(agent_factory=create_agent)) # 部署为OpenAI格式的后端模型服务
242
+ # asyncio.run(run_hepai_worker(agent_factory=create_agent)) # 部署为HepAI worker服务
243
+ ```
244
+ 后端默认启动在```http://localhost:42801/apiv2```, 通过```port```参数可自定义端口
245
+
246
+ ### 4.2.使用HepAI client访问的方式访问定制好的智能体
247
+
248
+ ```python
249
+ from hepai import HepAI
250
+ import os
251
+ import json
252
+ import requests
253
+ import sys
254
+
255
+ HEPAI_API_KEY = os.getenv("HEPAI_API_KEY")
256
+ base_url = "http://localhost:42801/apiv2"
257
+
258
+
259
+ # 调用HepAI client接口
260
+ client = HepAI(api_key=HEPAI_API_KEY, base_url=base_url)
261
+ completion = client.chat.completions.create(
262
+ model='hepai/Dr-Sai',
263
+ messages=[
264
+ {"role": "user", "content": "What is the weather in New York?"}
265
+ ],
266
+ stream=True
267
+ )
268
+ for chunk in completion:
269
+ if chunk.choices[0].delta.content:
270
+ print(chunk.choices[0].delta.content, end='', flush=True)
271
+ print('\n')
272
+ ```
273
+
274
+ ## 5.OpenWebUI Pipeline接入
275
+
276
+ ### 5.1.启动包含OpenWebUI Pipeline的OpenDrSai服务
277
+
278
+ ```python
279
+ asyncio.run(run_backend(agent_factory=create_agent, enable_openwebui_pipeline=True))
280
+ ```
281
+
282
+ 后端默认启动在```http://localhost:42801/apiv2```, 通过```port```参数可自定义端口;OpenWebUI Pipeline默认启动在```http://localhost:42801/pipelines```
283
+
284
+ ### 5.2.安装OpenWebUI
285
+
286
+ ```shell
287
+ pip install open-webui
288
+ ```
289
+
290
+ **设置HuggingFace镜像:**
291
+ 将HuggingFace镜像:'HF_ENDPOINT '= 'https://hf-mirror.com'加入到本地的环境。对于Linux系统,可以将其加入到~/.bashrc文件中:
292
+ ```export HF_ENDPOINT=https://hf-mirror.com```
293
+
294
+ 在命令行中运行:```open-webui serve --port 8088```启动OpenWebUI服务。
295
+
296
+ ### 5.3.配置OpenWebUI Pipeline
297
+
298
+ pipeline的密钥在```drsai/backend/pipelines/config.py```中,默认为:```0p3n-w3bu!```,将密钥和pipeline后端服务的地址:```http://localhost:42801/pipelines```加入OpenWebUI的```管理员面板-设置-外部连接-管理OpenAI API连接```中。
299
+
300
+ ### 5.4.自定义Pipeline
301
+
302
+ 将OpenDrSai项目中的```drsai/backend/owebui_pipeline/pipelines/pipelines/drsai_pipeline.py```复制到在自定义文件夹下,进行自定义修改,设置环境变量```PIPELINES_DIR```,让OpenWebUI Pipeline加载自定义的pipeline文件。
303
+
304
+ ## 6.详细文档
305
+ 见docs目录:
306
+ ```shell
307
+ 开发中
308
+ ```
309
+
310
+ ## 7.联系我们
311
+
312
+ - 邮箱:hepai@ihep.ac.cn/xiongdb@ihep.ac.cn
313
+ - 微信:xiongdongbo_12138
drsai-0.5.6/README.md ADDED
@@ -0,0 +1,279 @@
1
+ # OpenDrSai
2
+
3
+ 由高能物理研究所Dr.Sai团队开发的智能体与多智能体协同系统快速开发框架,可快速地开发和部署自己的智能体与多智能体协作系统后端服务。
4
+
5
+ <div align="center">
6
+ <p>
7
+ <img width="80%" src="assets/drsai.png" alt="适配逻辑图">
8
+ </p>
9
+ </div>
10
+
11
+ ## 1.特色
12
+
13
+ - 1.可基于[HepAI平台](https://ai.ihep.ac.cn/)进行智能体基座模型的灵活切换。
14
+ - 2.为智能体设计了感知、思考、记忆、执行等行为功能,并进行了插件化设计,可灵活扩展,满足多种应用场景。
15
+ - 3.为智能体和多智能体协作系统交互提供了兼容OpenAI Chat和OpenAI ASSISTANTS(**正在开发**)的标准后端接口,可与兼容OpenAI输出的前端进行无缝对接,从而可将智能体和多智能体协作系统作为模型或智能体服务进行部署。
16
+
17
+ ## 2.快速开始
18
+
19
+ ### 2.1.安装OpenDrSai
20
+
21
+ #### pip 安装
22
+
23
+ ```shell
24
+ conda create -n drsai python=>3.11
25
+ conda activate drsai
26
+ pip install drsai -U
27
+ ```
28
+
29
+ #### 从源码安装和配置OpenDrSai运行环境
30
+
31
+ 创建[code.ihep.ac.cn](https://code.ihep.ac.cn/)账号,克隆OpenDrSai仓库到本地:
32
+ ```shell
33
+ git clone https://code.ihep.ac.cn/hepai/drsai.git drsai
34
+ cd drsai
35
+ ```
36
+
37
+ 配置conda环境,安装依赖包:
38
+ ```shell
39
+ conda create -n drsai python>=3.11
40
+ conda activate drsai
41
+ pip install -e . # 以开发者模式安装,任何仓库内的修改会直接生效 ,无需重新安装。
42
+ ```
43
+
44
+ #### 配置HepAI平台的API访问密钥
45
+
46
+ 配置[HepAI](https://ai.ihep.ac.cn)DDF2平台的API访问密钥等环境变量(Based on bash):
47
+
48
+ linux/mac平台:
49
+ ```shell
50
+ vi ~/.bashrc
51
+ export HEPAI_API_KEY=your_api_key
52
+ source ~/.bashrc
53
+ ```
54
+ windows平台:
55
+ ```shell
56
+ setx "HEPAI_API_KEY" "your_api_key"
57
+ # 注意 windows环境变量需要重启电脑才会生效
58
+ ```
59
+
60
+ ### 2.2.创建一个可以使用函数作为工具的简单智能体
61
+
62
+ ```python
63
+ from drsai import AssistantAgent, HepAIChatCompletionClient
64
+ import os
65
+ import asyncio
66
+
67
+ # 创建一个工厂函数,用于并发访问时确保后端使用的Agent实例是隔离的。
68
+ def create_agent() -> AssistantAgent:
69
+
70
+ # Define a model client. You can use other model client that implements
71
+ # the `ChatCompletionClient` interface.
72
+ model_client = HepAIChatCompletionClient(
73
+ model="openai/gpt-4o",
74
+ api_key=os.environ.get("HEPAI_API_KEY"),
75
+ # base_url = "http://192.168.32.148:42601/apiv2"
76
+ )
77
+
78
+ # Define a simple function tool that the agent can use.
79
+ # For this example, we use a fake weather tool for demonstration purposes.
80
+ async def get_weather(city: str) -> str:
81
+ """Get the weather for a given city."""
82
+ return f"The weather in {city} is 73 degrees and Sunny."
83
+
84
+ # Define an AssistantAgent with the model, tool, system message, and reflection enabled.
85
+ # The system message instructs the agent via natural language.
86
+ return AssistantAgent(
87
+ name="weather_agent",
88
+ model_client=model_client,
89
+ tools=[get_weather],
90
+ system_message="You are a helpful assistant.",
91
+ reflect_on_tool_use=False,
92
+ model_client_stream=True, # Enable streaming tokens from the model client.
93
+ )
94
+
95
+ from drsai import run_console
96
+ asyncio.run(run_console(agent_factory=create_agent, task="What is the weather in New York?"))
97
+ ```
98
+
99
+ ## 3.自定义智能体开发案例
100
+
101
+ ### 3.1.使用简单的RAG函数作为智能体的记忆层
102
+
103
+ ```python
104
+ from drsai import AssistantAgent, HepAIChatCompletionClient, LLMMessage, CancellationToken
105
+
106
+ import os
107
+ import asyncio
108
+ from typing import List, Dict, Union
109
+
110
+ # 创建一个工厂函数,用于并发访问时确保后端使用的Agent实例是隔离的。
111
+ def create_agent() -> AssistantAgent:
112
+
113
+ # Define a model client. You can use other model client that implements
114
+ # the `ChatCompletionClient` interface.
115
+ model_client = HepAIChatCompletionClient(
116
+ model="openai/gpt-4o",
117
+ # api_key=os.environ.get("HEPAI_API_KEY"),
118
+ )
119
+
120
+ # Define a simple rag-demo for the assistant.
121
+ async def rag_demo(
122
+ oai_messages: List[Dict],
123
+ llm_messages: List[LLMMessage],
124
+ model_client: HepAIChatCompletionClient,
125
+ cancellation_token: CancellationToken,
126
+ agent_name: str,
127
+ **kwargs):
128
+ query = oai_messages[-1]["content"] # Select the last message of the chat history as the RAG query statement.
129
+ retrieve_txt = "1. Humans will be destroyed by AI in 2050;\n2. Humans are destroyed by AI due to their arrogance and conceit."
130
+ last_txt = f"""The following are some reference materials, and you must refer to these materials to answer the question:\n{retrieve_txt}. My question is: {query}"""
131
+ oai_messages[-1]["content"] = last_txt
132
+ return oai_messages
133
+
134
+ # Define an AssistantAgent with the model, tool, system message, and reflection enabled.
135
+ # The system message instructs the agent via natural language.
136
+ return AssistantAgent(
137
+ name="weather_agent",
138
+ model_client=model_client,
139
+ memory_function=rag_demo,
140
+ system_message="You are a helpful assistant.",
141
+ reflect_on_tool_use=False,
142
+ model_client_stream=True, # Enable streaming tokens from the model client.
143
+ )
144
+
145
+ from drsai import run_console
146
+ asyncio.run(run_console(agent_factory=create_agent, task="Why will humans be destroyed"))
147
+ ```
148
+
149
+ ### 3.2.自定义智能体的回复逻辑
150
+
151
+ ```python
152
+
153
+ from drsai import AssistantAgent, HepAIChatCompletionClient
154
+ import os
155
+ import asyncio
156
+ from autogen_core import CancellationToken
157
+ from autogen_core.tools import BaseTool
158
+ from autogen_core.models import (
159
+ LLMMessage,
160
+ ChatCompletionClient,
161
+ )
162
+ from typing import List, Dict, Any, Union, AsyncGenerator
163
+
164
+ # 创建一个工厂函数,用于并发访问时确保后端使用的Agent实例是隔离的。
165
+ def create_agent() -> AssistantAgent:
166
+
167
+ # Define a model client. You can use other model client that implements
168
+ # the `ChatCompletionClient` interface.
169
+ model_client = HepAIChatCompletionClient(
170
+ model="openai/gpt-4o",
171
+ # api_key=os.environ.get("HEPAI_API_KEY"),
172
+ )
173
+
174
+ # Address the messages and return the response. Must accept messages and return a string, or a generator of strings.
175
+ async def interface(
176
+ oai_messages: List[str], # OAI messages
177
+ agent_name: str, # Agent name
178
+ llm_messages: List[LLMMessage], # AutoGen LLM messages
179
+ model_client: ChatCompletionClient, # AutoGen LLM Model client
180
+ tools: List[BaseTool[Any, Any]], # AutoGen tools
181
+ cancellation_token: CancellationToken, # AutoGen cancellation token,
182
+ **kwargs) -> Union[str, AsyncGenerator[str, None]]:
183
+ """Address the messages and return the response."""
184
+ yield "test_worker reply"
185
+
186
+
187
+ # Define an AssistantAgent with the model, tool, system message, and reflection enabled.
188
+ # The system message instructs the agent via natural language.
189
+ return AssistantAgent(
190
+ name="weather_agent",
191
+ model_client=model_client,
192
+ reply_function=interface,
193
+ system_message="You are a helpful assistant.",
194
+ reflect_on_tool_use=False
195
+ )
196
+
197
+ from drsai import run_console
198
+ asyncio.run(run_console(agent_factory=create_agent, task="Why will humans be destroyed"))
199
+ ```
200
+
201
+ ## 4.将OpenDrSai部署为OpenAI格式的后端模型服务或者HepAI woker服务
202
+
203
+ ### 4.1.部署为OpenAI格式的后端模型服务/HepAI worker服务
204
+ ```python
205
+ from drsai import run_backend, run_hepai_worker
206
+ import asyncio
207
+ asyncio.run(run_backend(agent_factory=create_agent)) # 部署为OpenAI格式的后端模型服务
208
+ # asyncio.run(run_hepai_worker(agent_factory=create_agent)) # 部署为HepAI worker服务
209
+ ```
210
+ 后端默认启动在```http://localhost:42801/apiv2```, 通过```port```参数可自定义端口
211
+
212
+ ### 4.2.使用HepAI client访问的方式访问定制好的智能体
213
+
214
+ ```python
215
+ from hepai import HepAI
216
+ import os
217
+ import json
218
+ import requests
219
+ import sys
220
+
221
+ HEPAI_API_KEY = os.getenv("HEPAI_API_KEY")
222
+ base_url = "http://localhost:42801/apiv2"
223
+
224
+
225
+ # 调用HepAI client接口
226
+ client = HepAI(api_key=HEPAI_API_KEY, base_url=base_url)
227
+ completion = client.chat.completions.create(
228
+ model='hepai/Dr-Sai',
229
+ messages=[
230
+ {"role": "user", "content": "What is the weather in New York?"}
231
+ ],
232
+ stream=True
233
+ )
234
+ for chunk in completion:
235
+ if chunk.choices[0].delta.content:
236
+ print(chunk.choices[0].delta.content, end='', flush=True)
237
+ print('\n')
238
+ ```
239
+
240
+ ## 5.OpenWebUI Pipeline接入
241
+
242
+ ### 5.1.启动包含OpenWebUI Pipeline的OpenDrSai服务
243
+
244
+ ```python
245
+ asyncio.run(run_backend(agent_factory=create_agent, enable_openwebui_pipeline=True))
246
+ ```
247
+
248
+ 后端默认启动在```http://localhost:42801/apiv2```, 通过```port```参数可自定义端口;OpenWebUI Pipeline默认启动在```http://localhost:42801/pipelines```
249
+
250
+ ### 5.2.安装OpenWebUI
251
+
252
+ ```shell
253
+ pip install open-webui
254
+ ```
255
+
256
+ **设置HuggingFace镜像:**
257
+ 将HuggingFace镜像:'HF_ENDPOINT '= 'https://hf-mirror.com'加入到本地的环境。对于Linux系统,可以将其加入到~/.bashrc文件中:
258
+ ```export HF_ENDPOINT=https://hf-mirror.com```
259
+
260
+ 在命令行中运行:```open-webui serve --port 8088```启动OpenWebUI服务。
261
+
262
+ ### 5.3.配置OpenWebUI Pipeline
263
+
264
+ pipeline的密钥在```drsai/backend/pipelines/config.py```中,默认为:```0p3n-w3bu!```,将密钥和pipeline后端服务的地址:```http://localhost:42801/pipelines```加入OpenWebUI的```管理员面板-设置-外部连接-管理OpenAI API连接```中。
265
+
266
+ ### 5.4.自定义Pipeline
267
+
268
+ 将OpenDrSai项目中的```drsai/backend/owebui_pipeline/pipelines/pipelines/drsai_pipeline.py```复制到在自定义文件夹下,进行自定义修改,设置环境变量```PIPELINES_DIR```,让OpenWebUI Pipeline加载自定义的pipeline文件。
269
+
270
+ ## 6.详细文档
271
+ 见docs目录:
272
+ ```shell
273
+ 开发中
274
+ ```
275
+
276
+ ## 7.联系我们
277
+
278
+ - 邮箱:hepai@ihep.ac.cn/xiongdb@ihep.ac.cn
279
+ - 微信:xiongdongbo_12138