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 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  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. from openai.lib.azure import AzureOpenAI
  17. from zhipuai import ZhipuAI
  18. from dashscope import Generation
  19. from abc import ABC
  20. from openai import OpenAI
  21. import openai
  22. from ollama import Client
  23. from volcengine.maas.v2 import MaasService
  24. from rag.nlp import is_english
  25. from rag.utils import num_tokens_from_string
  26. from groq import Groq
  27. import os
  28. import json
  29. import requests
  30. class Base(ABC):
  31. def __init__(self, key, model_name, base_url):
  32. self.client = OpenAI(api_key=key, base_url=base_url)
  33. self.model_name = model_name
  34. def chat(self, system, history, gen_conf):
  35. if system:
  36. history.insert(0, {"role": "system", "content": system})
  37. try:
  38. response = self.client.chat.completions.create(
  39. model=self.model_name,
  40. messages=history,
  41. **gen_conf)
  42. ans = response.choices[0].message.content.strip()
  43. if response.choices[0].finish_reason == "length":
  44. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  45. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  46. return ans, response.usage.total_tokens
  47. except openai.APIError as e:
  48. return "**ERROR**: " + str(e), 0
  49. def chat_streamly(self, system, history, gen_conf):
  50. if system:
  51. history.insert(0, {"role": "system", "content": system})
  52. ans = ""
  53. total_tokens = 0
  54. try:
  55. response = self.client.chat.completions.create(
  56. model=self.model_name,
  57. messages=history,
  58. stream=True,
  59. **gen_conf)
  60. for resp in response:
  61. if not resp.choices:continue
  62. ans += resp.choices[0].delta.content
  63. total_tokens = (
  64. (
  65. total_tokens
  66. + num_tokens_from_string(resp.choices[0].delta.content)
  67. )
  68. if not hasattr(resp, "usage")
  69. else resp.usage["total_tokens"]
  70. )
  71. if resp.choices[0].finish_reason == "length":
  72. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  73. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  74. yield ans
  75. except openai.APIError as e:
  76. yield ans + "\n**ERROR**: " + str(e)
  77. yield total_tokens
  78. class GptTurbo(Base):
  79. def __init__(self, key, model_name="gpt-3.5-turbo", base_url="https://api.openai.com/v1"):
  80. if not base_url: base_url="https://api.openai.com/v1"
  81. super().__init__(key, model_name, base_url)
  82. class MoonshotChat(Base):
  83. def __init__(self, key, model_name="moonshot-v1-8k", base_url="https://api.moonshot.cn/v1"):
  84. if not base_url: base_url="https://api.moonshot.cn/v1"
  85. super().__init__(key, model_name, base_url)
  86. class XinferenceChat(Base):
  87. def __init__(self, key=None, model_name="", base_url=""):
  88. if not base_url:
  89. raise ValueError("Local llm url cannot be None")
  90. if base_url.split("/")[-1] != "v1":
  91. self.base_url = os.path.join(base_url, "v1")
  92. key = "xxx"
  93. super().__init__(key, model_name, base_url)
  94. class DeepSeekChat(Base):
  95. def __init__(self, key, model_name="deepseek-chat", base_url="https://api.deepseek.com/v1"):
  96. if not base_url: base_url="https://api.deepseek.com/v1"
  97. super().__init__(key, model_name, base_url)
  98. class AzureChat(Base):
  99. def __init__(self, key, model_name, **kwargs):
  100. self.client = AzureOpenAI(api_key=key, azure_endpoint=kwargs["base_url"], api_version="2024-02-01")
  101. self.model_name = model_name
  102. class BaiChuanChat(Base):
  103. def __init__(self, key, model_name="Baichuan3-Turbo", base_url="https://api.baichuan-ai.com/v1"):
  104. if not base_url:
  105. base_url = "https://api.baichuan-ai.com/v1"
  106. super().__init__(key, model_name, base_url)
  107. @staticmethod
  108. def _format_params(params):
  109. return {
  110. "temperature": params.get("temperature", 0.3),
  111. "max_tokens": params.get("max_tokens", 2048),
  112. "top_p": params.get("top_p", 0.85),
  113. }
  114. def chat(self, system, history, gen_conf):
  115. if system:
  116. history.insert(0, {"role": "system", "content": system})
  117. try:
  118. response = self.client.chat.completions.create(
  119. model=self.model_name,
  120. messages=history,
  121. extra_body={
  122. "tools": [{
  123. "type": "web_search",
  124. "web_search": {
  125. "enable": True,
  126. "search_mode": "performance_first"
  127. }
  128. }]
  129. },
  130. **self._format_params(gen_conf))
  131. ans = response.choices[0].message.content.strip()
  132. if response.choices[0].finish_reason == "length":
  133. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  134. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  135. return ans, response.usage.total_tokens
  136. except openai.APIError as e:
  137. return "**ERROR**: " + str(e), 0
  138. def chat_streamly(self, system, history, gen_conf):
  139. if system:
  140. history.insert(0, {"role": "system", "content": system})
  141. ans = ""
  142. total_tokens = 0
  143. try:
  144. response = self.client.chat.completions.create(
  145. model=self.model_name,
  146. messages=history,
  147. extra_body={
  148. "tools": [{
  149. "type": "web_search",
  150. "web_search": {
  151. "enable": True,
  152. "search_mode": "performance_first"
  153. }
  154. }]
  155. },
  156. stream=True,
  157. **self._format_params(gen_conf))
  158. for resp in response:
  159. if resp.choices[0].finish_reason == "stop":
  160. if not resp.choices[0].delta.content:
  161. continue
  162. total_tokens = resp.usage.get('total_tokens', 0)
  163. if not resp.choices[0].delta.content:
  164. continue
  165. ans += resp.choices[0].delta.content
  166. if resp.choices[0].finish_reason == "length":
  167. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  168. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  169. yield ans
  170. except Exception as e:
  171. yield ans + "\n**ERROR**: " + str(e)
  172. yield total_tokens
  173. class QWenChat(Base):
  174. def __init__(self, key, model_name=Generation.Models.qwen_turbo, **kwargs):
  175. import dashscope
  176. dashscope.api_key = key
  177. self.model_name = model_name
  178. def chat(self, system, history, gen_conf):
  179. from http import HTTPStatus
  180. if system:
  181. history.insert(0, {"role": "system", "content": system})
  182. response = Generation.call(
  183. self.model_name,
  184. messages=history,
  185. result_format='message',
  186. **gen_conf
  187. )
  188. ans = ""
  189. tk_count = 0
  190. if response.status_code == HTTPStatus.OK:
  191. ans += response.output.choices[0]['message']['content']
  192. tk_count += response.usage.total_tokens
  193. if response.output.choices[0].get("finish_reason", "") == "length":
  194. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  195. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  196. return ans, tk_count
  197. return "**ERROR**: " + response.message, tk_count
  198. def chat_streamly(self, system, history, gen_conf):
  199. from http import HTTPStatus
  200. if system:
  201. history.insert(0, {"role": "system", "content": system})
  202. ans = ""
  203. tk_count = 0
  204. try:
  205. response = Generation.call(
  206. self.model_name,
  207. messages=history,
  208. result_format='message',
  209. stream=True,
  210. **gen_conf
  211. )
  212. for resp in response:
  213. if resp.status_code == HTTPStatus.OK:
  214. ans = resp.output.choices[0]['message']['content']
  215. tk_count = resp.usage.total_tokens
  216. if resp.output.choices[0].get("finish_reason", "") == "length":
  217. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  218. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  219. yield ans
  220. else:
  221. yield ans + "\n**ERROR**: " + resp.message if str(resp.message).find("Access")<0 else "Out of credit. Please set the API key in **settings > Model providers.**"
  222. except Exception as e:
  223. yield ans + "\n**ERROR**: " + str(e)
  224. yield tk_count
  225. class ZhipuChat(Base):
  226. def __init__(self, key, model_name="glm-3-turbo", **kwargs):
  227. self.client = ZhipuAI(api_key=key)
  228. self.model_name = model_name
  229. def chat(self, system, history, gen_conf):
  230. if system:
  231. history.insert(0, {"role": "system", "content": system})
  232. try:
  233. if "presence_penalty" in gen_conf: del gen_conf["presence_penalty"]
  234. if "frequency_penalty" in gen_conf: del gen_conf["frequency_penalty"]
  235. response = self.client.chat.completions.create(
  236. model=self.model_name,
  237. messages=history,
  238. **gen_conf
  239. )
  240. ans = response.choices[0].message.content.strip()
  241. if response.choices[0].finish_reason == "length":
  242. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  243. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  244. return ans, response.usage.total_tokens
  245. except Exception as e:
  246. return "**ERROR**: " + str(e), 0
  247. def chat_streamly(self, system, history, gen_conf):
  248. if system:
  249. history.insert(0, {"role": "system", "content": system})
  250. if "presence_penalty" in gen_conf: del gen_conf["presence_penalty"]
  251. if "frequency_penalty" in gen_conf: del gen_conf["frequency_penalty"]
  252. ans = ""
  253. tk_count = 0
  254. try:
  255. response = self.client.chat.completions.create(
  256. model=self.model_name,
  257. messages=history,
  258. stream=True,
  259. **gen_conf
  260. )
  261. for resp in response:
  262. if not resp.choices[0].delta.content:continue
  263. delta = resp.choices[0].delta.content
  264. ans += delta
  265. if resp.choices[0].finish_reason == "length":
  266. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  267. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  268. tk_count = resp.usage.total_tokens
  269. if resp.choices[0].finish_reason == "stop": tk_count = resp.usage.total_tokens
  270. yield ans
  271. except Exception as e:
  272. yield ans + "\n**ERROR**: " + str(e)
  273. yield tk_count
  274. class OllamaChat(Base):
  275. def __init__(self, key, model_name, **kwargs):
  276. self.client = Client(host=kwargs["base_url"])
  277. self.model_name = model_name
  278. def chat(self, system, history, gen_conf):
  279. if system:
  280. history.insert(0, {"role": "system", "content": system})
  281. try:
  282. options = {}
  283. if "temperature" in gen_conf: options["temperature"] = gen_conf["temperature"]
  284. if "max_tokens" in gen_conf: options["num_predict"] = gen_conf["max_tokens"]
  285. if "top_p" in gen_conf: options["top_k"] = gen_conf["top_p"]
  286. if "presence_penalty" in gen_conf: options["presence_penalty"] = gen_conf["presence_penalty"]
  287. if "frequency_penalty" in gen_conf: options["frequency_penalty"] = gen_conf["frequency_penalty"]
  288. response = self.client.chat(
  289. model=self.model_name,
  290. messages=history,
  291. options=options,
  292. keep_alive=-1
  293. )
  294. ans = response["message"]["content"].strip()
  295. return ans, response["eval_count"] + response.get("prompt_eval_count", 0)
  296. except Exception as e:
  297. return "**ERROR**: " + str(e), 0
  298. def chat_streamly(self, system, history, gen_conf):
  299. if system:
  300. history.insert(0, {"role": "system", "content": system})
  301. options = {}
  302. if "temperature" in gen_conf: options["temperature"] = gen_conf["temperature"]
  303. if "max_tokens" in gen_conf: options["num_predict"] = gen_conf["max_tokens"]
  304. if "top_p" in gen_conf: options["top_k"] = gen_conf["top_p"]
  305. if "presence_penalty" in gen_conf: options["presence_penalty"] = gen_conf["presence_penalty"]
  306. if "frequency_penalty" in gen_conf: options["frequency_penalty"] = gen_conf["frequency_penalty"]
  307. ans = ""
  308. try:
  309. response = self.client.chat(
  310. model=self.model_name,
  311. messages=history,
  312. stream=True,
  313. options=options,
  314. keep_alive=-1
  315. )
  316. for resp in response:
  317. if resp["done"]:
  318. yield resp.get("prompt_eval_count", 0) + resp.get("eval_count", 0)
  319. ans += resp["message"]["content"]
  320. yield ans
  321. except Exception as e:
  322. yield ans + "\n**ERROR**: " + str(e)
  323. yield 0
  324. class LocalAIChat(Base):
  325. def __init__(self, key, model_name, base_url):
  326. if not base_url:
  327. raise ValueError("Local llm url cannot be None")
  328. if base_url.split("/")[-1] != "v1":
  329. self.base_url = os.path.join(base_url, "v1")
  330. self.client = OpenAI(api_key="empty", base_url=self.base_url)
  331. self.model_name = model_name.split("___")[0]
  332. class LocalLLM(Base):
  333. class RPCProxy:
  334. def __init__(self, host, port):
  335. self.host = host
  336. self.port = int(port)
  337. self.__conn()
  338. def __conn(self):
  339. from multiprocessing.connection import Client
  340. self._connection = Client(
  341. (self.host, self.port), authkey=b'infiniflow-token4kevinhu')
  342. def __getattr__(self, name):
  343. import pickle
  344. def do_rpc(*args, **kwargs):
  345. for _ in range(3):
  346. try:
  347. self._connection.send(
  348. pickle.dumps((name, args, kwargs)))
  349. return pickle.loads(self._connection.recv())
  350. except Exception as e:
  351. self.__conn()
  352. raise Exception("RPC connection lost!")
  353. return do_rpc
  354. def __init__(self, key, model_name="glm-3-turbo"):
  355. self.client = LocalLLM.RPCProxy("127.0.0.1", 7860)
  356. def chat(self, system, history, gen_conf):
  357. if system:
  358. history.insert(0, {"role": "system", "content": system})
  359. try:
  360. ans = self.client.chat(
  361. history,
  362. gen_conf
  363. )
  364. return ans, num_tokens_from_string(ans)
  365. except Exception as e:
  366. return "**ERROR**: " + str(e), 0
  367. def chat_streamly(self, system, history, gen_conf):
  368. if system:
  369. history.insert(0, {"role": "system", "content": system})
  370. token_count = 0
  371. answer = ""
  372. try:
  373. for ans in self.client.chat_streamly(history, gen_conf):
  374. answer += ans
  375. token_count += 1
  376. yield answer
  377. except Exception as e:
  378. yield answer + "\n**ERROR**: " + str(e)
  379. yield token_count
  380. class VolcEngineChat(Base):
  381. def __init__(self, key, model_name, base_url):
  382. """
  383. Since do not want to modify the original database fields, and the VolcEngine authentication method is quite special,
  384. Assemble ak, sk, ep_id into api_key, store it as a dictionary type, and parse it for use
  385. model_name is for display only
  386. """
  387. self.client = MaasService('maas-api.ml-platform-cn-beijing.volces.com', 'cn-beijing')
  388. self.volc_ak = eval(key).get('volc_ak', '')
  389. self.volc_sk = eval(key).get('volc_sk', '')
  390. self.client.set_ak(self.volc_ak)
  391. self.client.set_sk(self.volc_sk)
  392. self.model_name = eval(key).get('ep_id', '')
  393. def chat(self, system, history, gen_conf):
  394. if system:
  395. history.insert(0, {"role": "system", "content": system})
  396. try:
  397. req = {
  398. "parameters": {
  399. "min_new_tokens": gen_conf.get("min_new_tokens", 1),
  400. "top_k": gen_conf.get("top_k", 0),
  401. "max_prompt_tokens": gen_conf.get("max_prompt_tokens", 30000),
  402. "temperature": gen_conf.get("temperature", 0.1),
  403. "max_new_tokens": gen_conf.get("max_tokens", 1000),
  404. "top_p": gen_conf.get("top_p", 0.3),
  405. },
  406. "messages": history
  407. }
  408. response = self.client.chat(self.model_name, req)
  409. ans = response.choices[0].message.content.strip()
  410. if response.choices[0].finish_reason == "length":
  411. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  412. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  413. return ans, response.usage.total_tokens
  414. except Exception as e:
  415. return "**ERROR**: " + str(e), 0
  416. def chat_streamly(self, system, history, gen_conf):
  417. if system:
  418. history.insert(0, {"role": "system", "content": system})
  419. ans = ""
  420. tk_count = 0
  421. try:
  422. req = {
  423. "parameters": {
  424. "min_new_tokens": gen_conf.get("min_new_tokens", 1),
  425. "top_k": gen_conf.get("top_k", 0),
  426. "max_prompt_tokens": gen_conf.get("max_prompt_tokens", 30000),
  427. "temperature": gen_conf.get("temperature", 0.1),
  428. "max_new_tokens": gen_conf.get("max_tokens", 1000),
  429. "top_p": gen_conf.get("top_p", 0.3),
  430. },
  431. "messages": history
  432. }
  433. stream = self.client.stream_chat(self.model_name, req)
  434. for resp in stream:
  435. if not resp.choices[0].message.content:
  436. continue
  437. ans += resp.choices[0].message.content
  438. if resp.choices[0].finish_reason == "stop":
  439. tk_count = resp.usage.total_tokens
  440. yield ans
  441. except Exception as e:
  442. yield ans + "\n**ERROR**: " + str(e)
  443. yield tk_count
  444. class MiniMaxChat(Base):
  445. def __init__(
  446. self,
  447. key,
  448. model_name,
  449. base_url="https://api.minimax.chat/v1/text/chatcompletion_v2",
  450. ):
  451. if not base_url:
  452. base_url = "https://api.minimax.chat/v1/text/chatcompletion_v2"
  453. self.base_url = base_url
  454. self.model_name = model_name
  455. self.api_key = key
  456. def chat(self, system, history, gen_conf):
  457. if system:
  458. history.insert(0, {"role": "system", "content": system})
  459. for k in list(gen_conf.keys()):
  460. if k not in ["temperature", "top_p", "max_tokens"]:
  461. del gen_conf[k]
  462. headers = {
  463. "Authorization": f"Bearer {self.api_key}",
  464. "Content-Type": "application/json",
  465. }
  466. payload = json.dumps(
  467. {"model": self.model_name, "messages": history, **gen_conf}
  468. )
  469. try:
  470. response = requests.request(
  471. "POST", url=self.base_url, headers=headers, data=payload
  472. )
  473. response = response.json()
  474. ans = response["choices"][0]["message"]["content"].strip()
  475. if response["choices"][0]["finish_reason"] == "length":
  476. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  477. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  478. return ans, response["usage"]["total_tokens"]
  479. except Exception as e:
  480. return "**ERROR**: " + str(e), 0
  481. def chat_streamly(self, system, history, gen_conf):
  482. if system:
  483. history.insert(0, {"role": "system", "content": system})
  484. ans = ""
  485. total_tokens = 0
  486. try:
  487. headers = {
  488. "Authorization": f"Bearer {self.api_key}",
  489. "Content-Type": "application/json",
  490. }
  491. payload = json.dumps(
  492. {
  493. "model": self.model_name,
  494. "messages": history,
  495. "stream": True,
  496. **gen_conf,
  497. }
  498. )
  499. response = requests.request(
  500. "POST",
  501. url=self.base_url,
  502. headers=headers,
  503. data=payload,
  504. )
  505. for resp in response.text.split("\n\n")[:-1]:
  506. resp = json.loads(resp[6:])
  507. if "delta" in resp["choices"][0]:
  508. text = resp["choices"][0]["delta"]["content"]
  509. else:
  510. continue
  511. ans += text
  512. total_tokens += num_tokens_from_string(text)
  513. yield ans
  514. except Exception as e:
  515. yield ans + "\n**ERROR**: " + str(e)
  516. yield total_tokens
  517. class MistralChat(Base):
  518. def __init__(self, key, model_name, base_url=None):
  519. from mistralai.client import MistralClient
  520. self.client = MistralClient(api_key=key)
  521. self.model_name = model_name
  522. def chat(self, system, history, gen_conf):
  523. if system:
  524. history.insert(0, {"role": "system", "content": system})
  525. for k in list(gen_conf.keys()):
  526. if k not in ["temperature", "top_p", "max_tokens"]:
  527. del gen_conf[k]
  528. try:
  529. response = self.client.chat(
  530. model=self.model_name,
  531. messages=history,
  532. **gen_conf)
  533. ans = response.choices[0].message.content
  534. if response.choices[0].finish_reason == "length":
  535. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  536. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  537. return ans, response.usage.total_tokens
  538. except openai.APIError as e:
  539. return "**ERROR**: " + str(e), 0
  540. def chat_streamly(self, system, history, gen_conf):
  541. if system:
  542. history.insert(0, {"role": "system", "content": system})
  543. for k in list(gen_conf.keys()):
  544. if k not in ["temperature", "top_p", "max_tokens"]:
  545. del gen_conf[k]
  546. ans = ""
  547. total_tokens = 0
  548. try:
  549. response = self.client.chat_stream(
  550. model=self.model_name,
  551. messages=history,
  552. **gen_conf)
  553. for resp in response:
  554. if not resp.choices or not resp.choices[0].delta.content:continue
  555. ans += resp.choices[0].delta.content
  556. total_tokens += 1
  557. if resp.choices[0].finish_reason == "length":
  558. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  559. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  560. yield ans
  561. except openai.APIError as e:
  562. yield ans + "\n**ERROR**: " + str(e)
  563. yield total_tokens
  564. class BedrockChat(Base):
  565. def __init__(self, key, model_name, **kwargs):
  566. import boto3
  567. self.bedrock_ak = eval(key).get('bedrock_ak', '')
  568. self.bedrock_sk = eval(key).get('bedrock_sk', '')
  569. self.bedrock_region = eval(key).get('bedrock_region', '')
  570. self.model_name = model_name
  571. self.client = boto3.client(service_name='bedrock-runtime', region_name=self.bedrock_region,
  572. aws_access_key_id=self.bedrock_ak, aws_secret_access_key=self.bedrock_sk)
  573. def chat(self, system, history, gen_conf):
  574. from botocore.exceptions import ClientError
  575. if system:
  576. history.insert(0, {"role": "system", "content": system})
  577. for k in list(gen_conf.keys()):
  578. if k not in ["temperature", "top_p", "max_tokens"]:
  579. del gen_conf[k]
  580. if "max_tokens" in gen_conf:
  581. gen_conf["maxTokens"] = gen_conf["max_tokens"]
  582. _ = gen_conf.pop("max_tokens")
  583. if "top_p" in gen_conf:
  584. gen_conf["topP"] = gen_conf["top_p"]
  585. _ = gen_conf.pop("top_p")
  586. try:
  587. # Send the message to the model, using a basic inference configuration.
  588. response = self.client.converse(
  589. modelId=self.model_name,
  590. messages=history,
  591. inferenceConfig=gen_conf
  592. )
  593. # Extract and print the response text.
  594. ans = response["output"]["message"]["content"][0]["text"]
  595. return ans, num_tokens_from_string(ans)
  596. except (ClientError, Exception) as e:
  597. return f"ERROR: Can't invoke '{self.model_name}'. Reason: {e}", 0
  598. def chat_streamly(self, system, history, gen_conf):
  599. from botocore.exceptions import ClientError
  600. if system:
  601. history.insert(0, {"role": "system", "content": system})
  602. for k in list(gen_conf.keys()):
  603. if k not in ["temperature", "top_p", "max_tokens"]:
  604. del gen_conf[k]
  605. if "max_tokens" in gen_conf:
  606. gen_conf["maxTokens"] = gen_conf["max_tokens"]
  607. _ = gen_conf.pop("max_tokens")
  608. if "top_p" in gen_conf:
  609. gen_conf["topP"] = gen_conf["top_p"]
  610. _ = gen_conf.pop("top_p")
  611. if self.model_name.split('.')[0] == 'ai21':
  612. try:
  613. response = self.client.converse(
  614. modelId=self.model_name,
  615. messages=history,
  616. inferenceConfig=gen_conf
  617. )
  618. ans = response["output"]["message"]["content"][0]["text"]
  619. return ans, num_tokens_from_string(ans)
  620. except (ClientError, Exception) as e:
  621. return f"ERROR: Can't invoke '{self.model_name}'. Reason: {e}", 0
  622. ans = ""
  623. try:
  624. # Send the message to the model, using a basic inference configuration.
  625. streaming_response = self.client.converse_stream(
  626. modelId=self.model_name,
  627. messages=history,
  628. inferenceConfig=gen_conf
  629. )
  630. # Extract and print the streamed response text in real-time.
  631. for resp in streaming_response["stream"]:
  632. if "contentBlockDelta" in resp:
  633. ans += resp["contentBlockDelta"]["delta"]["text"]
  634. yield ans
  635. except (ClientError, Exception) as e:
  636. yield ans + f"ERROR: Can't invoke '{self.model_name}'. Reason: {e}"
  637. yield num_tokens_from_string(ans)
  638. class GeminiChat(Base):
  639. def __init__(self, key, model_name,base_url=None):
  640. from google.generativeai import client,GenerativeModel
  641. client.configure(api_key=key)
  642. _client = client.get_default_generative_client()
  643. self.model_name = 'models/' + model_name
  644. self.model = GenerativeModel(model_name=self.model_name)
  645. self.model._client = _client
  646. def chat(self,system,history,gen_conf):
  647. if system:
  648. history.insert(0, {"role": "user", "parts": system})
  649. if 'max_tokens' in gen_conf:
  650. gen_conf['max_output_tokens'] = gen_conf['max_tokens']
  651. for k in list(gen_conf.keys()):
  652. if k not in ["temperature", "top_p", "max_output_tokens"]:
  653. del gen_conf[k]
  654. for item in history:
  655. if 'role' in item and item['role'] == 'assistant':
  656. item['role'] = 'model'
  657. if 'content' in item :
  658. item['parts'] = item.pop('content')
  659. try:
  660. response = self.model.generate_content(
  661. history,
  662. generation_config=gen_conf)
  663. ans = response.text
  664. return ans, response.usage_metadata.total_token_count
  665. except Exception as e:
  666. return "**ERROR**: " + str(e), 0
  667. def chat_streamly(self, system, history, gen_conf):
  668. if system:
  669. history.insert(0, {"role": "user", "parts": system})
  670. if 'max_tokens' in gen_conf:
  671. gen_conf['max_output_tokens'] = gen_conf['max_tokens']
  672. for k in list(gen_conf.keys()):
  673. if k not in ["temperature", "top_p", "max_output_tokens"]:
  674. del gen_conf[k]
  675. for item in history:
  676. if 'role' in item and item['role'] == 'assistant':
  677. item['role'] = 'model'
  678. if 'content' in item :
  679. item['parts'] = item.pop('content')
  680. ans = ""
  681. try:
  682. response = self.model.generate_content(
  683. history,
  684. generation_config=gen_conf,stream=True)
  685. for resp in response:
  686. ans += resp.text
  687. yield ans
  688. except Exception as e:
  689. yield ans + "\n**ERROR**: " + str(e)
  690. yield response._chunks[-1].usage_metadata.total_token_count
  691. class GroqChat:
  692. def __init__(self, key, model_name,base_url=''):
  693. self.client = Groq(api_key=key)
  694. self.model_name = model_name
  695. def chat(self, system, history, gen_conf):
  696. if system:
  697. history.insert(0, {"role": "system", "content": system})
  698. for k in list(gen_conf.keys()):
  699. if k not in ["temperature", "top_p", "max_tokens"]:
  700. del gen_conf[k]
  701. ans = ""
  702. try:
  703. response = self.client.chat.completions.create(
  704. model=self.model_name,
  705. messages=history,
  706. **gen_conf
  707. )
  708. ans = response.choices[0].message.content
  709. if response.choices[0].finish_reason == "length":
  710. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  711. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  712. return ans, response.usage.total_tokens
  713. except Exception as e:
  714. return ans + "\n**ERROR**: " + str(e), 0
  715. def chat_streamly(self, system, history, gen_conf):
  716. if system:
  717. history.insert(0, {"role": "system", "content": system})
  718. for k in list(gen_conf.keys()):
  719. if k not in ["temperature", "top_p", "max_tokens"]:
  720. del gen_conf[k]
  721. ans = ""
  722. total_tokens = 0
  723. try:
  724. response = self.client.chat.completions.create(
  725. model=self.model_name,
  726. messages=history,
  727. stream=True,
  728. **gen_conf
  729. )
  730. for resp in response:
  731. if not resp.choices or not resp.choices[0].delta.content:
  732. continue
  733. ans += resp.choices[0].delta.content
  734. total_tokens += 1
  735. if resp.choices[0].finish_reason == "length":
  736. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  737. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  738. yield ans
  739. except Exception as e:
  740. yield ans + "\n**ERROR**: " + str(e)
  741. yield total_tokens
  742. ## openrouter
  743. class OpenRouterChat(Base):
  744. def __init__(self, key, model_name, base_url="https://openrouter.ai/api/v1"):
  745. if not base_url:
  746. base_url = "https://openrouter.ai/api/v1"
  747. super().__init__(key, model_name, base_url)
  748. class StepFunChat(Base):
  749. def __init__(self, key, model_name, base_url="https://api.stepfun.com/v1"):
  750. if not base_url:
  751. base_url = "https://api.stepfun.com/v1"
  752. super().__init__(key, model_name, base_url)
  753. class NvidiaChat(Base):
  754. def __init__(self, key, model_name, base_url="https://integrate.api.nvidia.com/v1"):
  755. if not base_url:
  756. base_url = "https://integrate.api.nvidia.com/v1"
  757. super().__init__(key, model_name, base_url)
  758. class LmStudioChat(Base):
  759. def __init__(self, key, model_name, base_url):
  760. if not base_url:
  761. raise ValueError("Local llm url cannot be None")
  762. if base_url.split("/")[-1] != "v1":
  763. self.base_url = os.path.join(base_url, "v1")
  764. self.client = OpenAI(api_key="lm-studio", base_url=self.base_url)
  765. self.model_name = model_name