Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

chat_model.py 54KB

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