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

chat_model.py 56KB

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