您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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