-
Notifications
You must be signed in to change notification settings - Fork 82
Expand file tree
/
Copy pathstart.py
More file actions
366 lines (305 loc) · 11.3 KB
/
Copy pathstart.py
File metadata and controls
366 lines (305 loc) · 11.3 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
import time, sys
import os
import yaml
import requests
from typing import List
from loguru import logger
from tqdm import tqdm
import ollama
import shutil
from concurrent.futures import ThreadPoolExecutor
from langchain.llms.base import LLM
from langchain.embeddings.base import Embeddings
grandparent_dir = os.path.join(
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
)
sys.path.append(grandparent_dir)
parent_dir = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
)
sys.path.append(parent_dir)
logger.info(f'parent_dir is {parent_dir}' )
try:
import test_config
except Exception as e:
# set your config
logger.error(f"{e}")
logger.error(f"please set your test_config")
if not os.path.exists(os.path.join(parent_dir, "test_config.py")):
shutil.copy(
os.path.join(parent_dir, "test_config.py.example"),
os.path.join(parent_dir, "test_config.py")
)
import test_config
from muagent.schemas.db import *
from muagent.schemas.apis.ekg_api_schema import LLMFCRequest
from muagent.db_handler import *
from muagent.llm_models.llm_config import EmbedConfig, LLMConfig
from muagent.service.ekg_construct.ekg_construct_base import EKGConstructService
from muagent.service.ekg_inference import IntentionRouter
from muagent.connector.memory_manager import TbaseMemoryManager
from muagent.llm_models import getChatModelFromConfig
from pydantic import BaseModel
from muagent.schemas.models import ModelConfig
from muagent.models import get_model
cur_dir = os.path.dirname(__file__)
# print(cur_dir)
# # 要打开的YAML文件路径
# file_path = 'ekg.yaml'
# if not os.path.exists(os.path.join(cur_dir, file_path)):
# shutil.copy(
# os.path.join(cur_dir, "ekg.yaml.example"),
# os.path.join(cur_dir, "ekg.yaml")
# )
# with open(os.path.join(cur_dir, file_path), 'r') as file:
# # 加载YAML文件内容
# config_data = yaml.safe_load(file)
# llm config
class CustomLLM(LLM, BaseModel):
url: str = os.environ["API_BASE_URL"]# "http://ollama:11434/api/generate"
model_name: str=os.environ["model_name"] #str = "qwen2.5:0.5b"
model_type: str = os.environ["model_engine"]#"ollama"
api_key: str = os.environ["OPENAI_API_KEY"]#""
stop: str = None
temperature: float = 0.3
top_k: int = 50
top_p: float = 0.95
def params(self):
keys = ["url", "model_name", "model_type", "api_key", "stop", "temperature", "top_k", "top_p"]
return {
k:v
for k,v in self.__dict__.items()
if k in keys}
def update_params(self, **kwargs):
# 更新属性
for key, value in kwargs.items():
setattr(self, key, value)
def _llm_type(self, *args):
return ""
def _get_model(self):
"""_call
"""
if self.model_type in [
"ollama", "qwen", "openai", "lingyiwanwu",
"kimi", "moonshot",
]:
from muagent.llm_models.openai_model import getChatModelFromConfig
llm_config = LLMConfig(
model_name=self.model_name,
model_engine=self.model_type,
api_key=self.api_key,
api_base_url=self.url,
temperature=self.temperature,
stop=self.stop
)
model = getChatModelFromConfig(llm_config)
else:
model_config = ModelConfig(
model_type=self.model_type,
model_name=self.model_name,
api_key=self.api_key,
api_url=self.url,
temperature=self.temperature,
)
model = get_model(model_config)
return model
def predict(self, prompt: str, stop = None) -> str:
return self._call(prompt, stop)
def fc(self, request: LLMFCRequest) -> str:
"""_function_call
"""
if self.model_type not in [
"openai", "ollama", "lingyiwanwu", "kimi", "moonshot", "qwen"
]:
return f"{self.model_type} not in valid model range"
model = self._get_model()
return model.fc(
messages=request.messages,
tools=request.tools,
tool_choice=request.tool_choice,
parallel_tool_calls=request.parallel_tool_calls,
)
def _call(self, prompt: str,
stop = None) -> str:
"""_call
"""
return_str = ""
stop = stop or self.stop
if self.model_type not in [
"openai", "ollama", "lingyiwanwu", "kimi", "moonshot", "qwen"
]:
pass
elif self.model_type not in [
"dashscope_chat", "moonshot_chat", "ollama_chat",
"openai_chat", "qwen_chat", "yi_chat",
"dashscope_text_embedding", "ollama_embedding", "openai_embedding", "qwen_text_embedding"
]:
pass
else:
return f"{self.model_type} not in valid model range"
model = self._get_model()
return model.predict(prompt, stop=self.stop)
class CustomEmbeddings(Embeddings):
# ollama embeddings
url = "http://ollama:11434/api/embeddings"
#
embedding_type = "ollama"
model_name = "qwen2.5:0.5b"
api_key = ""
def params(self):
return {
"url": self.url, "model_name": self.model_name,
"embedding_type": self.embedding_type, "api_key": self.api_key
}
def update_params(self, **kwargs):
# 更新属性
for key, value in kwargs.items():
setattr(self, key, value)
def _get_sentence_emb(self, sentence: str) -> dict:
"""
调用句子向量提取服务
"""
if self.embedding_type == "ollama":
ollama_embeddings = ollama.embed(
model=self.model_name,
input=sentence
)
return ollama_embeddings["embeddings"][0]
elif self.embedding_type == "openai":
from muagent.llm_models.get_embedding import get_embedding
os.environ["OPENAI_API_KEY"] = self.api_key
os.environ["API_BASE_URL"] = self.url
embed_config = EmbedConfig(
embed_engine="openai",
api_key=self.api_key,
api_base_url=self.url,
)
text2vector_dict = get_embedding("openai", [sentence], embed_config=embed_config)
return text2vector_dict[sentence]
elif self.embedding_type in [
"dashscope_text_embedding", "ollama_embedding", "openai_embedding", "qwen_text_embedding"
]:
model_config = ModelConfig(
model_type=self.embedding_type,
model_name=self.model_name,
api_key=self.api_key,
api_url=self.url,
)
model = get_model(model_config)
return model.embed_query(sentence)
else:
pass
return []
def embed_documents(self, texts: List[str]) -> List[List[float]]:
embeddings = []
def process_text(text):
# print("分句:" + str(text) + "\n")
emb_str = self._get_sentence_emb(text)
# print("向量:" + str(emb_str) + "\n")
return emb_str
with ThreadPoolExecutor() as executor:
results = list(tqdm(executor.map(process_text, texts), total=len(texts), desc="Embedding documents"))
embeddings.extend(results)
print("向量个数" + str(len(embeddings)))
return embeddings
def embed_query(self, text: str) -> List[float]:
"""Compute query embeddings using a HuggingFace transformer model.
Args:
text: The text to embed.
Returns:
Embeddings for the text.
"""
logger.info("提问query: " + str(text))
embedding = self._get_sentence_emb(text)
logger.info("提问向量:" + str(embedding))
return embedding
# gb_config = GBConfig(
# gb_type="GeaBaseHandler",
# extra_kwargs={
# 'metaserver_address': config_data["gbase_config"]['metaserver_address'],
# 'project': config_data["gbase_config"]['project'],
# 'city': config_data["gbase_config"]['city'],
# 'lib_path': config_data["gbase_config"]['lib_path'],
# }
# )
# 初始化 NebulaHandler 实例
gb_config = GBConfig(
gb_type="NebulaHandler",
extra_kwargs={
'host': os.environ["nb_host"], # config_data["nebula_config"]['host'],
'port': os.environ["nb_port"], # config_data["nebula_config"]['port'],
'username': os.environ["nb_username"], # config_data["nebula_config"]['username'] ,
'password': os.environ["nb_password"], # config_data["nebula_config"]['password'],
"space": os.environ["nb_space"], # config_data["nebula_config"]['space_name'],
}
)
# 初始化 TbaseHandler 实例
tb_config = TBConfig(
tb_type="TbaseHandler",
index_name="muagent_test",
host=os.environ["tb_host"], # config_data["tbase_config"]["host"],
port=os.environ["tb_port"], # config_data["tbase_config"]['port'],
username=os.environ["tb_username"], # config_data["tbase_config"]['username'],
password=os.environ["tb_password"], # config_data["tbase_config"]['password'],
extra_kwargs={
'host': os.environ["tb_host"], # config_data["tbase_config"]['host'],
'port': os.environ["tb_port"], # config_data["tbase_config"]['port'],
'username': os.environ["tb_username"], # config_data["tbase_config"]['username'] ,
'password': os.environ["tb_password"], # config_data["tbase_config"]['password'],
'definition_value': os.environ["tb_definition_value"], # config_data["tbase_config"]['definition_value']
}
)
llm = CustomLLM()
llm_config = LLMConfig(
llm=llm
)
embeddings = CustomEmbeddings()
# embed_config = EmbedConfig(
# embed_model="default",
# langchain_embeddings=embeddings
# )
embed_config = None
clear_history_data = os.environ.get('clear_history_data', 'False') == 'True'
ekg_construct_service = EKGConstructService(
embed_config=embed_config,
llm_config=llm_config,
tb_config=tb_config,
gb_config=gb_config,
initialize_space=True,
clear_history_data=clear_history_data
)
# 指定index_name
index_name = os.environ["tb_index_name"]
th = TbaseHandler(tb_config, index_name, definition_value=os.environ['tb_definition_value'])
# 5、memory 接口配置
# create tbase memory manager
memory_manager = TbaseMemoryManager(
unique_name="EKG",
embed_config=embed_config,
llm_config=llm_config,
tbase_handler=th,
use_vector=False
)
intention_router = IntentionRouter(
ekg_construct_service.model,
ekg_construct_service.gb,
ekg_construct_service.tb,
embed_config
)
memory_manager = memory_manager
#geabase_handler = GeaBaseHandler(gb_config)
geabase_handler = ekg_construct_service.gb
intention_router = intention_router
from who_is_spy_game import load_whoisspy_datas, test_whoisspy_datas
load_whoisspy_datas(ekg_construct_service)
test_whoisspy_datas(ekg_construct_service)
from muagent.httpapis.ekg_construct import create_api
app = create_api(
llm,
llm_config,
embeddings,
ekg_construct_service,
memory_manager,
geabase_handler,
intention_router
)