Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

chat_model.py 40KB

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