Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259
  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='https://ark.cn-beijing.volces.com/api/v3'):
  400. """
  401. Since do not want to modify the original database fields, and the VolcEngine authentication method is quite special,
  402. Assemble ark_api_key, 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. base_url = base_url if base_url else 'https://ark.cn-beijing.volces.com/api/v3'
  406. ark_api_key = json.loads(key).get('ark_api_key', '')
  407. model_name = json.loads(key).get('ep_id', '')
  408. super().__init__(ark_api_key, model_name, base_url)
  409. class MiniMaxChat(Base):
  410. def __init__(
  411. self,
  412. key,
  413. model_name,
  414. base_url="https://api.minimax.chat/v1/text/chatcompletion_v2",
  415. ):
  416. if not base_url:
  417. base_url = "https://api.minimax.chat/v1/text/chatcompletion_v2"
  418. self.base_url = base_url
  419. self.model_name = model_name
  420. self.api_key = key
  421. def chat(self, system, history, gen_conf):
  422. if system:
  423. history.insert(0, {"role": "system", "content": system})
  424. for k in list(gen_conf.keys()):
  425. if k not in ["temperature", "top_p", "max_tokens"]:
  426. del gen_conf[k]
  427. headers = {
  428. "Authorization": f"Bearer {self.api_key}",
  429. "Content-Type": "application/json",
  430. }
  431. payload = json.dumps(
  432. {"model": self.model_name, "messages": history, **gen_conf}
  433. )
  434. try:
  435. response = requests.request(
  436. "POST", url=self.base_url, headers=headers, data=payload
  437. )
  438. response = response.json()
  439. ans = response["choices"][0]["message"]["content"].strip()
  440. if response["choices"][0]["finish_reason"] == "length":
  441. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  442. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  443. return ans, response["usage"]["total_tokens"]
  444. except Exception as e:
  445. return "**ERROR**: " + str(e), 0
  446. def chat_streamly(self, system, history, gen_conf):
  447. if system:
  448. history.insert(0, {"role": "system", "content": system})
  449. ans = ""
  450. total_tokens = 0
  451. try:
  452. headers = {
  453. "Authorization": f"Bearer {self.api_key}",
  454. "Content-Type": "application/json",
  455. }
  456. payload = json.dumps(
  457. {
  458. "model": self.model_name,
  459. "messages": history,
  460. "stream": True,
  461. **gen_conf,
  462. }
  463. )
  464. response = requests.request(
  465. "POST",
  466. url=self.base_url,
  467. headers=headers,
  468. data=payload,
  469. )
  470. for resp in response.text.split("\n\n")[:-1]:
  471. resp = json.loads(resp[6:])
  472. text = ""
  473. if "choices" in resp and "delta" in resp["choices"][0]:
  474. text = resp["choices"][0]["delta"]["content"]
  475. ans += text
  476. total_tokens = (
  477. total_tokens + num_tokens_from_string(text)
  478. if "usage" not in resp
  479. else resp["usage"]["total_tokens"]
  480. )
  481. yield ans
  482. except Exception as e:
  483. yield ans + "\n**ERROR**: " + str(e)
  484. yield total_tokens
  485. class MistralChat(Base):
  486. def __init__(self, key, model_name, base_url=None):
  487. from mistralai.client import MistralClient
  488. self.client = MistralClient(api_key=key)
  489. self.model_name = model_name
  490. def chat(self, system, history, gen_conf):
  491. if system:
  492. history.insert(0, {"role": "system", "content": system})
  493. for k in list(gen_conf.keys()):
  494. if k not in ["temperature", "top_p", "max_tokens"]:
  495. del gen_conf[k]
  496. try:
  497. response = self.client.chat(
  498. model=self.model_name,
  499. messages=history,
  500. **gen_conf)
  501. ans = response.choices[0].message.content
  502. if response.choices[0].finish_reason == "length":
  503. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  504. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  505. return ans, response.usage.total_tokens
  506. except openai.APIError as e:
  507. return "**ERROR**: " + str(e), 0
  508. def chat_streamly(self, system, history, gen_conf):
  509. if system:
  510. history.insert(0, {"role": "system", "content": system})
  511. for k in list(gen_conf.keys()):
  512. if k not in ["temperature", "top_p", "max_tokens"]:
  513. del gen_conf[k]
  514. ans = ""
  515. total_tokens = 0
  516. try:
  517. response = self.client.chat_stream(
  518. model=self.model_name,
  519. messages=history,
  520. **gen_conf)
  521. for resp in response:
  522. if not resp.choices or not resp.choices[0].delta.content:continue
  523. ans += resp.choices[0].delta.content
  524. total_tokens += 1
  525. if resp.choices[0].finish_reason == "length":
  526. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  527. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  528. yield ans
  529. except openai.APIError as e:
  530. yield ans + "\n**ERROR**: " + str(e)
  531. yield total_tokens
  532. class BedrockChat(Base):
  533. def __init__(self, key, model_name, **kwargs):
  534. import boto3
  535. self.bedrock_ak = json.loads(key).get('bedrock_ak', '')
  536. self.bedrock_sk = json.loads(key).get('bedrock_sk', '')
  537. self.bedrock_region = json.loads(key).get('bedrock_region', '')
  538. self.model_name = model_name
  539. self.client = boto3.client(service_name='bedrock-runtime', region_name=self.bedrock_region,
  540. aws_access_key_id=self.bedrock_ak, aws_secret_access_key=self.bedrock_sk)
  541. def chat(self, system, history, gen_conf):
  542. from botocore.exceptions import ClientError
  543. for k in list(gen_conf.keys()):
  544. if k not in ["temperature", "top_p", "max_tokens"]:
  545. del gen_conf[k]
  546. if "max_tokens" in gen_conf:
  547. gen_conf["maxTokens"] = gen_conf["max_tokens"]
  548. _ = gen_conf.pop("max_tokens")
  549. if "top_p" in gen_conf:
  550. gen_conf["topP"] = gen_conf["top_p"]
  551. _ = gen_conf.pop("top_p")
  552. for item in history:
  553. if not isinstance(item["content"],list) and not isinstance(item["content"],tuple):
  554. item["content"] = [{"text":item["content"]}]
  555. try:
  556. # Send the message to the model, using a basic inference configuration.
  557. response = self.client.converse(
  558. modelId=self.model_name,
  559. messages=history,
  560. inferenceConfig=gen_conf,
  561. system=[{"text": system}] if system else None,
  562. )
  563. # Extract and print the response text.
  564. ans = response["output"]["message"]["content"][0]["text"]
  565. return ans, num_tokens_from_string(ans)
  566. except (ClientError, Exception) as e:
  567. return f"ERROR: Can't invoke '{self.model_name}'. Reason: {e}", 0
  568. def chat_streamly(self, system, history, gen_conf):
  569. from botocore.exceptions import ClientError
  570. for k in list(gen_conf.keys()):
  571. if k not in ["temperature", "top_p", "max_tokens"]:
  572. del gen_conf[k]
  573. if "max_tokens" in gen_conf:
  574. gen_conf["maxTokens"] = gen_conf["max_tokens"]
  575. _ = gen_conf.pop("max_tokens")
  576. if "top_p" in gen_conf:
  577. gen_conf["topP"] = gen_conf["top_p"]
  578. _ = gen_conf.pop("top_p")
  579. for item in history:
  580. if not isinstance(item["content"],list) and not isinstance(item["content"],tuple):
  581. item["content"] = [{"text":item["content"]}]
  582. if self.model_name.split('.')[0] == 'ai21':
  583. try:
  584. response = self.client.converse(
  585. modelId=self.model_name,
  586. messages=history,
  587. inferenceConfig=gen_conf,
  588. system=[{"text": system}] if system else None,
  589. )
  590. ans = response["output"]["message"]["content"][0]["text"]
  591. return ans, num_tokens_from_string(ans)
  592. except (ClientError, Exception) as e:
  593. return f"ERROR: Can't invoke '{self.model_name}'. Reason: {e}", 0
  594. ans = ""
  595. try:
  596. # Send the message to the model, using a basic inference configuration.
  597. streaming_response = self.client.converse_stream(
  598. modelId=self.model_name,
  599. messages=history,
  600. inferenceConfig=gen_conf
  601. )
  602. # Extract and print the streamed response text in real-time.
  603. for resp in streaming_response["stream"]:
  604. if "contentBlockDelta" in resp:
  605. ans += resp["contentBlockDelta"]["delta"]["text"]
  606. yield ans
  607. except (ClientError, Exception) as e:
  608. yield ans + f"ERROR: Can't invoke '{self.model_name}'. Reason: {e}"
  609. yield num_tokens_from_string(ans)
  610. class GeminiChat(Base):
  611. def __init__(self, key, model_name,base_url=None):
  612. from google.generativeai import client,GenerativeModel
  613. client.configure(api_key=key)
  614. _client = client.get_default_generative_client()
  615. self.model_name = 'models/' + model_name
  616. self.model = GenerativeModel(model_name=self.model_name)
  617. self.model._client = _client
  618. def chat(self,system,history,gen_conf):
  619. if system:
  620. history.insert(0, {"role": "user", "parts": system})
  621. if 'max_tokens' in gen_conf:
  622. gen_conf['max_output_tokens'] = gen_conf['max_tokens']
  623. for k in list(gen_conf.keys()):
  624. if k not in ["temperature", "top_p", "max_output_tokens"]:
  625. del gen_conf[k]
  626. for item in history:
  627. if 'role' in item and item['role'] == 'assistant':
  628. item['role'] = 'model'
  629. if 'content' in item :
  630. item['parts'] = item.pop('content')
  631. try:
  632. response = self.model.generate_content(
  633. history,
  634. generation_config=gen_conf)
  635. ans = response.text
  636. return ans, response.usage_metadata.total_token_count
  637. except Exception as e:
  638. return "**ERROR**: " + str(e), 0
  639. def chat_streamly(self, system, history, gen_conf):
  640. if system:
  641. history.insert(0, {"role": "user", "parts": system})
  642. if 'max_tokens' in gen_conf:
  643. gen_conf['max_output_tokens'] = gen_conf['max_tokens']
  644. for k in list(gen_conf.keys()):
  645. if k not in ["temperature", "top_p", "max_output_tokens"]:
  646. del gen_conf[k]
  647. for item in history:
  648. if 'role' in item and item['role'] == 'assistant':
  649. item['role'] = 'model'
  650. if 'content' in item :
  651. item['parts'] = item.pop('content')
  652. ans = ""
  653. try:
  654. response = self.model.generate_content(
  655. history,
  656. generation_config=gen_conf,stream=True)
  657. for resp in response:
  658. ans += resp.text
  659. yield ans
  660. except Exception as e:
  661. yield ans + "\n**ERROR**: " + str(e)
  662. yield response._chunks[-1].usage_metadata.total_token_count
  663. class GroqChat:
  664. def __init__(self, key, model_name,base_url=''):
  665. self.client = Groq(api_key=key)
  666. self.model_name = model_name
  667. def chat(self, system, history, gen_conf):
  668. if system:
  669. history.insert(0, {"role": "system", "content": system})
  670. for k in list(gen_conf.keys()):
  671. if k not in ["temperature", "top_p", "max_tokens"]:
  672. del gen_conf[k]
  673. ans = ""
  674. try:
  675. response = self.client.chat.completions.create(
  676. model=self.model_name,
  677. messages=history,
  678. **gen_conf
  679. )
  680. ans = response.choices[0].message.content
  681. if response.choices[0].finish_reason == "length":
  682. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  683. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  684. return ans, response.usage.total_tokens
  685. except Exception as e:
  686. return ans + "\n**ERROR**: " + str(e), 0
  687. def chat_streamly(self, system, history, gen_conf):
  688. if system:
  689. history.insert(0, {"role": "system", "content": system})
  690. for k in list(gen_conf.keys()):
  691. if k not in ["temperature", "top_p", "max_tokens"]:
  692. del gen_conf[k]
  693. ans = ""
  694. total_tokens = 0
  695. try:
  696. response = self.client.chat.completions.create(
  697. model=self.model_name,
  698. messages=history,
  699. stream=True,
  700. **gen_conf
  701. )
  702. for resp in response:
  703. if not resp.choices or not resp.choices[0].delta.content:
  704. continue
  705. ans += resp.choices[0].delta.content
  706. total_tokens += 1
  707. if resp.choices[0].finish_reason == "length":
  708. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  709. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  710. yield ans
  711. except Exception as e:
  712. yield ans + "\n**ERROR**: " + str(e)
  713. yield total_tokens
  714. ## openrouter
  715. class OpenRouterChat(Base):
  716. def __init__(self, key, model_name, base_url="https://openrouter.ai/api/v1"):
  717. if not base_url:
  718. base_url = "https://openrouter.ai/api/v1"
  719. super().__init__(key, model_name, base_url)
  720. class StepFunChat(Base):
  721. def __init__(self, key, model_name, base_url="https://api.stepfun.com/v1"):
  722. if not base_url:
  723. base_url = "https://api.stepfun.com/v1"
  724. super().__init__(key, model_name, base_url)
  725. class NvidiaChat(Base):
  726. def __init__(self, key, model_name, base_url="https://integrate.api.nvidia.com/v1"):
  727. if not base_url:
  728. base_url = "https://integrate.api.nvidia.com/v1"
  729. super().__init__(key, model_name, base_url)
  730. class LmStudioChat(Base):
  731. def __init__(self, key, model_name, base_url):
  732. if not base_url:
  733. raise ValueError("Local llm url cannot be None")
  734. if base_url.split("/")[-1] != "v1":
  735. base_url = os.path.join(base_url, "v1")
  736. self.client = OpenAI(api_key="lm-studio", base_url=base_url)
  737. self.model_name = model_name
  738. class OpenAI_APIChat(Base):
  739. def __init__(self, key, model_name, base_url):
  740. if not base_url:
  741. raise ValueError("url cannot be None")
  742. if base_url.split("/")[-1] != "v1":
  743. base_url = os.path.join(base_url, "v1")
  744. model_name = model_name.split("___")[0]
  745. super().__init__(key, model_name, base_url)
  746. class CoHereChat(Base):
  747. def __init__(self, key, model_name, base_url=""):
  748. from cohere import Client
  749. self.client = Client(api_key=key)
  750. self.model_name = model_name
  751. def chat(self, system, history, gen_conf):
  752. if system:
  753. history.insert(0, {"role": "system", "content": system})
  754. if "top_p" in gen_conf:
  755. gen_conf["p"] = gen_conf.pop("top_p")
  756. if "frequency_penalty" in gen_conf and "presence_penalty" in gen_conf:
  757. gen_conf.pop("presence_penalty")
  758. for item in history:
  759. if "role" in item and item["role"] == "user":
  760. item["role"] = "USER"
  761. if "role" in item and item["role"] == "assistant":
  762. item["role"] = "CHATBOT"
  763. if "content" in item:
  764. item["message"] = item.pop("content")
  765. mes = history.pop()["message"]
  766. ans = ""
  767. try:
  768. response = self.client.chat(
  769. model=self.model_name, chat_history=history, message=mes, **gen_conf
  770. )
  771. ans = response.text
  772. if response.finish_reason == "MAX_TOKENS":
  773. ans += (
  774. "...\nFor the content length reason, it stopped, continue?"
  775. if is_english([ans])
  776. else "······\n由于长度的原因,回答被截断了,要继续吗?"
  777. )
  778. return (
  779. ans,
  780. response.meta.tokens.input_tokens + response.meta.tokens.output_tokens,
  781. )
  782. except Exception as e:
  783. return ans + "\n**ERROR**: " + str(e), 0
  784. def chat_streamly(self, system, history, gen_conf):
  785. if system:
  786. history.insert(0, {"role": "system", "content": system})
  787. if "top_p" in gen_conf:
  788. gen_conf["p"] = gen_conf.pop("top_p")
  789. if "frequency_penalty" in gen_conf and "presence_penalty" in gen_conf:
  790. gen_conf.pop("presence_penalty")
  791. for item in history:
  792. if "role" in item and item["role"] == "user":
  793. item["role"] = "USER"
  794. if "role" in item and item["role"] == "assistant":
  795. item["role"] = "CHATBOT"
  796. if "content" in item:
  797. item["message"] = item.pop("content")
  798. mes = history.pop()["message"]
  799. ans = ""
  800. total_tokens = 0
  801. try:
  802. response = self.client.chat_stream(
  803. model=self.model_name, chat_history=history, message=mes, **gen_conf
  804. )
  805. for resp in response:
  806. if resp.event_type == "text-generation":
  807. ans += resp.text
  808. total_tokens += num_tokens_from_string(resp.text)
  809. elif resp.event_type == "stream-end":
  810. if resp.finish_reason == "MAX_TOKENS":
  811. ans += (
  812. "...\nFor the content length reason, it stopped, continue?"
  813. if is_english([ans])
  814. else "······\n由于长度的原因,回答被截断了,要继续吗?"
  815. )
  816. yield ans
  817. except Exception as e:
  818. yield ans + "\n**ERROR**: " + str(e)
  819. yield total_tokens
  820. class LeptonAIChat(Base):
  821. def __init__(self, key, model_name, base_url=None):
  822. if not base_url:
  823. base_url = os.path.join("https://"+model_name+".lepton.run","api","v1")
  824. super().__init__(key, model_name, base_url)
  825. class TogetherAIChat(Base):
  826. def __init__(self, key, model_name, base_url="https://api.together.xyz/v1"):
  827. if not base_url:
  828. base_url = "https://api.together.xyz/v1"
  829. super().__init__(key, model_name, base_url)
  830. class PerfXCloudChat(Base):
  831. def __init__(self, key, model_name, base_url="https://cloud.perfxlab.cn/v1"):
  832. if not base_url:
  833. base_url = "https://cloud.perfxlab.cn/v1"
  834. super().__init__(key, model_name, base_url)
  835. class UpstageChat(Base):
  836. def __init__(self, key, model_name, base_url="https://api.upstage.ai/v1/solar"):
  837. if not base_url:
  838. base_url = "https://api.upstage.ai/v1/solar"
  839. super().__init__(key, model_name, base_url)
  840. class NovitaAIChat(Base):
  841. def __init__(self, key, model_name, base_url="https://api.novita.ai/v3/openai"):
  842. if not base_url:
  843. base_url = "https://api.novita.ai/v3/openai"
  844. super().__init__(key, model_name, base_url)
  845. class SILICONFLOWChat(Base):
  846. def __init__(self, key, model_name, base_url="https://api.siliconflow.cn/v1"):
  847. if not base_url:
  848. base_url = "https://api.siliconflow.cn/v1"
  849. super().__init__(key, model_name, base_url)
  850. class YiChat(Base):
  851. def __init__(self, key, model_name, base_url="https://api.01.ai/v1"):
  852. if not base_url:
  853. base_url = "https://api.01.ai/v1"
  854. super().__init__(key, model_name, base_url)
  855. class ReplicateChat(Base):
  856. def __init__(self, key, model_name, base_url=None):
  857. from replicate.client import Client
  858. self.model_name = model_name
  859. self.client = Client(api_token=key)
  860. self.system = ""
  861. def chat(self, system, history, gen_conf):
  862. if "max_tokens" in gen_conf:
  863. gen_conf["max_new_tokens"] = gen_conf.pop("max_tokens")
  864. if system:
  865. self.system = system
  866. prompt = "\n".join(
  867. [item["role"] + ":" + item["content"] for item in history[-5:]]
  868. )
  869. ans = ""
  870. try:
  871. response = self.client.run(
  872. self.model_name,
  873. input={"system_prompt": self.system, "prompt": prompt, **gen_conf},
  874. )
  875. ans = "".join(response)
  876. return ans, num_tokens_from_string(ans)
  877. except Exception as e:
  878. return ans + "\n**ERROR**: " + str(e), 0
  879. def chat_streamly(self, system, history, gen_conf):
  880. if "max_tokens" in gen_conf:
  881. gen_conf["max_new_tokens"] = gen_conf.pop("max_tokens")
  882. if system:
  883. self.system = system
  884. prompt = "\n".join(
  885. [item["role"] + ":" + item["content"] for item in history[-5:]]
  886. )
  887. ans = ""
  888. try:
  889. response = self.client.run(
  890. self.model_name,
  891. input={"system_prompt": self.system, "prompt": prompt, **gen_conf},
  892. )
  893. for resp in response:
  894. ans += resp
  895. yield ans
  896. except Exception as e:
  897. yield ans + "\n**ERROR**: " + str(e)
  898. yield num_tokens_from_string(ans)
  899. class HunyuanChat(Base):
  900. def __init__(self, key, model_name, base_url=None):
  901. from tencentcloud.common import credential
  902. from tencentcloud.hunyuan.v20230901 import hunyuan_client
  903. key = json.loads(key)
  904. sid = key.get("hunyuan_sid", "")
  905. sk = key.get("hunyuan_sk", "")
  906. cred = credential.Credential(sid, sk)
  907. self.model_name = model_name
  908. self.client = hunyuan_client.HunyuanClient(cred, "")
  909. def chat(self, system, history, gen_conf):
  910. from tencentcloud.hunyuan.v20230901 import models
  911. from tencentcloud.common.exception.tencent_cloud_sdk_exception import (
  912. TencentCloudSDKException,
  913. )
  914. _gen_conf = {}
  915. _history = [{k.capitalize(): v for k, v in item.items() } for item in history]
  916. if system:
  917. _history.insert(0, {"Role": "system", "Content": system})
  918. if "temperature" in gen_conf:
  919. _gen_conf["Temperature"] = gen_conf["temperature"]
  920. if "top_p" in gen_conf:
  921. _gen_conf["TopP"] = gen_conf["top_p"]
  922. req = models.ChatCompletionsRequest()
  923. params = {"Model": self.model_name, "Messages": _history, **_gen_conf}
  924. req.from_json_string(json.dumps(params))
  925. ans = ""
  926. try:
  927. response = self.client.ChatCompletions(req)
  928. ans = response.Choices[0].Message.Content
  929. return ans, response.Usage.TotalTokens
  930. except TencentCloudSDKException as e:
  931. return ans + "\n**ERROR**: " + str(e), 0
  932. def chat_streamly(self, system, history, gen_conf):
  933. from tencentcloud.hunyuan.v20230901 import models
  934. from tencentcloud.common.exception.tencent_cloud_sdk_exception import (
  935. TencentCloudSDKException,
  936. )
  937. _gen_conf = {}
  938. _history = [{k.capitalize(): v for k, v in item.items() } for item in history]
  939. if system:
  940. _history.insert(0, {"Role": "system", "Content": system})
  941. if "temperature" in gen_conf:
  942. _gen_conf["Temperature"] = gen_conf["temperature"]
  943. if "top_p" in gen_conf:
  944. _gen_conf["TopP"] = gen_conf["top_p"]
  945. req = models.ChatCompletionsRequest()
  946. params = {
  947. "Model": self.model_name,
  948. "Messages": _history,
  949. "Stream": True,
  950. **_gen_conf,
  951. }
  952. req.from_json_string(json.dumps(params))
  953. ans = ""
  954. total_tokens = 0
  955. try:
  956. response = self.client.ChatCompletions(req)
  957. for resp in response:
  958. resp = json.loads(resp["data"])
  959. if not resp["Choices"] or not resp["Choices"][0]["Delta"]["Content"]:
  960. continue
  961. ans += resp["Choices"][0]["Delta"]["Content"]
  962. total_tokens += 1
  963. yield ans
  964. except TencentCloudSDKException as e:
  965. yield ans + "\n**ERROR**: " + str(e)
  966. yield total_tokens
  967. class SparkChat(Base):
  968. def __init__(
  969. self, key, model_name, base_url="https://spark-api-open.xf-yun.com/v1"
  970. ):
  971. if not base_url:
  972. base_url = "https://spark-api-open.xf-yun.com/v1"
  973. model2version = {
  974. "Spark-Max": "generalv3.5",
  975. "Spark-Lite": "general",
  976. "Spark-Pro": "generalv3",
  977. "Spark-Pro-128K": "pro-128k",
  978. "Spark-4.0-Ultra": "4.0Ultra",
  979. }
  980. model_version = model2version[model_name]
  981. super().__init__(key, model_version, base_url)
  982. class BaiduYiyanChat(Base):
  983. def __init__(self, key, model_name, base_url=None):
  984. import qianfan
  985. key = json.loads(key)
  986. ak = key.get("yiyan_ak","")
  987. sk = key.get("yiyan_sk","")
  988. self.client = qianfan.ChatCompletion(ak=ak,sk=sk)
  989. self.model_name = model_name.lower()
  990. self.system = ""
  991. def chat(self, system, history, gen_conf):
  992. if system:
  993. self.system = system
  994. gen_conf["penalty_score"] = (
  995. (gen_conf.get("presence_penalty", 0) + gen_conf.get("frequency_penalty", 0)) / 2
  996. ) + 1
  997. if "max_tokens" in gen_conf:
  998. gen_conf["max_output_tokens"] = gen_conf["max_tokens"]
  999. ans = ""
  1000. try:
  1001. response = self.client.do(
  1002. model=self.model_name,
  1003. messages=history,
  1004. system=self.system,
  1005. **gen_conf
  1006. ).body
  1007. ans = response['result']
  1008. return ans, response["usage"]["total_tokens"]
  1009. except Exception as e:
  1010. return ans + "\n**ERROR**: " + str(e), 0
  1011. def chat_streamly(self, system, history, gen_conf):
  1012. if system:
  1013. self.system = system
  1014. gen_conf["penalty_score"] = (
  1015. (gen_conf.get("presence_penalty", 0) + gen_conf.get("frequency_penalty", 0)) / 2
  1016. ) + 1
  1017. if "max_tokens" in gen_conf:
  1018. gen_conf["max_output_tokens"] = gen_conf["max_tokens"]
  1019. ans = ""
  1020. total_tokens = 0
  1021. try:
  1022. response = self.client.do(
  1023. model=self.model_name,
  1024. messages=history,
  1025. system=self.system,
  1026. stream=True,
  1027. **gen_conf
  1028. )
  1029. for resp in response:
  1030. resp = resp.body
  1031. ans += resp['result']
  1032. total_tokens = resp["usage"]["total_tokens"]
  1033. yield ans
  1034. except Exception as e:
  1035. return ans + "\n**ERROR**: " + str(e), 0
  1036. yield total_tokens
  1037. class AnthropicChat(Base):
  1038. def __init__(self, key, model_name, base_url=None):
  1039. import anthropic
  1040. self.client = anthropic.Anthropic(api_key=key)
  1041. self.model_name = model_name
  1042. self.system = ""
  1043. def chat(self, system, history, gen_conf):
  1044. if system:
  1045. self.system = system
  1046. if "max_tokens" not in gen_conf:
  1047. gen_conf["max_tokens"] = 4096
  1048. try:
  1049. response = self.client.messages.create(
  1050. model=self.model_name,
  1051. messages=history,
  1052. system=self.system,
  1053. stream=False,
  1054. **gen_conf,
  1055. ).json()
  1056. ans = response["content"][0]["text"]
  1057. if response["stop_reason"] == "max_tokens":
  1058. ans += (
  1059. "...\nFor the content length reason, it stopped, continue?"
  1060. if is_english([ans])
  1061. else "······\n由于长度的原因,回答被截断了,要继续吗?"
  1062. )
  1063. return (
  1064. ans,
  1065. response["usage"]["input_tokens"] + response["usage"]["output_tokens"],
  1066. )
  1067. except Exception as e:
  1068. return ans + "\n**ERROR**: " + str(e), 0
  1069. def chat_streamly(self, system, history, gen_conf):
  1070. if system:
  1071. self.system = system
  1072. if "max_tokens" not in gen_conf:
  1073. gen_conf["max_tokens"] = 4096
  1074. ans = ""
  1075. total_tokens = 0
  1076. try:
  1077. response = self.client.messages.create(
  1078. model=self.model_name,
  1079. messages=history,
  1080. system=self.system,
  1081. stream=True,
  1082. **gen_conf,
  1083. )
  1084. for res in response.iter_lines():
  1085. res = res.decode("utf-8")
  1086. if "content_block_delta" in res and "data" in res:
  1087. text = json.loads(res[6:])["delta"]["text"]
  1088. ans += text
  1089. total_tokens += num_tokens_from_string(text)
  1090. except Exception as e:
  1091. yield ans + "\n**ERROR**: " + str(e)
  1092. yield total_tokens