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

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