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

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