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

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