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

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