You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

chat_model.py 54KB

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