Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

chat_model.py 56KB

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