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

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