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

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