您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

chat_model.py 58KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import re
  17. from openai.lib.azure import AzureOpenAI
  18. from zhipuai import ZhipuAI
  19. from dashscope import Generation
  20. from abc import ABC
  21. from openai import OpenAI
  22. import openai
  23. from ollama import Client
  24. from rag.nlp import is_chinese, is_english
  25. from rag.utils import num_tokens_from_string
  26. import os
  27. import json
  28. import requests
  29. import asyncio
  30. LENGTH_NOTIFICATION_CN = "······\n由于大模型的上下文窗口大小限制,回答已经被大模型截断。"
  31. LENGTH_NOTIFICATION_EN = "...\nThe answer is truncated by your chosen LLM due to its limitation on context length."
  32. class Base(ABC):
  33. def __init__(self, key, model_name, base_url):
  34. timeout = int(os.environ.get('LM_TIMEOUT_SECONDS', 600))
  35. self.client = OpenAI(api_key=key, base_url=base_url, timeout=timeout)
  36. self.model_name = model_name
  37. def chat(self, system, history, gen_conf):
  38. if system:
  39. history.insert(0, {"role": "system", "content": system})
  40. if "max_tokens" in gen_conf:
  41. del gen_conf["max_tokens"]
  42. try:
  43. response = self.client.chat.completions.create(
  44. model=self.model_name,
  45. messages=history,
  46. **gen_conf)
  47. if any([not response.choices, not response.choices[0].message, not response.choices[0].message.content]):
  48. return "", 0
  49. ans = response.choices[0].message.content.strip()
  50. if response.choices[0].finish_reason == "length":
  51. if is_chinese(ans):
  52. ans += LENGTH_NOTIFICATION_CN
  53. else:
  54. ans += LENGTH_NOTIFICATION_EN
  55. return ans, self.total_token_count(response)
  56. except openai.APIError as e:
  57. return "**ERROR**: " + str(e), 0
  58. def chat_streamly(self, system, history, gen_conf):
  59. if system:
  60. history.insert(0, {"role": "system", "content": system})
  61. if "max_tokens" in gen_conf:
  62. del gen_conf["max_tokens"]
  63. ans = ""
  64. total_tokens = 0
  65. try:
  66. response = self.client.chat.completions.create(
  67. model=self.model_name,
  68. messages=history,
  69. stream=True,
  70. **gen_conf)
  71. for resp in response:
  72. if not resp.choices:
  73. continue
  74. if not resp.choices[0].delta.content:
  75. resp.choices[0].delta.content = ""
  76. if hasattr(resp.choices[0].delta, "reasoning_content") and resp.choices[0].delta.reasoning_content:
  77. if ans.find("<think>") < 0:
  78. ans += "<think>"
  79. ans = ans.replace("</think>", "")
  80. ans += resp.choices[0].delta.reasoning_content + "</think>"
  81. else:
  82. ans += resp.choices[0].delta.content
  83. tol = self.total_token_count(resp)
  84. if not tol:
  85. total_tokens += num_tokens_from_string(resp.choices[0].delta.content)
  86. else:
  87. total_tokens = tol
  88. if resp.choices[0].finish_reason == "length":
  89. if is_chinese(ans):
  90. ans += LENGTH_NOTIFICATION_CN
  91. else:
  92. ans += LENGTH_NOTIFICATION_EN
  93. yield ans
  94. except openai.APIError as e:
  95. yield ans + "\n**ERROR**: " + str(e)
  96. yield total_tokens
  97. def total_token_count(self, resp):
  98. try:
  99. return resp.usage.total_tokens
  100. except Exception:
  101. pass
  102. try:
  103. return resp["usage"]["total_tokens"]
  104. except Exception:
  105. pass
  106. return 0
  107. class GptTurbo(Base):
  108. def __init__(self, key, model_name="gpt-3.5-turbo", base_url="https://api.openai.com/v1"):
  109. if not base_url:
  110. base_url = "https://api.openai.com/v1"
  111. super().__init__(key, model_name, base_url)
  112. class MoonshotChat(Base):
  113. def __init__(self, key, model_name="moonshot-v1-8k", base_url="https://api.moonshot.cn/v1"):
  114. if not base_url:
  115. base_url = "https://api.moonshot.cn/v1"
  116. super().__init__(key, model_name, base_url)
  117. class XinferenceChat(Base):
  118. def __init__(self, key=None, model_name="", base_url=""):
  119. if not base_url:
  120. raise ValueError("Local llm url cannot be None")
  121. if base_url.split("/")[-1] != "v1":
  122. base_url = os.path.join(base_url, "v1")
  123. super().__init__(key, model_name, base_url)
  124. class HuggingFaceChat(Base):
  125. def __init__(self, key=None, model_name="", base_url=""):
  126. if not base_url:
  127. raise ValueError("Local llm url cannot be None")
  128. if base_url.split("/")[-1] != "v1":
  129. base_url = os.path.join(base_url, "v1")
  130. super().__init__(key, model_name.split("___")[0], base_url)
  131. class ModelScopeChat(Base):
  132. def __init__(self, key=None, model_name="", base_url=""):
  133. if not base_url:
  134. raise ValueError("Local llm url cannot be None")
  135. base_url = base_url.rstrip('/')
  136. if base_url.split("/")[-1] != "v1":
  137. base_url = os.path.join(base_url, "v1")
  138. super().__init__(key, model_name.split("___")[0], base_url)
  139. class DeepSeekChat(Base):
  140. def __init__(self, key, model_name="deepseek-chat", base_url="https://api.deepseek.com/v1"):
  141. if not base_url:
  142. base_url = "https://api.deepseek.com/v1"
  143. super().__init__(key, model_name, base_url)
  144. class AzureChat(Base):
  145. def __init__(self, key, model_name, **kwargs):
  146. api_key = json.loads(key).get('api_key', '')
  147. api_version = json.loads(key).get('api_version', '2024-02-01')
  148. self.client = AzureOpenAI(api_key=api_key, azure_endpoint=kwargs["base_url"], api_version=api_version)
  149. self.model_name = model_name
  150. class BaiChuanChat(Base):
  151. def __init__(self, key, model_name="Baichuan3-Turbo", base_url="https://api.baichuan-ai.com/v1"):
  152. if not base_url:
  153. base_url = "https://api.baichuan-ai.com/v1"
  154. super().__init__(key, model_name, base_url)
  155. @staticmethod
  156. def _format_params(params):
  157. return {
  158. "temperature": params.get("temperature", 0.3),
  159. "top_p": params.get("top_p", 0.85),
  160. }
  161. def chat(self, system, history, gen_conf):
  162. if system:
  163. history.insert(0, {"role": "system", "content": system})
  164. if "max_tokens" in gen_conf:
  165. del gen_conf["max_tokens"]
  166. try:
  167. response = self.client.chat.completions.create(
  168. model=self.model_name,
  169. messages=history,
  170. extra_body={
  171. "tools": [{
  172. "type": "web_search",
  173. "web_search": {
  174. "enable": True,
  175. "search_mode": "performance_first"
  176. }
  177. }]
  178. },
  179. **self._format_params(gen_conf))
  180. ans = response.choices[0].message.content.strip()
  181. if response.choices[0].finish_reason == "length":
  182. if is_chinese([ans]):
  183. ans += LENGTH_NOTIFICATION_CN
  184. else:
  185. ans += LENGTH_NOTIFICATION_EN
  186. return ans, self.total_token_count(response)
  187. except openai.APIError as e:
  188. return "**ERROR**: " + str(e), 0
  189. def chat_streamly(self, system, history, gen_conf):
  190. if system:
  191. history.insert(0, {"role": "system", "content": system})
  192. if "max_tokens" in gen_conf:
  193. del gen_conf["max_tokens"]
  194. ans = ""
  195. total_tokens = 0
  196. try:
  197. response = self.client.chat.completions.create(
  198. model=self.model_name,
  199. messages=history,
  200. extra_body={
  201. "tools": [{
  202. "type": "web_search",
  203. "web_search": {
  204. "enable": True,
  205. "search_mode": "performance_first"
  206. }
  207. }]
  208. },
  209. stream=True,
  210. **self._format_params(gen_conf))
  211. for resp in response:
  212. if not resp.choices:
  213. continue
  214. if not resp.choices[0].delta.content:
  215. resp.choices[0].delta.content = ""
  216. ans += resp.choices[0].delta.content
  217. tol = self.total_token_count(resp)
  218. if not tol:
  219. total_tokens += num_tokens_from_string(resp.choices[0].delta.content)
  220. else:
  221. total_tokens = tol
  222. if resp.choices[0].finish_reason == "length":
  223. if is_chinese([ans]):
  224. ans += LENGTH_NOTIFICATION_CN
  225. else:
  226. ans += LENGTH_NOTIFICATION_EN
  227. yield ans
  228. except Exception as e:
  229. yield ans + "\n**ERROR**: " + str(e)
  230. yield total_tokens
  231. class QWenChat(Base):
  232. def __init__(self, key, model_name=Generation.Models.qwen_turbo, **kwargs):
  233. import dashscope
  234. dashscope.api_key = key
  235. self.model_name = model_name
  236. if self.is_reasoning_model(self.model_name):
  237. super().__init__(key, model_name, "https://dashscope.aliyuncs.com/compatible-mode/v1")
  238. def chat(self, system, history, gen_conf):
  239. if "max_tokens" in gen_conf:
  240. del gen_conf["max_tokens"]
  241. if self.is_reasoning_model(self.model_name):
  242. return super().chat(system, history, gen_conf)
  243. stream_flag = str(os.environ.get('QWEN_CHAT_BY_STREAM', 'true')).lower() == 'true'
  244. if not stream_flag:
  245. from http import HTTPStatus
  246. if system:
  247. history.insert(0, {"role": "system", "content": system})
  248. response = Generation.call(
  249. self.model_name,
  250. messages=history,
  251. result_format='message',
  252. **gen_conf
  253. )
  254. ans = ""
  255. tk_count = 0
  256. if response.status_code == HTTPStatus.OK:
  257. ans += response.output.choices[0]['message']['content']
  258. tk_count += self.total_token_count(response)
  259. if response.output.choices[0].get("finish_reason", "") == "length":
  260. if is_chinese([ans]):
  261. ans += LENGTH_NOTIFICATION_CN
  262. else:
  263. ans += LENGTH_NOTIFICATION_EN
  264. return ans, tk_count
  265. return "**ERROR**: " + response.message, tk_count
  266. else:
  267. g = self._chat_streamly(system, history, gen_conf, incremental_output=True)
  268. result_list = list(g)
  269. error_msg_list = [item for item in result_list if str(item).find("**ERROR**") >= 0]
  270. if len(error_msg_list) > 0:
  271. return "**ERROR**: " + "".join(error_msg_list), 0
  272. else:
  273. return "".join(result_list[:-1]), result_list[-1]
  274. def _chat_streamly(self, system, history, gen_conf, incremental_output=False):
  275. from http import HTTPStatus
  276. if system:
  277. history.insert(0, {"role": "system", "content": system})
  278. if "max_tokens" in gen_conf:
  279. del gen_conf["max_tokens"]
  280. ans = ""
  281. tk_count = 0
  282. try:
  283. response = Generation.call(
  284. self.model_name,
  285. messages=history,
  286. result_format='message',
  287. stream=True,
  288. incremental_output=incremental_output,
  289. **gen_conf
  290. )
  291. for resp in response:
  292. if resp.status_code == HTTPStatus.OK:
  293. ans = resp.output.choices[0]['message']['content']
  294. tk_count = self.total_token_count(resp)
  295. if resp.output.choices[0].get("finish_reason", "") == "length":
  296. if is_chinese(ans):
  297. ans += LENGTH_NOTIFICATION_CN
  298. else:
  299. ans += LENGTH_NOTIFICATION_EN
  300. yield ans
  301. else:
  302. yield ans + "\n**ERROR**: " + resp.message if not re.search(r" (key|quota)",
  303. str(resp.message).lower()) else "Out of credit. Please set the API key in **settings > Model providers.**"
  304. except Exception as e:
  305. yield ans + "\n**ERROR**: " + str(e)
  306. yield tk_count
  307. def chat_streamly(self, system, history, gen_conf):
  308. if "max_tokens" in gen_conf:
  309. del gen_conf["max_tokens"]
  310. if self.is_reasoning_model(self.model_name):
  311. return super().chat_streamly(system, history, gen_conf)
  312. return self._chat_streamly(system, history, gen_conf)
  313. @staticmethod
  314. def is_reasoning_model(model_name: str) -> bool:
  315. return any([
  316. model_name.lower().find("deepseek") >= 0,
  317. model_name.lower().find("qwq") >= 0 and model_name.lower() != 'qwq-32b-preview',
  318. ])
  319. class ZhipuChat(Base):
  320. def __init__(self, key, model_name="glm-3-turbo", **kwargs):
  321. self.client = ZhipuAI(api_key=key)
  322. self.model_name = model_name
  323. def chat(self, system, history, gen_conf):
  324. if system:
  325. history.insert(0, {"role": "system", "content": system})
  326. if "max_tokens" in gen_conf:
  327. del gen_conf["max_tokens"]
  328. try:
  329. if "presence_penalty" in gen_conf:
  330. del gen_conf["presence_penalty"]
  331. if "frequency_penalty" in gen_conf:
  332. del gen_conf["frequency_penalty"]
  333. response = self.client.chat.completions.create(
  334. model=self.model_name,
  335. messages=history,
  336. **gen_conf
  337. )
  338. ans = response.choices[0].message.content.strip()
  339. if response.choices[0].finish_reason == "length":
  340. if is_chinese(ans):
  341. ans += LENGTH_NOTIFICATION_CN
  342. else:
  343. ans += LENGTH_NOTIFICATION_EN
  344. return ans, self.total_token_count(response)
  345. except Exception as e:
  346. return "**ERROR**: " + str(e), 0
  347. def chat_streamly(self, system, history, gen_conf):
  348. if system:
  349. history.insert(0, {"role": "system", "content": system})
  350. if "max_tokens" in gen_conf:
  351. del gen_conf["max_tokens"]
  352. if "presence_penalty" in gen_conf:
  353. del gen_conf["presence_penalty"]
  354. if "frequency_penalty" in gen_conf:
  355. del gen_conf["frequency_penalty"]
  356. ans = ""
  357. tk_count = 0
  358. try:
  359. response = self.client.chat.completions.create(
  360. model=self.model_name,
  361. messages=history,
  362. stream=True,
  363. **gen_conf
  364. )
  365. for resp in response:
  366. if not resp.choices[0].delta.content:
  367. continue
  368. delta = resp.choices[0].delta.content
  369. ans += delta
  370. if resp.choices[0].finish_reason == "length":
  371. if is_chinese(ans):
  372. ans += LENGTH_NOTIFICATION_CN
  373. else:
  374. ans += LENGTH_NOTIFICATION_EN
  375. tk_count = self.total_token_count(resp)
  376. if resp.choices[0].finish_reason == "stop":
  377. tk_count = self.total_token_count(resp)
  378. yield ans
  379. except Exception as e:
  380. yield ans + "\n**ERROR**: " + str(e)
  381. yield tk_count
  382. class OllamaChat(Base):
  383. def __init__(self, key, model_name, **kwargs):
  384. self.client = Client(host=kwargs["base_url"]) if not key or key == "x" else \
  385. Client(host=kwargs["base_url"], headers={"Authorization": f"Bear {key}"})
  386. self.model_name = model_name
  387. def chat(self, system, history, gen_conf):
  388. if system:
  389. history.insert(0, {"role": "system", "content": system})
  390. if "max_tokens" in gen_conf:
  391. del gen_conf["max_tokens"]
  392. try:
  393. options = {}
  394. if "temperature" in gen_conf:
  395. options["temperature"] = gen_conf["temperature"]
  396. if "max_tokens" in gen_conf:
  397. options["num_predict"] = gen_conf["max_tokens"]
  398. if "top_p" in gen_conf:
  399. options["top_p"] = gen_conf["top_p"]
  400. if "presence_penalty" in gen_conf:
  401. options["presence_penalty"] = gen_conf["presence_penalty"]
  402. if "frequency_penalty" in gen_conf:
  403. options["frequency_penalty"] = gen_conf["frequency_penalty"]
  404. response = self.client.chat(
  405. model=self.model_name,
  406. messages=history,
  407. options=options,
  408. keep_alive=-1
  409. )
  410. ans = response["message"]["content"].strip()
  411. return ans, response.get("eval_count", 0) + response.get("prompt_eval_count", 0)
  412. except Exception as e:
  413. return "**ERROR**: " + str(e), 0
  414. def chat_streamly(self, system, history, gen_conf):
  415. if system:
  416. history.insert(0, {"role": "system", "content": system})
  417. if "max_tokens" in gen_conf:
  418. del gen_conf["max_tokens"]
  419. options = {}
  420. if "temperature" in gen_conf:
  421. options["temperature"] = gen_conf["temperature"]
  422. if "max_tokens" in gen_conf:
  423. options["num_predict"] = gen_conf["max_tokens"]
  424. if "top_p" in gen_conf:
  425. options["top_p"] = gen_conf["top_p"]
  426. if "presence_penalty" in gen_conf:
  427. options["presence_penalty"] = gen_conf["presence_penalty"]
  428. if "frequency_penalty" in gen_conf:
  429. options["frequency_penalty"] = gen_conf["frequency_penalty"]
  430. ans = ""
  431. try:
  432. response = self.client.chat(
  433. model=self.model_name,
  434. messages=history,
  435. stream=True,
  436. options=options,
  437. keep_alive=-1
  438. )
  439. for resp in response:
  440. if resp["done"]:
  441. yield resp.get("prompt_eval_count", 0) + resp.get("eval_count", 0)
  442. ans += resp["message"]["content"]
  443. yield ans
  444. except Exception as e:
  445. yield ans + "\n**ERROR**: " + str(e)
  446. yield 0
  447. class LocalAIChat(Base):
  448. def __init__(self, key, model_name, base_url):
  449. if not base_url:
  450. raise ValueError("Local llm url cannot be None")
  451. if base_url.split("/")[-1] != "v1":
  452. base_url = os.path.join(base_url, "v1")
  453. self.client = OpenAI(api_key="empty", base_url=base_url)
  454. self.model_name = model_name.split("___")[0]
  455. class LocalLLM(Base):
  456. class RPCProxy:
  457. def __init__(self, host, port):
  458. self.host = host
  459. self.port = int(port)
  460. self.__conn()
  461. def __conn(self):
  462. from multiprocessing.connection import Client
  463. self._connection = Client(
  464. (self.host, self.port), authkey=b"infiniflow-token4kevinhu"
  465. )
  466. def __getattr__(self, name):
  467. import pickle
  468. def do_rpc(*args, **kwargs):
  469. for _ in range(3):
  470. try:
  471. self._connection.send(pickle.dumps((name, args, kwargs)))
  472. return pickle.loads(self._connection.recv())
  473. except Exception:
  474. self.__conn()
  475. raise Exception("RPC connection lost!")
  476. return do_rpc
  477. def __init__(self, key, model_name):
  478. from jina import Client
  479. self.client = Client(port=12345, protocol="grpc", asyncio=True)
  480. def _prepare_prompt(self, system, history, gen_conf):
  481. from rag.svr.jina_server import Prompt
  482. if system:
  483. history.insert(0, {"role": "system", "content": system})
  484. return Prompt(message=history, gen_conf=gen_conf)
  485. def _stream_response(self, endpoint, prompt):
  486. from rag.svr.jina_server import Generation
  487. answer = ""
  488. try:
  489. res = self.client.stream_doc(
  490. on=endpoint, inputs=prompt, return_type=Generation
  491. )
  492. loop = asyncio.get_event_loop()
  493. try:
  494. while True:
  495. answer = loop.run_until_complete(res.__anext__()).text
  496. yield answer
  497. except StopAsyncIteration:
  498. pass
  499. except Exception as e:
  500. yield answer + "\n**ERROR**: " + str(e)
  501. yield num_tokens_from_string(answer)
  502. def chat(self, system, history, gen_conf):
  503. if "max_tokens" in gen_conf:
  504. del gen_conf["max_tokens"]
  505. prompt = self._prepare_prompt(system, history, gen_conf)
  506. chat_gen = self._stream_response("/chat", prompt)
  507. ans = next(chat_gen)
  508. total_tokens = next(chat_gen)
  509. return ans, total_tokens
  510. def chat_streamly(self, system, history, gen_conf):
  511. if "max_tokens" in gen_conf:
  512. del gen_conf["max_tokens"]
  513. prompt = self._prepare_prompt(system, history, gen_conf)
  514. return self._stream_response("/stream", prompt)
  515. class VolcEngineChat(Base):
  516. def __init__(self, key, model_name, base_url='https://ark.cn-beijing.volces.com/api/v3'):
  517. """
  518. Since do not want to modify the original database fields, and the VolcEngine authentication method is quite special,
  519. Assemble ark_api_key, ep_id into api_key, store it as a dictionary type, and parse it for use
  520. model_name is for display only
  521. """
  522. base_url = base_url if base_url else 'https://ark.cn-beijing.volces.com/api/v3'
  523. ark_api_key = json.loads(key).get('ark_api_key', '')
  524. model_name = json.loads(key).get('ep_id', '') + json.loads(key).get('endpoint_id', '')
  525. super().__init__(ark_api_key, model_name, base_url)
  526. class MiniMaxChat(Base):
  527. def __init__(
  528. self,
  529. key,
  530. model_name,
  531. base_url="https://api.minimax.chat/v1/text/chatcompletion_v2",
  532. ):
  533. if not base_url:
  534. base_url = "https://api.minimax.chat/v1/text/chatcompletion_v2"
  535. self.base_url = base_url
  536. self.model_name = model_name
  537. self.api_key = key
  538. def chat(self, system, history, gen_conf):
  539. if system:
  540. history.insert(0, {"role": "system", "content": system})
  541. for k in list(gen_conf.keys()):
  542. if k not in ["temperature", "top_p", "max_tokens"]:
  543. del gen_conf[k]
  544. headers = {
  545. "Authorization": f"Bearer {self.api_key}",
  546. "Content-Type": "application/json",
  547. }
  548. payload = json.dumps(
  549. {"model": self.model_name, "messages": history, **gen_conf}
  550. )
  551. try:
  552. response = requests.request(
  553. "POST", url=self.base_url, headers=headers, data=payload
  554. )
  555. response = response.json()
  556. ans = response["choices"][0]["message"]["content"].strip()
  557. if response["choices"][0]["finish_reason"] == "length":
  558. if is_chinese(ans):
  559. ans += LENGTH_NOTIFICATION_CN
  560. else:
  561. ans += LENGTH_NOTIFICATION_EN
  562. return ans, self.total_token_count(response)
  563. except Exception as e:
  564. return "**ERROR**: " + str(e), 0
  565. def chat_streamly(self, system, history, gen_conf):
  566. if system:
  567. history.insert(0, {"role": "system", "content": system})
  568. for k in list(gen_conf.keys()):
  569. if k not in ["temperature", "top_p", "max_tokens"]:
  570. del gen_conf[k]
  571. ans = ""
  572. total_tokens = 0
  573. try:
  574. headers = {
  575. "Authorization": f"Bearer {self.api_key}",
  576. "Content-Type": "application/json",
  577. }
  578. payload = json.dumps(
  579. {
  580. "model": self.model_name,
  581. "messages": history,
  582. "stream": True,
  583. **gen_conf,
  584. }
  585. )
  586. response = requests.request(
  587. "POST",
  588. url=self.base_url,
  589. headers=headers,
  590. data=payload,
  591. )
  592. for resp in response.text.split("\n\n")[:-1]:
  593. resp = json.loads(resp[6:])
  594. text = ""
  595. if "choices" in resp and "delta" in resp["choices"][0]:
  596. text = resp["choices"][0]["delta"]["content"]
  597. ans += text
  598. tol = self.total_token_count(resp)
  599. if not tol:
  600. total_tokens += num_tokens_from_string(text)
  601. else:
  602. total_tokens = tol
  603. yield ans
  604. except Exception as e:
  605. yield ans + "\n**ERROR**: " + str(e)
  606. yield total_tokens
  607. class MistralChat(Base):
  608. def __init__(self, key, model_name, base_url=None):
  609. from mistralai.client import MistralClient
  610. self.client = MistralClient(api_key=key)
  611. self.model_name = model_name
  612. def chat(self, system, history, gen_conf):
  613. if system:
  614. history.insert(0, {"role": "system", "content": system})
  615. for k in list(gen_conf.keys()):
  616. if k not in ["temperature", "top_p", "max_tokens"]:
  617. del gen_conf[k]
  618. try:
  619. response = self.client.chat(
  620. model=self.model_name,
  621. messages=history,
  622. **gen_conf)
  623. ans = response.choices[0].message.content
  624. if response.choices[0].finish_reason == "length":
  625. if is_chinese(ans):
  626. ans += LENGTH_NOTIFICATION_CN
  627. else:
  628. ans += LENGTH_NOTIFICATION_EN
  629. return ans, self.total_token_count(response)
  630. except openai.APIError as e:
  631. return "**ERROR**: " + str(e), 0
  632. def chat_streamly(self, system, history, gen_conf):
  633. if system:
  634. history.insert(0, {"role": "system", "content": system})
  635. for k in list(gen_conf.keys()):
  636. if k not in ["temperature", "top_p", "max_tokens"]:
  637. del gen_conf[k]
  638. ans = ""
  639. total_tokens = 0
  640. try:
  641. response = self.client.chat_stream(
  642. model=self.model_name,
  643. messages=history,
  644. **gen_conf)
  645. for resp in response:
  646. if not resp.choices or not resp.choices[0].delta.content:
  647. continue
  648. ans += resp.choices[0].delta.content
  649. total_tokens += 1
  650. if resp.choices[0].finish_reason == "length":
  651. if is_chinese(ans):
  652. ans += LENGTH_NOTIFICATION_CN
  653. else:
  654. ans += LENGTH_NOTIFICATION_EN
  655. yield ans
  656. except openai.APIError as e:
  657. yield ans + "\n**ERROR**: " + str(e)
  658. yield total_tokens
  659. class BedrockChat(Base):
  660. def __init__(self, key, model_name, **kwargs):
  661. import boto3
  662. self.bedrock_ak = json.loads(key).get('bedrock_ak', '')
  663. self.bedrock_sk = json.loads(key).get('bedrock_sk', '')
  664. self.bedrock_region = json.loads(key).get('bedrock_region', '')
  665. self.model_name = model_name
  666. if self.bedrock_ak == '' or self.bedrock_sk == '' or self.bedrock_region == '':
  667. # Try to create a client using the default credentials (AWS_PROFILE, AWS_DEFAULT_REGION, etc.)
  668. self.client = boto3.client('bedrock-runtime')
  669. else:
  670. self.client = boto3.client(service_name='bedrock-runtime', region_name=self.bedrock_region,
  671. aws_access_key_id=self.bedrock_ak, aws_secret_access_key=self.bedrock_sk)
  672. def chat(self, system, history, gen_conf):
  673. from botocore.exceptions import ClientError
  674. for k in list(gen_conf.keys()):
  675. if k not in ["top_p", "max_tokens"]:
  676. del gen_conf[k]
  677. for item in history:
  678. if not isinstance(item["content"], list) and not isinstance(item["content"], tuple):
  679. item["content"] = [{"text": item["content"]}]
  680. try:
  681. # Send the message to the model, using a basic inference configuration.
  682. response = self.client.converse(
  683. modelId=self.model_name,
  684. messages=history,
  685. inferenceConfig=gen_conf,
  686. system=[{"text": (system if system else "Answer the user's message.")}],
  687. )
  688. # Extract and print the response text.
  689. ans = response["output"]["message"]["content"][0]["text"]
  690. return ans, num_tokens_from_string(ans)
  691. except (ClientError, Exception) as e:
  692. return f"ERROR: Can't invoke '{self.model_name}'. Reason: {e}", 0
  693. def chat_streamly(self, system, history, gen_conf):
  694. from botocore.exceptions import ClientError
  695. for k in list(gen_conf.keys()):
  696. if k not in ["top_p", "max_tokens"]:
  697. del gen_conf[k]
  698. for item in history:
  699. if not isinstance(item["content"], list) and not isinstance(item["content"], tuple):
  700. item["content"] = [{"text": item["content"]}]
  701. if self.model_name.split('.')[0] == 'ai21':
  702. try:
  703. response = self.client.converse(
  704. modelId=self.model_name,
  705. messages=history,
  706. inferenceConfig=gen_conf,
  707. system=[{"text": (system if system else "Answer the user's message.")}]
  708. )
  709. ans = response["output"]["message"]["content"][0]["text"]
  710. return ans, num_tokens_from_string(ans)
  711. except (ClientError, Exception) as e:
  712. return f"ERROR: Can't invoke '{self.model_name}'. Reason: {e}", 0
  713. ans = ""
  714. try:
  715. # Send the message to the model, using a basic inference configuration.
  716. streaming_response = self.client.converse_stream(
  717. modelId=self.model_name,
  718. messages=history,
  719. inferenceConfig=gen_conf,
  720. system=[{"text": (system if system else "Answer the user's message.")}]
  721. )
  722. # Extract and print the streamed response text in real-time.
  723. for resp in streaming_response["stream"]:
  724. if "contentBlockDelta" in resp:
  725. ans += resp["contentBlockDelta"]["delta"]["text"]
  726. yield ans
  727. except (ClientError, Exception) as e:
  728. yield ans + f"ERROR: Can't invoke '{self.model_name}'. Reason: {e}"
  729. yield num_tokens_from_string(ans)
  730. class GeminiChat(Base):
  731. def __init__(self, key, model_name, base_url=None):
  732. from google.generativeai import client, GenerativeModel
  733. client.configure(api_key=key)
  734. _client = client.get_default_generative_client()
  735. self.model_name = 'models/' + model_name
  736. self.model = GenerativeModel(model_name=self.model_name)
  737. self.model._client = _client
  738. def chat(self, system, history, gen_conf):
  739. from google.generativeai.types import content_types
  740. if system:
  741. self.model._system_instruction = content_types.to_content(system)
  742. for k in list(gen_conf.keys()):
  743. if k not in ["temperature", "top_p", "max_tokens"]:
  744. del gen_conf[k]
  745. for item in history:
  746. if 'role' in item and item['role'] == 'assistant':
  747. item['role'] = 'model'
  748. if 'role' in item and item['role'] == 'system':
  749. item['role'] = 'user'
  750. if 'content' in item:
  751. item['parts'] = item.pop('content')
  752. try:
  753. response = self.model.generate_content(
  754. history,
  755. generation_config=gen_conf)
  756. ans = response.text
  757. return ans, response.usage_metadata.total_token_count
  758. except Exception as e:
  759. return "**ERROR**: " + str(e), 0
  760. def chat_streamly(self, system, history, gen_conf):
  761. from google.generativeai.types import content_types
  762. if system:
  763. self.model._system_instruction = content_types.to_content(system)
  764. for k in list(gen_conf.keys()):
  765. if k not in ["temperature", "top_p", "max_tokens"]:
  766. del gen_conf[k]
  767. for item in history:
  768. if 'role' in item and item['role'] == 'assistant':
  769. item['role'] = 'model'
  770. if 'content' in item:
  771. item['parts'] = item.pop('content')
  772. ans = ""
  773. try:
  774. response = self.model.generate_content(
  775. history,
  776. generation_config=gen_conf, stream=True)
  777. for resp in response:
  778. ans += resp.text
  779. yield ans
  780. yield response._chunks[-1].usage_metadata.total_token_count
  781. except Exception as e:
  782. yield ans + "\n**ERROR**: " + str(e)
  783. yield 0
  784. class GroqChat(Base):
  785. def __init__(self, key, model_name, base_url=''):
  786. from groq import Groq
  787. self.client = Groq(api_key=key)
  788. self.model_name = model_name
  789. def chat(self, system, history, gen_conf):
  790. if system:
  791. history.insert(0, {"role": "system", "content": system})
  792. for k in list(gen_conf.keys()):
  793. if k not in ["temperature", "top_p", "max_tokens"]:
  794. del gen_conf[k]
  795. ans = ""
  796. try:
  797. response = self.client.chat.completions.create(
  798. model=self.model_name,
  799. messages=history,
  800. **gen_conf
  801. )
  802. ans = response.choices[0].message.content
  803. if response.choices[0].finish_reason == "length":
  804. if is_chinese(ans):
  805. ans += LENGTH_NOTIFICATION_CN
  806. else:
  807. ans += LENGTH_NOTIFICATION_EN
  808. return ans, self.total_token_count(response)
  809. except Exception as e:
  810. return ans + "\n**ERROR**: " + str(e), 0
  811. def chat_streamly(self, system, history, gen_conf):
  812. if system:
  813. history.insert(0, {"role": "system", "content": system})
  814. for k in list(gen_conf.keys()):
  815. if k not in ["temperature", "top_p", "max_tokens"]:
  816. del gen_conf[k]
  817. ans = ""
  818. total_tokens = 0
  819. try:
  820. response = self.client.chat.completions.create(
  821. model=self.model_name,
  822. messages=history,
  823. stream=True,
  824. **gen_conf
  825. )
  826. for resp in response:
  827. if not resp.choices or not resp.choices[0].delta.content:
  828. continue
  829. ans += resp.choices[0].delta.content
  830. total_tokens += 1
  831. if resp.choices[0].finish_reason == "length":
  832. if is_chinese(ans):
  833. ans += LENGTH_NOTIFICATION_CN
  834. else:
  835. ans += LENGTH_NOTIFICATION_EN
  836. yield ans
  837. except Exception as e:
  838. yield ans + "\n**ERROR**: " + str(e)
  839. yield total_tokens
  840. ## openrouter
  841. class OpenRouterChat(Base):
  842. def __init__(self, key, model_name, base_url="https://openrouter.ai/api/v1"):
  843. if not base_url:
  844. base_url = "https://openrouter.ai/api/v1"
  845. super().__init__(key, model_name, base_url)
  846. class StepFunChat(Base):
  847. def __init__(self, key, model_name, base_url="https://api.stepfun.com/v1"):
  848. if not base_url:
  849. base_url = "https://api.stepfun.com/v1"
  850. super().__init__(key, model_name, base_url)
  851. class NvidiaChat(Base):
  852. def __init__(self, key, model_name, base_url="https://integrate.api.nvidia.com/v1"):
  853. if not base_url:
  854. base_url = "https://integrate.api.nvidia.com/v1"
  855. super().__init__(key, model_name, base_url)
  856. class LmStudioChat(Base):
  857. def __init__(self, key, model_name, base_url):
  858. if not base_url:
  859. raise ValueError("Local llm url cannot be None")
  860. if base_url.split("/")[-1] != "v1":
  861. base_url = os.path.join(base_url, "v1")
  862. self.client = OpenAI(api_key="lm-studio", base_url=base_url)
  863. self.model_name = model_name
  864. class OpenAI_APIChat(Base):
  865. def __init__(self, key, model_name, base_url):
  866. if not base_url:
  867. raise ValueError("url cannot be None")
  868. model_name = model_name.split("___")[0]
  869. super().__init__(key, model_name, base_url)
  870. class PPIOChat(Base):
  871. def __init__(self, key, model_name, base_url="https://api.ppinfra.com/v3/openai"):
  872. if not base_url:
  873. base_url = "https://api.ppinfra.com/v3/openai"
  874. super().__init__(key, model_name, base_url)
  875. class CoHereChat(Base):
  876. def __init__(self, key, model_name, base_url=""):
  877. from cohere import Client
  878. self.client = Client(api_key=key)
  879. self.model_name = model_name
  880. def chat(self, system, history, gen_conf):
  881. if system:
  882. history.insert(0, {"role": "system", "content": system})
  883. if "max_tokens" in gen_conf:
  884. del gen_conf["max_tokens"]
  885. if "top_p" in gen_conf:
  886. gen_conf["p"] = gen_conf.pop("top_p")
  887. if "frequency_penalty" in gen_conf and "presence_penalty" in gen_conf:
  888. gen_conf.pop("presence_penalty")
  889. for item in history:
  890. if "role" in item and item["role"] == "user":
  891. item["role"] = "USER"
  892. if "role" in item and item["role"] == "assistant":
  893. item["role"] = "CHATBOT"
  894. if "content" in item:
  895. item["message"] = item.pop("content")
  896. mes = history.pop()["message"]
  897. ans = ""
  898. try:
  899. response = self.client.chat(
  900. model=self.model_name, chat_history=history, message=mes, **gen_conf
  901. )
  902. ans = response.text
  903. if response.finish_reason == "MAX_TOKENS":
  904. ans += (
  905. "...\nFor the content length reason, it stopped, continue?"
  906. if is_english([ans])
  907. else "······\n由于长度的原因,回答被截断了,要继续吗?"
  908. )
  909. return (
  910. ans,
  911. response.meta.tokens.input_tokens + response.meta.tokens.output_tokens,
  912. )
  913. except Exception as e:
  914. return ans + "\n**ERROR**: " + str(e), 0
  915. def chat_streamly(self, system, history, gen_conf):
  916. if system:
  917. history.insert(0, {"role": "system", "content": system})
  918. if "max_tokens" in gen_conf:
  919. del gen_conf["max_tokens"]
  920. if "top_p" in gen_conf:
  921. gen_conf["p"] = gen_conf.pop("top_p")
  922. if "frequency_penalty" in gen_conf and "presence_penalty" in gen_conf:
  923. gen_conf.pop("presence_penalty")
  924. for item in history:
  925. if "role" in item and item["role"] == "user":
  926. item["role"] = "USER"
  927. if "role" in item and item["role"] == "assistant":
  928. item["role"] = "CHATBOT"
  929. if "content" in item:
  930. item["message"] = item.pop("content")
  931. mes = history.pop()["message"]
  932. ans = ""
  933. total_tokens = 0
  934. try:
  935. response = self.client.chat_stream(
  936. model=self.model_name, chat_history=history, message=mes, **gen_conf
  937. )
  938. for resp in response:
  939. if resp.event_type == "text-generation":
  940. ans += resp.text
  941. total_tokens += num_tokens_from_string(resp.text)
  942. elif resp.event_type == "stream-end":
  943. if resp.finish_reason == "MAX_TOKENS":
  944. ans += (
  945. "...\nFor the content length reason, it stopped, continue?"
  946. if is_english([ans])
  947. else "······\n由于长度的原因,回答被截断了,要继续吗?"
  948. )
  949. yield ans
  950. except Exception as e:
  951. yield ans + "\n**ERROR**: " + str(e)
  952. yield total_tokens
  953. class LeptonAIChat(Base):
  954. def __init__(self, key, model_name, base_url=None):
  955. if not base_url:
  956. base_url = os.path.join("https://" + model_name + ".lepton.run", "api", "v1")
  957. super().__init__(key, model_name, base_url)
  958. class TogetherAIChat(Base):
  959. def __init__(self, key, model_name, base_url="https://api.together.xyz/v1"):
  960. if not base_url:
  961. base_url = "https://api.together.xyz/v1"
  962. super().__init__(key, model_name, base_url)
  963. class PerfXCloudChat(Base):
  964. def __init__(self, key, model_name, base_url="https://cloud.perfxlab.cn/v1"):
  965. if not base_url:
  966. base_url = "https://cloud.perfxlab.cn/v1"
  967. super().__init__(key, model_name, base_url)
  968. class UpstageChat(Base):
  969. def __init__(self, key, model_name, base_url="https://api.upstage.ai/v1/solar"):
  970. if not base_url:
  971. base_url = "https://api.upstage.ai/v1/solar"
  972. super().__init__(key, model_name, base_url)
  973. class NovitaAIChat(Base):
  974. def __init__(self, key, model_name, base_url="https://api.novita.ai/v3/openai"):
  975. if not base_url:
  976. base_url = "https://api.novita.ai/v3/openai"
  977. super().__init__(key, model_name, base_url)
  978. class SILICONFLOWChat(Base):
  979. def __init__(self, key, model_name, base_url="https://api.siliconflow.cn/v1"):
  980. if not base_url:
  981. base_url = "https://api.siliconflow.cn/v1"
  982. super().__init__(key, model_name, base_url)
  983. class YiChat(Base):
  984. def __init__(self, key, model_name, base_url="https://api.lingyiwanwu.com/v1"):
  985. if not base_url:
  986. base_url = "https://api.lingyiwanwu.com/v1"
  987. super().__init__(key, model_name, base_url)
  988. class ReplicateChat(Base):
  989. def __init__(self, key, model_name, base_url=None):
  990. from replicate.client import Client
  991. self.model_name = model_name
  992. self.client = Client(api_token=key)
  993. self.system = ""
  994. def chat(self, system, history, gen_conf):
  995. if "max_tokens" in gen_conf:
  996. del gen_conf["max_tokens"]
  997. if system:
  998. self.system = system
  999. prompt = "\n".join(
  1000. [item["role"] + ":" + item["content"] for item in history[-5:]]
  1001. )
  1002. ans = ""
  1003. try:
  1004. response = self.client.run(
  1005. self.model_name,
  1006. input={"system_prompt": self.system, "prompt": prompt, **gen_conf},
  1007. )
  1008. ans = "".join(response)
  1009. return ans, num_tokens_from_string(ans)
  1010. except Exception as e:
  1011. return ans + "\n**ERROR**: " + str(e), 0
  1012. def chat_streamly(self, system, history, gen_conf):
  1013. if "max_tokens" in gen_conf:
  1014. del gen_conf["max_tokens"]
  1015. if system:
  1016. self.system = system
  1017. prompt = "\n".join(
  1018. [item["role"] + ":" + item["content"] for item in history[-5:]]
  1019. )
  1020. ans = ""
  1021. try:
  1022. response = self.client.run(
  1023. self.model_name,
  1024. input={"system_prompt": self.system, "prompt": prompt, **gen_conf},
  1025. )
  1026. for resp in response:
  1027. ans += resp
  1028. yield ans
  1029. except Exception as e:
  1030. yield ans + "\n**ERROR**: " + str(e)
  1031. yield num_tokens_from_string(ans)
  1032. class HunyuanChat(Base):
  1033. def __init__(self, key, model_name, base_url=None):
  1034. from tencentcloud.common import credential
  1035. from tencentcloud.hunyuan.v20230901 import hunyuan_client
  1036. key = json.loads(key)
  1037. sid = key.get("hunyuan_sid", "")
  1038. sk = key.get("hunyuan_sk", "")
  1039. cred = credential.Credential(sid, sk)
  1040. self.model_name = model_name
  1041. self.client = hunyuan_client.HunyuanClient(cred, "")
  1042. def chat(self, system, history, gen_conf):
  1043. from tencentcloud.hunyuan.v20230901 import models
  1044. from tencentcloud.common.exception.tencent_cloud_sdk_exception import (
  1045. TencentCloudSDKException,
  1046. )
  1047. _gen_conf = {}
  1048. _history = [{k.capitalize(): v for k, v in item.items()} for item in history]
  1049. if system:
  1050. _history.insert(0, {"Role": "system", "Content": system})
  1051. if "max_tokens" in gen_conf:
  1052. del gen_conf["max_tokens"]
  1053. if "temperature" in gen_conf:
  1054. _gen_conf["Temperature"] = gen_conf["temperature"]
  1055. if "top_p" in gen_conf:
  1056. _gen_conf["TopP"] = gen_conf["top_p"]
  1057. req = models.ChatCompletionsRequest()
  1058. params = {"Model": self.model_name, "Messages": _history, **_gen_conf}
  1059. req.from_json_string(json.dumps(params))
  1060. ans = ""
  1061. try:
  1062. response = self.client.ChatCompletions(req)
  1063. ans = response.Choices[0].Message.Content
  1064. return ans, response.Usage.TotalTokens
  1065. except TencentCloudSDKException as e:
  1066. return ans + "\n**ERROR**: " + str(e), 0
  1067. def chat_streamly(self, system, history, gen_conf):
  1068. from tencentcloud.hunyuan.v20230901 import models
  1069. from tencentcloud.common.exception.tencent_cloud_sdk_exception import (
  1070. TencentCloudSDKException,
  1071. )
  1072. _gen_conf = {}
  1073. _history = [{k.capitalize(): v for k, v in item.items()} for item in history]
  1074. if system:
  1075. _history.insert(0, {"Role": "system", "Content": system})
  1076. if "max_tokens" in gen_conf:
  1077. del gen_conf["max_tokens"]
  1078. if "temperature" in gen_conf:
  1079. _gen_conf["Temperature"] = gen_conf["temperature"]
  1080. if "top_p" in gen_conf:
  1081. _gen_conf["TopP"] = gen_conf["top_p"]
  1082. req = models.ChatCompletionsRequest()
  1083. params = {
  1084. "Model": self.model_name,
  1085. "Messages": _history,
  1086. "Stream": True,
  1087. **_gen_conf,
  1088. }
  1089. req.from_json_string(json.dumps(params))
  1090. ans = ""
  1091. total_tokens = 0
  1092. try:
  1093. response = self.client.ChatCompletions(req)
  1094. for resp in response:
  1095. resp = json.loads(resp["data"])
  1096. if not resp["Choices"] or not resp["Choices"][0]["Delta"]["Content"]:
  1097. continue
  1098. ans += resp["Choices"][0]["Delta"]["Content"]
  1099. total_tokens += 1
  1100. yield ans
  1101. except TencentCloudSDKException as e:
  1102. yield ans + "\n**ERROR**: " + str(e)
  1103. yield total_tokens
  1104. class SparkChat(Base):
  1105. def __init__(
  1106. self, key, model_name, base_url="https://spark-api-open.xf-yun.com/v1"
  1107. ):
  1108. if not base_url:
  1109. base_url = "https://spark-api-open.xf-yun.com/v1"
  1110. model2version = {
  1111. "Spark-Max": "generalv3.5",
  1112. "Spark-Lite": "general",
  1113. "Spark-Pro": "generalv3",
  1114. "Spark-Pro-128K": "pro-128k",
  1115. "Spark-4.0-Ultra": "4.0Ultra",
  1116. }
  1117. version2model = {v: k for k, v in model2version.items()}
  1118. assert model_name in model2version or model_name in version2model, f"The given model name is not supported yet. Support: {list(model2version.keys())}"
  1119. if model_name in model2version:
  1120. model_version = model2version[model_name]
  1121. else:
  1122. model_version = model_name
  1123. super().__init__(key, model_version, base_url)
  1124. class BaiduYiyanChat(Base):
  1125. def __init__(self, key, model_name, base_url=None):
  1126. import qianfan
  1127. key = json.loads(key)
  1128. ak = key.get("yiyan_ak", "")
  1129. sk = key.get("yiyan_sk", "")
  1130. self.client = qianfan.ChatCompletion(ak=ak, sk=sk)
  1131. self.model_name = model_name.lower()
  1132. self.system = ""
  1133. def chat(self, system, history, gen_conf):
  1134. if system:
  1135. self.system = system
  1136. gen_conf["penalty_score"] = (
  1137. (gen_conf.get("presence_penalty", 0) + gen_conf.get("frequency_penalty",
  1138. 0)) / 2
  1139. ) + 1
  1140. if "max_tokens" in gen_conf:
  1141. del gen_conf["max_tokens"]
  1142. ans = ""
  1143. try:
  1144. response = self.client.do(
  1145. model=self.model_name,
  1146. messages=history,
  1147. system=self.system,
  1148. **gen_conf
  1149. ).body
  1150. ans = response['result']
  1151. return ans, self.total_token_count(response)
  1152. except Exception as e:
  1153. return ans + "\n**ERROR**: " + str(e), 0
  1154. def chat_streamly(self, system, history, gen_conf):
  1155. if system:
  1156. self.system = system
  1157. gen_conf["penalty_score"] = (
  1158. (gen_conf.get("presence_penalty", 0) + gen_conf.get("frequency_penalty",
  1159. 0)) / 2
  1160. ) + 1
  1161. if "max_tokens" in gen_conf:
  1162. del gen_conf["max_tokens"]
  1163. ans = ""
  1164. total_tokens = 0
  1165. try:
  1166. response = self.client.do(
  1167. model=self.model_name,
  1168. messages=history,
  1169. system=self.system,
  1170. stream=True,
  1171. **gen_conf
  1172. )
  1173. for resp in response:
  1174. resp = resp.body
  1175. ans += resp['result']
  1176. total_tokens = self.total_token_count(resp)
  1177. yield ans
  1178. except Exception as e:
  1179. return ans + "\n**ERROR**: " + str(e), 0
  1180. yield total_tokens
  1181. class AnthropicChat(Base):
  1182. def __init__(self, key, model_name, base_url=None):
  1183. import anthropic
  1184. self.client = anthropic.Anthropic(api_key=key)
  1185. self.model_name = model_name
  1186. self.system = ""
  1187. def chat(self, system, history, gen_conf):
  1188. if system:
  1189. self.system = system
  1190. if "presence_penalty" in gen_conf:
  1191. del gen_conf["presence_penalty"]
  1192. if "frequency_penalty" in gen_conf:
  1193. del gen_conf["frequency_penalty"]
  1194. ans = ""
  1195. try:
  1196. response = self.client.messages.create(
  1197. model=self.model_name,
  1198. messages=history,
  1199. system=self.system,
  1200. stream=False,
  1201. **gen_conf,
  1202. ).to_dict()
  1203. ans = response["content"][0]["text"]
  1204. if response["stop_reason"] == "max_tokens":
  1205. ans += (
  1206. "...\nFor the content length reason, it stopped, continue?"
  1207. if is_english([ans])
  1208. else "······\n由于长度的原因,回答被截断了,要继续吗?"
  1209. )
  1210. return (
  1211. ans,
  1212. response["usage"]["input_tokens"] + response["usage"]["output_tokens"],
  1213. )
  1214. except Exception as e:
  1215. return ans + "\n**ERROR**: " + str(e), 0
  1216. def chat_streamly(self, system, history, gen_conf):
  1217. if system:
  1218. self.system = system
  1219. if "presence_penalty" in gen_conf:
  1220. del gen_conf["presence_penalty"]
  1221. if "frequency_penalty" in gen_conf:
  1222. del gen_conf["frequency_penalty"]
  1223. ans = ""
  1224. total_tokens = 0
  1225. try:
  1226. response = self.client.messages.create(
  1227. model=self.model_name,
  1228. messages=history,
  1229. system=self.system,
  1230. stream=True,
  1231. **gen_conf,
  1232. )
  1233. for res in response:
  1234. if res.type == 'content_block_delta':
  1235. text = res.delta.text
  1236. ans += text
  1237. total_tokens += num_tokens_from_string(text)
  1238. yield ans
  1239. except Exception as e:
  1240. yield ans + "\n**ERROR**: " + str(e)
  1241. yield total_tokens
  1242. class GoogleChat(Base):
  1243. def __init__(self, key, model_name, base_url=None):
  1244. from google.oauth2 import service_account
  1245. import base64
  1246. key = json.loads(key)
  1247. access_token = json.loads(
  1248. base64.b64decode(key.get("google_service_account_key", ""))
  1249. )
  1250. project_id = key.get("google_project_id", "")
  1251. region = key.get("google_region", "")
  1252. scopes = ["https://www.googleapis.com/auth/cloud-platform"]
  1253. self.model_name = model_name
  1254. self.system = ""
  1255. if "claude" in self.model_name:
  1256. from anthropic import AnthropicVertex
  1257. from google.auth.transport.requests import Request
  1258. if access_token:
  1259. credits = service_account.Credentials.from_service_account_info(
  1260. access_token, scopes=scopes
  1261. )
  1262. request = Request()
  1263. credits.refresh(request)
  1264. token = credits.token
  1265. self.client = AnthropicVertex(
  1266. region=region, project_id=project_id, access_token=token
  1267. )
  1268. else:
  1269. self.client = AnthropicVertex(region=region, project_id=project_id)
  1270. else:
  1271. from google.cloud import aiplatform
  1272. import vertexai.generative_models as glm
  1273. if access_token:
  1274. credits = service_account.Credentials.from_service_account_info(
  1275. access_token
  1276. )
  1277. aiplatform.init(
  1278. credentials=credits, project=project_id, location=region
  1279. )
  1280. else:
  1281. aiplatform.init(project=project_id, location=region)
  1282. self.client = glm.GenerativeModel(model_name=self.model_name)
  1283. def chat(self, system, history, gen_conf):
  1284. if system:
  1285. self.system = system
  1286. if "claude" in self.model_name:
  1287. if "max_tokens" in gen_conf:
  1288. del gen_conf["max_tokens"]
  1289. try:
  1290. response = self.client.messages.create(
  1291. model=self.model_name,
  1292. messages=history,
  1293. system=self.system,
  1294. stream=False,
  1295. **gen_conf,
  1296. ).json()
  1297. ans = response["content"][0]["text"]
  1298. if response["stop_reason"] == "max_tokens":
  1299. ans += (
  1300. "...\nFor the content length reason, it stopped, continue?"
  1301. if is_english([ans])
  1302. else "······\n由于长度的原因,回答被截断了,要继续吗?"
  1303. )
  1304. return (
  1305. ans,
  1306. response["usage"]["input_tokens"]
  1307. + response["usage"]["output_tokens"],
  1308. )
  1309. except Exception as e:
  1310. return "\n**ERROR**: " + str(e), 0
  1311. else:
  1312. self.client._system_instruction = self.system
  1313. if "max_tokens" in gen_conf:
  1314. gen_conf["max_output_tokens"] = gen_conf["max_tokens"]
  1315. for k in list(gen_conf.keys()):
  1316. if k not in ["temperature", "top_p", "max_output_tokens"]:
  1317. del gen_conf[k]
  1318. for item in history:
  1319. if "role" in item and item["role"] == "assistant":
  1320. item["role"] = "model"
  1321. if "content" in item:
  1322. item["parts"] = item.pop("content")
  1323. try:
  1324. response = self.client.generate_content(
  1325. history, generation_config=gen_conf
  1326. )
  1327. ans = response.text
  1328. return ans, response.usage_metadata.total_token_count
  1329. except Exception as e:
  1330. return "**ERROR**: " + str(e), 0
  1331. def chat_streamly(self, system, history, gen_conf):
  1332. if system:
  1333. self.system = system
  1334. if "claude" in self.model_name:
  1335. if "max_tokens" in gen_conf:
  1336. del gen_conf["max_tokens"]
  1337. ans = ""
  1338. total_tokens = 0
  1339. try:
  1340. response = self.client.messages.create(
  1341. model=self.model_name,
  1342. messages=history,
  1343. system=self.system,
  1344. stream=True,
  1345. **gen_conf,
  1346. )
  1347. for res in response.iter_lines():
  1348. res = res.decode("utf-8")
  1349. if "content_block_delta" in res and "data" in res:
  1350. text = json.loads(res[6:])["delta"]["text"]
  1351. ans += text
  1352. total_tokens += num_tokens_from_string(text)
  1353. except Exception as e:
  1354. yield ans + "\n**ERROR**: " + str(e)
  1355. yield total_tokens
  1356. else:
  1357. self.client._system_instruction = self.system
  1358. if "max_tokens" in gen_conf:
  1359. gen_conf["max_output_tokens"] = gen_conf["max_tokens"]
  1360. for k in list(gen_conf.keys()):
  1361. if k not in ["temperature", "top_p", "max_output_tokens"]:
  1362. del gen_conf[k]
  1363. for item in history:
  1364. if "role" in item and item["role"] == "assistant":
  1365. item["role"] = "model"
  1366. if "content" in item:
  1367. item["parts"] = item.pop("content")
  1368. ans = ""
  1369. try:
  1370. response = self.model.generate_content(
  1371. history, generation_config=gen_conf, stream=True
  1372. )
  1373. for resp in response:
  1374. ans += resp.text
  1375. yield ans
  1376. except Exception as e:
  1377. yield ans + "\n**ERROR**: " + str(e)
  1378. yield response._chunks[-1].usage_metadata.total_token_count
  1379. class GPUStackChat(Base):
  1380. def __init__(self, key=None, model_name="", base_url=""):
  1381. if not base_url:
  1382. raise ValueError("Local llm url cannot be None")
  1383. if base_url.split("/")[-1] != "v1-openai":
  1384. base_url = os.path.join(base_url, "v1-openai")
  1385. super().__init__(key, model_name, base_url)