You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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