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

chat_model.py 55KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446
  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. timeout = int(os.environ.get('LM_TIMEOUT_SECONDS', 600))
  33. self.client = OpenAI(api_key=key, base_url=base_url, timeout=timeout)
  34. self.model_name = model_name
  35. def chat(self, system, history, gen_conf):
  36. if system:
  37. history.insert(0, {"role": "system", "content": system})
  38. try:
  39. response = self.client.chat.completions.create(
  40. model=self.model_name,
  41. messages=history,
  42. **gen_conf)
  43. ans = response.choices[0].message.content.strip()
  44. if response.choices[0].finish_reason == "length":
  45. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  46. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  47. return ans, response.usage.total_tokens
  48. except openai.APIError as e:
  49. return "**ERROR**: " + str(e), 0
  50. def chat_streamly(self, system, history, gen_conf):
  51. if system:
  52. history.insert(0, {"role": "system", "content": system})
  53. ans = ""
  54. total_tokens = 0
  55. try:
  56. response = self.client.chat.completions.create(
  57. model=self.model_name,
  58. messages=history,
  59. stream=True,
  60. **gen_conf)
  61. for resp in response:
  62. if not resp.choices: continue
  63. if not resp.choices[0].delta.content:
  64. resp.choices[0].delta.content = ""
  65. ans += resp.choices[0].delta.content
  66. if not hasattr(resp, "usage") or not resp.usage:
  67. total_tokens = (
  68. total_tokens
  69. + num_tokens_from_string(resp.choices[0].delta.content)
  70. )
  71. elif isinstance(resp.usage, dict):
  72. total_tokens = resp.usage.get("total_tokens", total_tokens)
  73. else: total_tokens = resp.usage.total_tokens
  74. if resp.choices[0].finish_reason == "length":
  75. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  76. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  77. yield ans
  78. except openai.APIError as e:
  79. yield ans + "\n**ERROR**: " + str(e)
  80. yield total_tokens
  81. class GptTurbo(Base):
  82. def __init__(self, key, model_name="gpt-3.5-turbo", base_url="https://api.openai.com/v1"):
  83. if not base_url: base_url = "https://api.openai.com/v1"
  84. super().__init__(key, model_name, base_url)
  85. class MoonshotChat(Base):
  86. def __init__(self, key, model_name="moonshot-v1-8k", base_url="https://api.moonshot.cn/v1"):
  87. if not base_url: base_url = "https://api.moonshot.cn/v1"
  88. super().__init__(key, model_name, base_url)
  89. class XinferenceChat(Base):
  90. def __init__(self, key=None, model_name="", base_url=""):
  91. if not base_url:
  92. raise ValueError("Local llm url cannot be None")
  93. if base_url.split("/")[-1] != "v1":
  94. base_url = os.path.join(base_url, "v1")
  95. super().__init__(key, model_name, base_url)
  96. class HuggingFaceChat(Base):
  97. def __init__(self, key=None, model_name="", base_url=""):
  98. if not base_url:
  99. raise ValueError("Local llm url cannot be None")
  100. if base_url.split("/")[-1] != "v1":
  101. base_url = os.path.join(base_url, "v1")
  102. super().__init__(key, model_name, base_url)
  103. class DeepSeekChat(Base):
  104. def __init__(self, key, model_name="deepseek-chat", base_url="https://api.deepseek.com/v1"):
  105. if not base_url: base_url = "https://api.deepseek.com/v1"
  106. super().__init__(key, model_name, base_url)
  107. class AzureChat(Base):
  108. def __init__(self, key, model_name, **kwargs):
  109. api_key = json.loads(key).get('api_key', '')
  110. api_version = json.loads(key).get('api_version', '2024-02-01')
  111. self.client = AzureOpenAI(api_key=api_key, azure_endpoint=kwargs["base_url"], api_version=api_version)
  112. self.model_name = model_name
  113. class BaiChuanChat(Base):
  114. def __init__(self, key, model_name="Baichuan3-Turbo", base_url="https://api.baichuan-ai.com/v1"):
  115. if not base_url:
  116. base_url = "https://api.baichuan-ai.com/v1"
  117. super().__init__(key, model_name, base_url)
  118. @staticmethod
  119. def _format_params(params):
  120. return {
  121. "temperature": params.get("temperature", 0.3),
  122. "max_tokens": params.get("max_tokens", 2048),
  123. "top_p": params.get("top_p", 0.85),
  124. }
  125. def chat(self, system, history, gen_conf):
  126. if system:
  127. history.insert(0, {"role": "system", "content": system})
  128. try:
  129. response = self.client.chat.completions.create(
  130. model=self.model_name,
  131. messages=history,
  132. extra_body={
  133. "tools": [{
  134. "type": "web_search",
  135. "web_search": {
  136. "enable": True,
  137. "search_mode": "performance_first"
  138. }
  139. }]
  140. },
  141. **self._format_params(gen_conf))
  142. ans = response.choices[0].message.content.strip()
  143. if response.choices[0].finish_reason == "length":
  144. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  145. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  146. return ans, response.usage.total_tokens
  147. except openai.APIError as e:
  148. return "**ERROR**: " + str(e), 0
  149. def chat_streamly(self, system, history, gen_conf):
  150. if system:
  151. history.insert(0, {"role": "system", "content": system})
  152. ans = ""
  153. total_tokens = 0
  154. try:
  155. response = self.client.chat.completions.create(
  156. model=self.model_name,
  157. messages=history,
  158. extra_body={
  159. "tools": [{
  160. "type": "web_search",
  161. "web_search": {
  162. "enable": True,
  163. "search_mode": "performance_first"
  164. }
  165. }]
  166. },
  167. stream=True,
  168. **self._format_params(gen_conf))
  169. for resp in response:
  170. if not resp.choices: continue
  171. if not resp.choices[0].delta.content:
  172. resp.choices[0].delta.content = ""
  173. ans += resp.choices[0].delta.content
  174. total_tokens = (
  175. (
  176. total_tokens
  177. + num_tokens_from_string(resp.choices[0].delta.content)
  178. )
  179. if not hasattr(resp, "usage")
  180. else resp.usage["total_tokens"]
  181. )
  182. if resp.choices[0].finish_reason == "length":
  183. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  184. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  185. yield ans
  186. except Exception as e:
  187. yield ans + "\n**ERROR**: " + str(e)
  188. yield total_tokens
  189. class QWenChat(Base):
  190. def __init__(self, key, model_name=Generation.Models.qwen_turbo, **kwargs):
  191. import dashscope
  192. dashscope.api_key = key
  193. self.model_name = model_name
  194. def chat(self, system, history, gen_conf):
  195. stream_flag = str(os.environ.get('QWEN_CHAT_BY_STREAM', 'true')).lower() == 'true'
  196. if not stream_flag:
  197. from http import HTTPStatus
  198. if system:
  199. history.insert(0, {"role": "system", "content": system})
  200. response = Generation.call(
  201. self.model_name,
  202. messages=history,
  203. result_format='message',
  204. **gen_conf
  205. )
  206. ans = ""
  207. tk_count = 0
  208. if response.status_code == HTTPStatus.OK:
  209. ans += response.output.choices[0]['message']['content']
  210. tk_count += response.usage.total_tokens
  211. if response.output.choices[0].get("finish_reason", "") == "length":
  212. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  213. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  214. return ans, tk_count
  215. return "**ERROR**: " + response.message, tk_count
  216. else:
  217. g = self._chat_streamly(system, history, gen_conf, incremental_output=True)
  218. result_list = list(g)
  219. error_msg_list = [item for item in result_list if str(item).find("**ERROR**") >= 0]
  220. if len(error_msg_list) > 0:
  221. return "**ERROR**: " + "".join(error_msg_list) , 0
  222. else:
  223. return "".join(result_list[:-1]), result_list[-1]
  224. def _chat_streamly(self, system, history, gen_conf, incremental_output=False):
  225. from http import HTTPStatus
  226. if system:
  227. history.insert(0, {"role": "system", "content": system})
  228. ans = ""
  229. tk_count = 0
  230. try:
  231. response = Generation.call(
  232. self.model_name,
  233. messages=history,
  234. result_format='message',
  235. stream=True,
  236. incremental_output=incremental_output,
  237. **gen_conf
  238. )
  239. for resp in response:
  240. if resp.status_code == HTTPStatus.OK:
  241. ans = resp.output.choices[0]['message']['content']
  242. tk_count = resp.usage.total_tokens
  243. if resp.output.choices[0].get("finish_reason", "") == "length":
  244. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  245. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  246. yield ans
  247. else:
  248. yield ans + "\n**ERROR**: " + resp.message if str(resp.message).find(
  249. "Access") < 0 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. except Exception as e:
  688. yield ans + "\n**ERROR**: " + str(e)
  689. yield response._chunks[-1].usage_metadata.total_token_count
  690. class GroqChat:
  691. def __init__(self, key, model_name, base_url=''):
  692. self.client = Groq(api_key=key)
  693. self.model_name = model_name
  694. def chat(self, system, history, gen_conf):
  695. if system:
  696. history.insert(0, {"role": "system", "content": system})
  697. for k in list(gen_conf.keys()):
  698. if k not in ["temperature", "top_p", "max_tokens"]:
  699. del gen_conf[k]
  700. ans = ""
  701. try:
  702. response = self.client.chat.completions.create(
  703. model=self.model_name,
  704. messages=history,
  705. **gen_conf
  706. )
  707. ans = response.choices[0].message.content
  708. if response.choices[0].finish_reason == "length":
  709. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  710. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  711. return ans, response.usage.total_tokens
  712. except Exception as e:
  713. return ans + "\n**ERROR**: " + str(e), 0
  714. def chat_streamly(self, system, history, gen_conf):
  715. if system:
  716. history.insert(0, {"role": "system", "content": system})
  717. for k in list(gen_conf.keys()):
  718. if k not in ["temperature", "top_p", "max_tokens"]:
  719. del gen_conf[k]
  720. ans = ""
  721. total_tokens = 0
  722. try:
  723. response = self.client.chat.completions.create(
  724. model=self.model_name,
  725. messages=history,
  726. stream=True,
  727. **gen_conf
  728. )
  729. for resp in response:
  730. if not resp.choices or not resp.choices[0].delta.content:
  731. continue
  732. ans += resp.choices[0].delta.content
  733. total_tokens += 1
  734. if resp.choices[0].finish_reason == "length":
  735. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  736. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  737. yield ans
  738. except Exception as e:
  739. yield ans + "\n**ERROR**: " + str(e)
  740. yield total_tokens
  741. ## openrouter
  742. class OpenRouterChat(Base):
  743. def __init__(self, key, model_name, base_url="https://openrouter.ai/api/v1"):
  744. if not base_url:
  745. base_url = "https://openrouter.ai/api/v1"
  746. super().__init__(key, model_name, base_url)
  747. class StepFunChat(Base):
  748. def __init__(self, key, model_name, base_url="https://api.stepfun.com/v1"):
  749. if not base_url:
  750. base_url = "https://api.stepfun.com/v1"
  751. super().__init__(key, model_name, base_url)
  752. class NvidiaChat(Base):
  753. def __init__(self, key, model_name, base_url="https://integrate.api.nvidia.com/v1"):
  754. if not base_url:
  755. base_url = "https://integrate.api.nvidia.com/v1"
  756. super().__init__(key, model_name, base_url)
  757. class LmStudioChat(Base):
  758. def __init__(self, key, model_name, base_url):
  759. if not base_url:
  760. raise ValueError("Local llm url cannot be None")
  761. if base_url.split("/")[-1] != "v1":
  762. base_url = os.path.join(base_url, "v1")
  763. self.client = OpenAI(api_key="lm-studio", base_url=base_url)
  764. self.model_name = model_name
  765. class OpenAI_APIChat(Base):
  766. def __init__(self, key, model_name, base_url):
  767. if not base_url:
  768. raise ValueError("url cannot be None")
  769. if base_url.split("/")[-1] != "v1":
  770. base_url = os.path.join(base_url, "v1")
  771. model_name = model_name.split("___")[0]
  772. super().__init__(key, model_name, base_url)
  773. class CoHereChat(Base):
  774. def __init__(self, key, model_name, base_url=""):
  775. from cohere import Client
  776. self.client = Client(api_key=key)
  777. self.model_name = model_name
  778. def chat(self, system, history, gen_conf):
  779. if system:
  780. history.insert(0, {"role": "system", "content": system})
  781. if "top_p" in gen_conf:
  782. gen_conf["p"] = gen_conf.pop("top_p")
  783. if "frequency_penalty" in gen_conf and "presence_penalty" in gen_conf:
  784. gen_conf.pop("presence_penalty")
  785. for item in history:
  786. if "role" in item and item["role"] == "user":
  787. item["role"] = "USER"
  788. if "role" in item and item["role"] == "assistant":
  789. item["role"] = "CHATBOT"
  790. if "content" in item:
  791. item["message"] = item.pop("content")
  792. mes = history.pop()["message"]
  793. ans = ""
  794. try:
  795. response = self.client.chat(
  796. model=self.model_name, chat_history=history, message=mes, **gen_conf
  797. )
  798. ans = response.text
  799. if response.finish_reason == "MAX_TOKENS":
  800. ans += (
  801. "...\nFor the content length reason, it stopped, continue?"
  802. if is_english([ans])
  803. else "······\n由于长度的原因,回答被截断了,要继续吗?"
  804. )
  805. return (
  806. ans,
  807. response.meta.tokens.input_tokens + response.meta.tokens.output_tokens,
  808. )
  809. except Exception as e:
  810. return ans + "\n**ERROR**: " + str(e), 0
  811. def chat_streamly(self, system, history, gen_conf):
  812. if system:
  813. history.insert(0, {"role": "system", "content": system})
  814. if "top_p" in gen_conf:
  815. gen_conf["p"] = gen_conf.pop("top_p")
  816. if "frequency_penalty" in gen_conf and "presence_penalty" in gen_conf:
  817. gen_conf.pop("presence_penalty")
  818. for item in history:
  819. if "role" in item and item["role"] == "user":
  820. item["role"] = "USER"
  821. if "role" in item and item["role"] == "assistant":
  822. item["role"] = "CHATBOT"
  823. if "content" in item:
  824. item["message"] = item.pop("content")
  825. mes = history.pop()["message"]
  826. ans = ""
  827. total_tokens = 0
  828. try:
  829. response = self.client.chat_stream(
  830. model=self.model_name, chat_history=history, message=mes, **gen_conf
  831. )
  832. for resp in response:
  833. if resp.event_type == "text-generation":
  834. ans += resp.text
  835. total_tokens += num_tokens_from_string(resp.text)
  836. elif resp.event_type == "stream-end":
  837. if resp.finish_reason == "MAX_TOKENS":
  838. ans += (
  839. "...\nFor the content length reason, it stopped, continue?"
  840. if is_english([ans])
  841. else "······\n由于长度的原因,回答被截断了,要继续吗?"
  842. )
  843. yield ans
  844. except Exception as e:
  845. yield ans + "\n**ERROR**: " + str(e)
  846. yield total_tokens
  847. class LeptonAIChat(Base):
  848. def __init__(self, key, model_name, base_url=None):
  849. if not base_url:
  850. base_url = os.path.join("https://" + model_name + ".lepton.run", "api", "v1")
  851. super().__init__(key, model_name, base_url)
  852. class TogetherAIChat(Base):
  853. def __init__(self, key, model_name, base_url="https://api.together.xyz/v1"):
  854. if not base_url:
  855. base_url = "https://api.together.xyz/v1"
  856. super().__init__(key, model_name, base_url)
  857. class PerfXCloudChat(Base):
  858. def __init__(self, key, model_name, base_url="https://cloud.perfxlab.cn/v1"):
  859. if not base_url:
  860. base_url = "https://cloud.perfxlab.cn/v1"
  861. super().__init__(key, model_name, base_url)
  862. class UpstageChat(Base):
  863. def __init__(self, key, model_name, base_url="https://api.upstage.ai/v1/solar"):
  864. if not base_url:
  865. base_url = "https://api.upstage.ai/v1/solar"
  866. super().__init__(key, model_name, base_url)
  867. class NovitaAIChat(Base):
  868. def __init__(self, key, model_name, base_url="https://api.novita.ai/v3/openai"):
  869. if not base_url:
  870. base_url = "https://api.novita.ai/v3/openai"
  871. super().__init__(key, model_name, base_url)
  872. class SILICONFLOWChat(Base):
  873. def __init__(self, key, model_name, base_url="https://api.siliconflow.cn/v1"):
  874. if not base_url:
  875. base_url = "https://api.siliconflow.cn/v1"
  876. super().__init__(key, model_name, base_url)
  877. class YiChat(Base):
  878. def __init__(self, key, model_name, base_url="https://api.lingyiwanwu.com/v1"):
  879. if not base_url:
  880. base_url = "https://api.lingyiwanwu.com/v1"
  881. super().__init__(key, model_name, base_url)
  882. class ReplicateChat(Base):
  883. def __init__(self, key, model_name, base_url=None):
  884. from replicate.client import Client
  885. self.model_name = model_name
  886. self.client = Client(api_token=key)
  887. self.system = ""
  888. def chat(self, system, history, gen_conf):
  889. if "max_tokens" in gen_conf:
  890. gen_conf["max_new_tokens"] = gen_conf.pop("max_tokens")
  891. if system:
  892. self.system = system
  893. prompt = "\n".join(
  894. [item["role"] + ":" + item["content"] for item in history[-5:]]
  895. )
  896. ans = ""
  897. try:
  898. response = self.client.run(
  899. self.model_name,
  900. input={"system_prompt": self.system, "prompt": prompt, **gen_conf},
  901. )
  902. ans = "".join(response)
  903. return ans, num_tokens_from_string(ans)
  904. except Exception as e:
  905. return ans + "\n**ERROR**: " + str(e), 0
  906. def chat_streamly(self, system, history, gen_conf):
  907. if "max_tokens" in gen_conf:
  908. gen_conf["max_new_tokens"] = gen_conf.pop("max_tokens")
  909. if system:
  910. self.system = system
  911. prompt = "\n".join(
  912. [item["role"] + ":" + item["content"] for item in history[-5:]]
  913. )
  914. ans = ""
  915. try:
  916. response = self.client.run(
  917. self.model_name,
  918. input={"system_prompt": self.system, "prompt": prompt, **gen_conf},
  919. )
  920. for resp in response:
  921. ans += resp
  922. yield ans
  923. except Exception as e:
  924. yield ans + "\n**ERROR**: " + str(e)
  925. yield num_tokens_from_string(ans)
  926. class HunyuanChat(Base):
  927. def __init__(self, key, model_name, base_url=None):
  928. from tencentcloud.common import credential
  929. from tencentcloud.hunyuan.v20230901 import hunyuan_client
  930. key = json.loads(key)
  931. sid = key.get("hunyuan_sid", "")
  932. sk = key.get("hunyuan_sk", "")
  933. cred = credential.Credential(sid, sk)
  934. self.model_name = model_name
  935. self.client = hunyuan_client.HunyuanClient(cred, "")
  936. def chat(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 = {"Model": self.model_name, "Messages": _history, **_gen_conf}
  951. req.from_json_string(json.dumps(params))
  952. ans = ""
  953. try:
  954. response = self.client.ChatCompletions(req)
  955. ans = response.Choices[0].Message.Content
  956. return ans, response.Usage.TotalTokens
  957. except TencentCloudSDKException as e:
  958. return ans + "\n**ERROR**: " + str(e), 0
  959. def chat_streamly(self, system, history, gen_conf):
  960. from tencentcloud.hunyuan.v20230901 import models
  961. from tencentcloud.common.exception.tencent_cloud_sdk_exception import (
  962. TencentCloudSDKException,
  963. )
  964. _gen_conf = {}
  965. _history = [{k.capitalize(): v for k, v in item.items()} for item in history]
  966. if system:
  967. _history.insert(0, {"Role": "system", "Content": system})
  968. if "temperature" in gen_conf:
  969. _gen_conf["Temperature"] = gen_conf["temperature"]
  970. if "top_p" in gen_conf:
  971. _gen_conf["TopP"] = gen_conf["top_p"]
  972. req = models.ChatCompletionsRequest()
  973. params = {
  974. "Model": self.model_name,
  975. "Messages": _history,
  976. "Stream": True,
  977. **_gen_conf,
  978. }
  979. req.from_json_string(json.dumps(params))
  980. ans = ""
  981. total_tokens = 0
  982. try:
  983. response = self.client.ChatCompletions(req)
  984. for resp in response:
  985. resp = json.loads(resp["data"])
  986. if not resp["Choices"] or not resp["Choices"][0]["Delta"]["Content"]:
  987. continue
  988. ans += resp["Choices"][0]["Delta"]["Content"]
  989. total_tokens += 1
  990. yield ans
  991. except TencentCloudSDKException as e:
  992. yield ans + "\n**ERROR**: " + str(e)
  993. yield total_tokens
  994. class SparkChat(Base):
  995. def __init__(
  996. self, key, model_name, base_url="https://spark-api-open.xf-yun.com/v1"
  997. ):
  998. if not base_url:
  999. base_url = "https://spark-api-open.xf-yun.com/v1"
  1000. model2version = {
  1001. "Spark-Max": "generalv3.5",
  1002. "Spark-Lite": "general",
  1003. "Spark-Pro": "generalv3",
  1004. "Spark-Pro-128K": "pro-128k",
  1005. "Spark-4.0-Ultra": "4.0Ultra",
  1006. }
  1007. model_version = model2version[model_name]
  1008. super().__init__(key, model_version, base_url)
  1009. class BaiduYiyanChat(Base):
  1010. def __init__(self, key, model_name, base_url=None):
  1011. import qianfan
  1012. key = json.loads(key)
  1013. ak = key.get("yiyan_ak", "")
  1014. sk = key.get("yiyan_sk", "")
  1015. self.client = qianfan.ChatCompletion(ak=ak, sk=sk)
  1016. self.model_name = model_name.lower()
  1017. self.system = ""
  1018. def chat(self, system, history, gen_conf):
  1019. if system:
  1020. self.system = system
  1021. gen_conf["penalty_score"] = (
  1022. (gen_conf.get("presence_penalty", 0) + gen_conf.get("frequency_penalty",
  1023. 0)) / 2
  1024. ) + 1
  1025. if "max_tokens" in gen_conf:
  1026. gen_conf["max_output_tokens"] = gen_conf["max_tokens"]
  1027. ans = ""
  1028. try:
  1029. response = self.client.do(
  1030. model=self.model_name,
  1031. messages=history,
  1032. system=self.system,
  1033. **gen_conf
  1034. ).body
  1035. ans = response['result']
  1036. return ans, response["usage"]["total_tokens"]
  1037. except Exception as e:
  1038. return ans + "\n**ERROR**: " + str(e), 0
  1039. def chat_streamly(self, system, history, gen_conf):
  1040. if system:
  1041. self.system = system
  1042. gen_conf["penalty_score"] = (
  1043. (gen_conf.get("presence_penalty", 0) + gen_conf.get("frequency_penalty",
  1044. 0)) / 2
  1045. ) + 1
  1046. if "max_tokens" in gen_conf:
  1047. gen_conf["max_output_tokens"] = gen_conf["max_tokens"]
  1048. ans = ""
  1049. total_tokens = 0
  1050. try:
  1051. response = self.client.do(
  1052. model=self.model_name,
  1053. messages=history,
  1054. system=self.system,
  1055. stream=True,
  1056. **gen_conf
  1057. )
  1058. for resp in response:
  1059. resp = resp.body
  1060. ans += resp['result']
  1061. total_tokens = resp["usage"]["total_tokens"]
  1062. yield ans
  1063. except Exception as e:
  1064. return ans + "\n**ERROR**: " + str(e), 0
  1065. yield total_tokens
  1066. class AnthropicChat(Base):
  1067. def __init__(self, key, model_name, base_url=None):
  1068. import anthropic
  1069. self.client = anthropic.Anthropic(api_key=key)
  1070. self.model_name = model_name
  1071. self.system = ""
  1072. def chat(self, system, history, gen_conf):
  1073. if system:
  1074. self.system = system
  1075. if "max_tokens" not in gen_conf:
  1076. gen_conf["max_tokens"] = 4096
  1077. try:
  1078. response = self.client.messages.create(
  1079. model=self.model_name,
  1080. messages=history,
  1081. system=self.system,
  1082. stream=False,
  1083. **gen_conf,
  1084. ).json()
  1085. ans = response["content"][0]["text"]
  1086. if response["stop_reason"] == "max_tokens":
  1087. ans += (
  1088. "...\nFor the content length reason, it stopped, continue?"
  1089. if is_english([ans])
  1090. else "······\n由于长度的原因,回答被截断了,要继续吗?"
  1091. )
  1092. return (
  1093. ans,
  1094. response["usage"]["input_tokens"] + response["usage"]["output_tokens"],
  1095. )
  1096. except Exception as e:
  1097. return ans + "\n**ERROR**: " + str(e), 0
  1098. def chat_streamly(self, system, history, gen_conf):
  1099. if system:
  1100. self.system = system
  1101. if "max_tokens" not in gen_conf:
  1102. gen_conf["max_tokens"] = 4096
  1103. ans = ""
  1104. total_tokens = 0
  1105. try:
  1106. response = self.client.messages.create(
  1107. model=self.model_name,
  1108. messages=history,
  1109. system=self.system,
  1110. stream=True,
  1111. **gen_conf,
  1112. )
  1113. for res in response.iter_lines():
  1114. res = res.decode("utf-8")
  1115. if "content_block_delta" in res and "data" in res:
  1116. text = json.loads(res[6:])["delta"]["text"]
  1117. ans += text
  1118. total_tokens += num_tokens_from_string(text)
  1119. except Exception as e:
  1120. yield ans + "\n**ERROR**: " + str(e)
  1121. yield total_tokens
  1122. class GoogleChat(Base):
  1123. def __init__(self, key, model_name, base_url=None):
  1124. from google.oauth2 import service_account
  1125. import base64
  1126. key = json.load(key)
  1127. access_token = json.loads(
  1128. base64.b64decode(key.get("google_service_account_key", ""))
  1129. )
  1130. project_id = key.get("google_project_id", "")
  1131. region = key.get("google_region", "")
  1132. scopes = ["https://www.googleapis.com/auth/cloud-platform"]
  1133. self.model_name = model_name
  1134. self.system = ""
  1135. if "claude" in self.model_name:
  1136. from anthropic import AnthropicVertex
  1137. from google.auth.transport.requests import Request
  1138. if access_token:
  1139. credits = service_account.Credentials.from_service_account_info(
  1140. access_token, scopes=scopes
  1141. )
  1142. request = Request()
  1143. credits.refresh(request)
  1144. token = credits.token
  1145. self.client = AnthropicVertex(
  1146. region=region, project_id=project_id, access_token=token
  1147. )
  1148. else:
  1149. self.client = AnthropicVertex(region=region, project_id=project_id)
  1150. else:
  1151. from google.cloud import aiplatform
  1152. import vertexai.generative_models as glm
  1153. if access_token:
  1154. credits = service_account.Credentials.from_service_account_info(
  1155. access_token
  1156. )
  1157. aiplatform.init(
  1158. credentials=credits, project=project_id, location=region
  1159. )
  1160. else:
  1161. aiplatform.init(project=project_id, location=region)
  1162. self.client = glm.GenerativeModel(model_name=self.model_name)
  1163. def chat(self, system, history, gen_conf):
  1164. if system:
  1165. self.system = system
  1166. if "claude" in self.model_name:
  1167. if "max_tokens" not in gen_conf:
  1168. gen_conf["max_tokens"] = 4096
  1169. try:
  1170. response = self.client.messages.create(
  1171. model=self.model_name,
  1172. messages=history,
  1173. system=self.system,
  1174. stream=False,
  1175. **gen_conf,
  1176. ).json()
  1177. ans = response["content"][0]["text"]
  1178. if response["stop_reason"] == "max_tokens":
  1179. ans += (
  1180. "...\nFor the content length reason, it stopped, continue?"
  1181. if is_english([ans])
  1182. else "······\n由于长度的原因,回答被截断了,要继续吗?"
  1183. )
  1184. return (
  1185. ans,
  1186. response["usage"]["input_tokens"]
  1187. + response["usage"]["output_tokens"],
  1188. )
  1189. except Exception as e:
  1190. return "\n**ERROR**: " + str(e), 0
  1191. else:
  1192. self.client._system_instruction = self.system
  1193. if "max_tokens" in gen_conf:
  1194. gen_conf["max_output_tokens"] = gen_conf["max_tokens"]
  1195. for k in list(gen_conf.keys()):
  1196. if k not in ["temperature", "top_p", "max_output_tokens"]:
  1197. del gen_conf[k]
  1198. for item in history:
  1199. if "role" in item and item["role"] == "assistant":
  1200. item["role"] = "model"
  1201. if "content" in item:
  1202. item["parts"] = item.pop("content")
  1203. try:
  1204. response = self.client.generate_content(
  1205. history, generation_config=gen_conf
  1206. )
  1207. ans = response.text
  1208. return ans, response.usage_metadata.total_token_count
  1209. except Exception as e:
  1210. return "**ERROR**: " + str(e), 0
  1211. def chat_streamly(self, system, history, gen_conf):
  1212. if system:
  1213. self.system = system
  1214. if "claude" in self.model_name:
  1215. if "max_tokens" not in gen_conf:
  1216. gen_conf["max_tokens"] = 4096
  1217. ans = ""
  1218. total_tokens = 0
  1219. try:
  1220. response = self.client.messages.create(
  1221. model=self.model_name,
  1222. messages=history,
  1223. system=self.system,
  1224. stream=True,
  1225. **gen_conf,
  1226. )
  1227. for res in response.iter_lines():
  1228. res = res.decode("utf-8")
  1229. if "content_block_delta" in res and "data" in res:
  1230. text = json.loads(res[6:])["delta"]["text"]
  1231. ans += text
  1232. total_tokens += num_tokens_from_string(text)
  1233. except Exception as e:
  1234. yield ans + "\n**ERROR**: " + str(e)
  1235. yield total_tokens
  1236. else:
  1237. self.client._system_instruction = self.system
  1238. if "max_tokens" in gen_conf:
  1239. gen_conf["max_output_tokens"] = gen_conf["max_tokens"]
  1240. for k in list(gen_conf.keys()):
  1241. if k not in ["temperature", "top_p", "max_output_tokens"]:
  1242. del gen_conf[k]
  1243. for item in history:
  1244. if "role" in item and item["role"] == "assistant":
  1245. item["role"] = "model"
  1246. if "content" in item:
  1247. item["parts"] = item.pop("content")
  1248. ans = ""
  1249. try:
  1250. response = self.model.generate_content(
  1251. history, generation_config=gen_conf, stream=True
  1252. )
  1253. for resp in response:
  1254. ans += resp.text
  1255. yield ans
  1256. except Exception as e:
  1257. yield ans + "\n**ERROR**: " + str(e)
  1258. yield response._chunks[-1].usage_metadata.total_token_count