You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

chat_model.py 56KB

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