Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

chat_model.py 53KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418
  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 "Answer the user's message.")}] ,
  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. system=[{"text": system if system else ""}],
  600. )
  601. # Extract and print the streamed response text in real-time.
  602. for resp in streaming_response["stream"]:
  603. if "contentBlockDelta" in resp:
  604. ans += resp["contentBlockDelta"]["delta"]["text"]
  605. yield ans
  606. except (ClientError, Exception) as e:
  607. yield ans + f"ERROR: Can't invoke '{self.model_name}'. Reason: {e}"
  608. yield num_tokens_from_string(ans)
  609. class GeminiChat(Base):
  610. def __init__(self, key, model_name,base_url=None):
  611. from google.generativeai import client,GenerativeModel
  612. client.configure(api_key=key)
  613. _client = client.get_default_generative_client()
  614. self.model_name = 'models/' + model_name
  615. self.model = GenerativeModel(model_name=self.model_name)
  616. self.model._client = _client
  617. def chat(self,system,history,gen_conf):
  618. from google.generativeai.types import content_types
  619. if system:
  620. self.model._system_instruction = content_types.to_content(system)
  621. if 'max_tokens' in gen_conf:
  622. gen_conf['max_output_tokens'] = gen_conf['max_tokens']
  623. for k in list(gen_conf.keys()):
  624. if k not in ["temperature", "top_p", "max_output_tokens"]:
  625. del gen_conf[k]
  626. for item in history:
  627. if 'role' in item and item['role'] == 'assistant':
  628. item['role'] = 'model'
  629. if 'content' in item :
  630. item['parts'] = item.pop('content')
  631. try:
  632. response = self.model.generate_content(
  633. history,
  634. generation_config=gen_conf)
  635. ans = response.text
  636. return ans, response.usage_metadata.total_token_count
  637. except Exception as e:
  638. return "**ERROR**: " + str(e), 0
  639. def chat_streamly(self, system, history, gen_conf):
  640. from google.generativeai.types import content_types
  641. if system:
  642. self.model._system_instruction = content_types.to_content(system)
  643. if 'max_tokens' in gen_conf:
  644. gen_conf['max_output_tokens'] = gen_conf['max_tokens']
  645. for k in list(gen_conf.keys()):
  646. if k not in ["temperature", "top_p", "max_output_tokens"]:
  647. del gen_conf[k]
  648. for item in history:
  649. if 'role' in item and item['role'] == 'assistant':
  650. item['role'] = 'model'
  651. if 'content' in item :
  652. item['parts'] = item.pop('content')
  653. ans = ""
  654. try:
  655. response = self.model.generate_content(
  656. history,
  657. generation_config=gen_conf,stream=True)
  658. for resp in response:
  659. ans += resp.text
  660. yield ans
  661. except Exception as e:
  662. yield ans + "\n**ERROR**: " + str(e)
  663. yield response._chunks[-1].usage_metadata.total_token_count
  664. class GroqChat:
  665. def __init__(self, key, model_name,base_url=''):
  666. self.client = Groq(api_key=key)
  667. self.model_name = model_name
  668. def chat(self, system, history, gen_conf):
  669. if system:
  670. history.insert(0, {"role": "system", "content": system})
  671. for k in list(gen_conf.keys()):
  672. if k not in ["temperature", "top_p", "max_tokens"]:
  673. del gen_conf[k]
  674. ans = ""
  675. try:
  676. response = self.client.chat.completions.create(
  677. model=self.model_name,
  678. messages=history,
  679. **gen_conf
  680. )
  681. ans = response.choices[0].message.content
  682. if response.choices[0].finish_reason == "length":
  683. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  684. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  685. return ans, response.usage.total_tokens
  686. except Exception as e:
  687. return ans + "\n**ERROR**: " + str(e), 0
  688. def chat_streamly(self, system, history, gen_conf):
  689. if system:
  690. history.insert(0, {"role": "system", "content": system})
  691. for k in list(gen_conf.keys()):
  692. if k not in ["temperature", "top_p", "max_tokens"]:
  693. del gen_conf[k]
  694. ans = ""
  695. total_tokens = 0
  696. try:
  697. response = self.client.chat.completions.create(
  698. model=self.model_name,
  699. messages=history,
  700. stream=True,
  701. **gen_conf
  702. )
  703. for resp in response:
  704. if not resp.choices or not resp.choices[0].delta.content:
  705. continue
  706. ans += resp.choices[0].delta.content
  707. total_tokens += 1
  708. if resp.choices[0].finish_reason == "length":
  709. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  710. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  711. yield ans
  712. except Exception as e:
  713. yield ans + "\n**ERROR**: " + str(e)
  714. yield total_tokens
  715. ## openrouter
  716. class OpenRouterChat(Base):
  717. def __init__(self, key, model_name, base_url="https://openrouter.ai/api/v1"):
  718. if not base_url:
  719. base_url = "https://openrouter.ai/api/v1"
  720. super().__init__(key, model_name, base_url)
  721. class StepFunChat(Base):
  722. def __init__(self, key, model_name, base_url="https://api.stepfun.com/v1"):
  723. if not base_url:
  724. base_url = "https://api.stepfun.com/v1"
  725. super().__init__(key, model_name, base_url)
  726. class NvidiaChat(Base):
  727. def __init__(self, key, model_name, base_url="https://integrate.api.nvidia.com/v1"):
  728. if not base_url:
  729. base_url = "https://integrate.api.nvidia.com/v1"
  730. super().__init__(key, model_name, base_url)
  731. class LmStudioChat(Base):
  732. def __init__(self, key, model_name, base_url):
  733. if not base_url:
  734. raise ValueError("Local llm url cannot be None")
  735. if base_url.split("/")[-1] != "v1":
  736. base_url = os.path.join(base_url, "v1")
  737. self.client = OpenAI(api_key="lm-studio", base_url=base_url)
  738. self.model_name = model_name
  739. class OpenAI_APIChat(Base):
  740. def __init__(self, key, model_name, base_url):
  741. if not base_url:
  742. raise ValueError("url cannot be None")
  743. if base_url.split("/")[-1] != "v1":
  744. base_url = os.path.join(base_url, "v1")
  745. model_name = model_name.split("___")[0]
  746. super().__init__(key, model_name, base_url)
  747. class CoHereChat(Base):
  748. def __init__(self, key, model_name, base_url=""):
  749. from cohere import Client
  750. self.client = Client(api_key=key)
  751. self.model_name = model_name
  752. def chat(self, system, history, gen_conf):
  753. if system:
  754. history.insert(0, {"role": "system", "content": system})
  755. if "top_p" in gen_conf:
  756. gen_conf["p"] = gen_conf.pop("top_p")
  757. if "frequency_penalty" in gen_conf and "presence_penalty" in gen_conf:
  758. gen_conf.pop("presence_penalty")
  759. for item in history:
  760. if "role" in item and item["role"] == "user":
  761. item["role"] = "USER"
  762. if "role" in item and item["role"] == "assistant":
  763. item["role"] = "CHATBOT"
  764. if "content" in item:
  765. item["message"] = item.pop("content")
  766. mes = history.pop()["message"]
  767. ans = ""
  768. try:
  769. response = self.client.chat(
  770. model=self.model_name, chat_history=history, message=mes, **gen_conf
  771. )
  772. ans = response.text
  773. if response.finish_reason == "MAX_TOKENS":
  774. ans += (
  775. "...\nFor the content length reason, it stopped, continue?"
  776. if is_english([ans])
  777. else "······\n由于长度的原因,回答被截断了,要继续吗?"
  778. )
  779. return (
  780. ans,
  781. response.meta.tokens.input_tokens + response.meta.tokens.output_tokens,
  782. )
  783. except Exception as e:
  784. return ans + "\n**ERROR**: " + str(e), 0
  785. def chat_streamly(self, system, history, gen_conf):
  786. if system:
  787. history.insert(0, {"role": "system", "content": system})
  788. if "top_p" in gen_conf:
  789. gen_conf["p"] = gen_conf.pop("top_p")
  790. if "frequency_penalty" in gen_conf and "presence_penalty" in gen_conf:
  791. gen_conf.pop("presence_penalty")
  792. for item in history:
  793. if "role" in item and item["role"] == "user":
  794. item["role"] = "USER"
  795. if "role" in item and item["role"] == "assistant":
  796. item["role"] = "CHATBOT"
  797. if "content" in item:
  798. item["message"] = item.pop("content")
  799. mes = history.pop()["message"]
  800. ans = ""
  801. total_tokens = 0
  802. try:
  803. response = self.client.chat_stream(
  804. model=self.model_name, chat_history=history, message=mes, **gen_conf
  805. )
  806. for resp in response:
  807. if resp.event_type == "text-generation":
  808. ans += resp.text
  809. total_tokens += num_tokens_from_string(resp.text)
  810. elif resp.event_type == "stream-end":
  811. if resp.finish_reason == "MAX_TOKENS":
  812. ans += (
  813. "...\nFor the content length reason, it stopped, continue?"
  814. if is_english([ans])
  815. else "······\n由于长度的原因,回答被截断了,要继续吗?"
  816. )
  817. yield ans
  818. except Exception as e:
  819. yield ans + "\n**ERROR**: " + str(e)
  820. yield total_tokens
  821. class LeptonAIChat(Base):
  822. def __init__(self, key, model_name, base_url=None):
  823. if not base_url:
  824. base_url = os.path.join("https://"+model_name+".lepton.run","api","v1")
  825. super().__init__(key, model_name, base_url)
  826. class TogetherAIChat(Base):
  827. def __init__(self, key, model_name, base_url="https://api.together.xyz/v1"):
  828. if not base_url:
  829. base_url = "https://api.together.xyz/v1"
  830. super().__init__(key, model_name, base_url)
  831. class PerfXCloudChat(Base):
  832. def __init__(self, key, model_name, base_url="https://cloud.perfxlab.cn/v1"):
  833. if not base_url:
  834. base_url = "https://cloud.perfxlab.cn/v1"
  835. super().__init__(key, model_name, base_url)
  836. class UpstageChat(Base):
  837. def __init__(self, key, model_name, base_url="https://api.upstage.ai/v1/solar"):
  838. if not base_url:
  839. base_url = "https://api.upstage.ai/v1/solar"
  840. super().__init__(key, model_name, base_url)
  841. class NovitaAIChat(Base):
  842. def __init__(self, key, model_name, base_url="https://api.novita.ai/v3/openai"):
  843. if not base_url:
  844. base_url = "https://api.novita.ai/v3/openai"
  845. super().__init__(key, model_name, base_url)
  846. class SILICONFLOWChat(Base):
  847. def __init__(self, key, model_name, base_url="https://api.siliconflow.cn/v1"):
  848. if not base_url:
  849. base_url = "https://api.siliconflow.cn/v1"
  850. super().__init__(key, model_name, base_url)
  851. class YiChat(Base):
  852. def __init__(self, key, model_name, base_url="https://api.lingyiwanwu.com/v1"):
  853. if not base_url:
  854. base_url = "https://api.lingyiwanwu.com/v1"
  855. super().__init__(key, model_name, base_url)
  856. class ReplicateChat(Base):
  857. def __init__(self, key, model_name, base_url=None):
  858. from replicate.client import Client
  859. self.model_name = model_name
  860. self.client = Client(api_token=key)
  861. self.system = ""
  862. def chat(self, system, history, gen_conf):
  863. if "max_tokens" in gen_conf:
  864. gen_conf["max_new_tokens"] = gen_conf.pop("max_tokens")
  865. if system:
  866. self.system = system
  867. prompt = "\n".join(
  868. [item["role"] + ":" + item["content"] for item in history[-5:]]
  869. )
  870. ans = ""
  871. try:
  872. response = self.client.run(
  873. self.model_name,
  874. input={"system_prompt": self.system, "prompt": prompt, **gen_conf},
  875. )
  876. ans = "".join(response)
  877. return ans, num_tokens_from_string(ans)
  878. except Exception as e:
  879. return ans + "\n**ERROR**: " + str(e), 0
  880. def chat_streamly(self, system, history, gen_conf):
  881. if "max_tokens" in gen_conf:
  882. gen_conf["max_new_tokens"] = gen_conf.pop("max_tokens")
  883. if system:
  884. self.system = system
  885. prompt = "\n".join(
  886. [item["role"] + ":" + item["content"] for item in history[-5:]]
  887. )
  888. ans = ""
  889. try:
  890. response = self.client.run(
  891. self.model_name,
  892. input={"system_prompt": self.system, "prompt": prompt, **gen_conf},
  893. )
  894. for resp in response:
  895. ans += resp
  896. yield ans
  897. except Exception as e:
  898. yield ans + "\n**ERROR**: " + str(e)
  899. yield num_tokens_from_string(ans)
  900. class HunyuanChat(Base):
  901. def __init__(self, key, model_name, base_url=None):
  902. from tencentcloud.common import credential
  903. from tencentcloud.hunyuan.v20230901 import hunyuan_client
  904. key = json.loads(key)
  905. sid = key.get("hunyuan_sid", "")
  906. sk = key.get("hunyuan_sk", "")
  907. cred = credential.Credential(sid, sk)
  908. self.model_name = model_name
  909. self.client = hunyuan_client.HunyuanClient(cred, "")
  910. def chat(self, system, history, gen_conf):
  911. from tencentcloud.hunyuan.v20230901 import models
  912. from tencentcloud.common.exception.tencent_cloud_sdk_exception import (
  913. TencentCloudSDKException,
  914. )
  915. _gen_conf = {}
  916. _history = [{k.capitalize(): v for k, v in item.items() } for item in history]
  917. if system:
  918. _history.insert(0, {"Role": "system", "Content": system})
  919. if "temperature" in gen_conf:
  920. _gen_conf["Temperature"] = gen_conf["temperature"]
  921. if "top_p" in gen_conf:
  922. _gen_conf["TopP"] = gen_conf["top_p"]
  923. req = models.ChatCompletionsRequest()
  924. params = {"Model": self.model_name, "Messages": _history, **_gen_conf}
  925. req.from_json_string(json.dumps(params))
  926. ans = ""
  927. try:
  928. response = self.client.ChatCompletions(req)
  929. ans = response.Choices[0].Message.Content
  930. return ans, response.Usage.TotalTokens
  931. except TencentCloudSDKException as e:
  932. return ans + "\n**ERROR**: " + str(e), 0
  933. def chat_streamly(self, system, history, gen_conf):
  934. from tencentcloud.hunyuan.v20230901 import models
  935. from tencentcloud.common.exception.tencent_cloud_sdk_exception import (
  936. TencentCloudSDKException,
  937. )
  938. _gen_conf = {}
  939. _history = [{k.capitalize(): v for k, v in item.items() } for item in history]
  940. if system:
  941. _history.insert(0, {"Role": "system", "Content": system})
  942. if "temperature" in gen_conf:
  943. _gen_conf["Temperature"] = gen_conf["temperature"]
  944. if "top_p" in gen_conf:
  945. _gen_conf["TopP"] = gen_conf["top_p"]
  946. req = models.ChatCompletionsRequest()
  947. params = {
  948. "Model": self.model_name,
  949. "Messages": _history,
  950. "Stream": True,
  951. **_gen_conf,
  952. }
  953. req.from_json_string(json.dumps(params))
  954. ans = ""
  955. total_tokens = 0
  956. try:
  957. response = self.client.ChatCompletions(req)
  958. for resp in response:
  959. resp = json.loads(resp["data"])
  960. if not resp["Choices"] or not resp["Choices"][0]["Delta"]["Content"]:
  961. continue
  962. ans += resp["Choices"][0]["Delta"]["Content"]
  963. total_tokens += 1
  964. yield ans
  965. except TencentCloudSDKException as e:
  966. yield ans + "\n**ERROR**: " + str(e)
  967. yield total_tokens
  968. class SparkChat(Base):
  969. def __init__(
  970. self, key, model_name, base_url="https://spark-api-open.xf-yun.com/v1"
  971. ):
  972. if not base_url:
  973. base_url = "https://spark-api-open.xf-yun.com/v1"
  974. model2version = {
  975. "Spark-Max": "generalv3.5",
  976. "Spark-Lite": "general",
  977. "Spark-Pro": "generalv3",
  978. "Spark-Pro-128K": "pro-128k",
  979. "Spark-4.0-Ultra": "4.0Ultra",
  980. }
  981. model_version = model2version[model_name]
  982. super().__init__(key, model_version, base_url)
  983. class BaiduYiyanChat(Base):
  984. def __init__(self, key, model_name, base_url=None):
  985. import qianfan
  986. key = json.loads(key)
  987. ak = key.get("yiyan_ak","")
  988. sk = key.get("yiyan_sk","")
  989. self.client = qianfan.ChatCompletion(ak=ak,sk=sk)
  990. self.model_name = model_name.lower()
  991. self.system = ""
  992. def chat(self, system, history, gen_conf):
  993. if system:
  994. self.system = system
  995. gen_conf["penalty_score"] = (
  996. (gen_conf.get("presence_penalty", 0) + gen_conf.get("frequency_penalty", 0)) / 2
  997. ) + 1
  998. if "max_tokens" in gen_conf:
  999. gen_conf["max_output_tokens"] = gen_conf["max_tokens"]
  1000. ans = ""
  1001. try:
  1002. response = self.client.do(
  1003. model=self.model_name,
  1004. messages=history,
  1005. system=self.system,
  1006. **gen_conf
  1007. ).body
  1008. ans = response['result']
  1009. return ans, response["usage"]["total_tokens"]
  1010. except Exception as e:
  1011. return ans + "\n**ERROR**: " + str(e), 0
  1012. def chat_streamly(self, system, history, gen_conf):
  1013. if system:
  1014. self.system = system
  1015. gen_conf["penalty_score"] = (
  1016. (gen_conf.get("presence_penalty", 0) + gen_conf.get("frequency_penalty", 0)) / 2
  1017. ) + 1
  1018. if "max_tokens" in gen_conf:
  1019. gen_conf["max_output_tokens"] = gen_conf["max_tokens"]
  1020. ans = ""
  1021. total_tokens = 0
  1022. try:
  1023. response = self.client.do(
  1024. model=self.model_name,
  1025. messages=history,
  1026. system=self.system,
  1027. stream=True,
  1028. **gen_conf
  1029. )
  1030. for resp in response:
  1031. resp = resp.body
  1032. ans += resp['result']
  1033. total_tokens = resp["usage"]["total_tokens"]
  1034. yield ans
  1035. except Exception as e:
  1036. return ans + "\n**ERROR**: " + str(e), 0
  1037. yield total_tokens
  1038. class AnthropicChat(Base):
  1039. def __init__(self, key, model_name, base_url=None):
  1040. import anthropic
  1041. self.client = anthropic.Anthropic(api_key=key)
  1042. self.model_name = model_name
  1043. self.system = ""
  1044. def chat(self, system, history, gen_conf):
  1045. if system:
  1046. self.system = system
  1047. if "max_tokens" not in gen_conf:
  1048. gen_conf["max_tokens"] = 4096
  1049. try:
  1050. response = self.client.messages.create(
  1051. model=self.model_name,
  1052. messages=history,
  1053. system=self.system,
  1054. stream=False,
  1055. **gen_conf,
  1056. ).json()
  1057. ans = response["content"][0]["text"]
  1058. if response["stop_reason"] == "max_tokens":
  1059. ans += (
  1060. "...\nFor the content length reason, it stopped, continue?"
  1061. if is_english([ans])
  1062. else "······\n由于长度的原因,回答被截断了,要继续吗?"
  1063. )
  1064. return (
  1065. ans,
  1066. response["usage"]["input_tokens"] + response["usage"]["output_tokens"],
  1067. )
  1068. except Exception as e:
  1069. return ans + "\n**ERROR**: " + str(e), 0
  1070. def chat_streamly(self, system, history, gen_conf):
  1071. if system:
  1072. self.system = system
  1073. if "max_tokens" not in gen_conf:
  1074. gen_conf["max_tokens"] = 4096
  1075. ans = ""
  1076. total_tokens = 0
  1077. try:
  1078. response = self.client.messages.create(
  1079. model=self.model_name,
  1080. messages=history,
  1081. system=self.system,
  1082. stream=True,
  1083. **gen_conf,
  1084. )
  1085. for res in response.iter_lines():
  1086. res = res.decode("utf-8")
  1087. if "content_block_delta" in res and "data" in res:
  1088. text = json.loads(res[6:])["delta"]["text"]
  1089. ans += text
  1090. total_tokens += num_tokens_from_string(text)
  1091. except Exception as e:
  1092. yield ans + "\n**ERROR**: " + str(e)
  1093. yield total_tokens
  1094. class GoogleChat(Base):
  1095. def __init__(self, key, model_name, base_url=None):
  1096. from google.oauth2 import service_account
  1097. import base64
  1098. key = json.load(key)
  1099. access_token = json.loads(
  1100. base64.b64decode(key.get("google_service_account_key", ""))
  1101. )
  1102. project_id = key.get("google_project_id", "")
  1103. region = key.get("google_region", "")
  1104. scopes = ["https://www.googleapis.com/auth/cloud-platform"]
  1105. self.model_name = model_name
  1106. self.system = ""
  1107. if "claude" in self.model_name:
  1108. from anthropic import AnthropicVertex
  1109. from google.auth.transport.requests import Request
  1110. if access_token:
  1111. credits = service_account.Credentials.from_service_account_info(
  1112. access_token, scopes=scopes
  1113. )
  1114. request = Request()
  1115. credits.refresh(request)
  1116. token = credits.token
  1117. self.client = AnthropicVertex(
  1118. region=region, project_id=project_id, access_token=token
  1119. )
  1120. else:
  1121. self.client = AnthropicVertex(region=region, project_id=project_id)
  1122. else:
  1123. from google.cloud import aiplatform
  1124. import vertexai.generative_models as glm
  1125. if access_token:
  1126. credits = service_account.Credentials.from_service_account_info(
  1127. access_token
  1128. )
  1129. aiplatform.init(
  1130. credentials=credits, project=project_id, location=region
  1131. )
  1132. else:
  1133. aiplatform.init(project=project_id, location=region)
  1134. self.client = glm.GenerativeModel(model_name=self.model_name)
  1135. def chat(self, system, history, gen_conf):
  1136. if system:
  1137. self.system = system
  1138. if "claude" in self.model_name:
  1139. if "max_tokens" not in gen_conf:
  1140. gen_conf["max_tokens"] = 4096
  1141. try:
  1142. response = self.client.messages.create(
  1143. model=self.model_name,
  1144. messages=history,
  1145. system=self.system,
  1146. stream=False,
  1147. **gen_conf,
  1148. ).json()
  1149. ans = response["content"][0]["text"]
  1150. if response["stop_reason"] == "max_tokens":
  1151. ans += (
  1152. "...\nFor the content length reason, it stopped, continue?"
  1153. if is_english([ans])
  1154. else "······\n由于长度的原因,回答被截断了,要继续吗?"
  1155. )
  1156. return (
  1157. ans,
  1158. response["usage"]["input_tokens"]
  1159. + response["usage"]["output_tokens"],
  1160. )
  1161. except Exception as e:
  1162. return "\n**ERROR**: " + str(e), 0
  1163. else:
  1164. self.client._system_instruction = self.system
  1165. if "max_tokens" in gen_conf:
  1166. gen_conf["max_output_tokens"] = gen_conf["max_tokens"]
  1167. for k in list(gen_conf.keys()):
  1168. if k not in ["temperature", "top_p", "max_output_tokens"]:
  1169. del gen_conf[k]
  1170. for item in history:
  1171. if "role" in item and item["role"] == "assistant":
  1172. item["role"] = "model"
  1173. if "content" in item:
  1174. item["parts"] = item.pop("content")
  1175. try:
  1176. response = self.client.generate_content(
  1177. history, generation_config=gen_conf
  1178. )
  1179. ans = response.text
  1180. return ans, response.usage_metadata.total_token_count
  1181. except Exception as e:
  1182. return "**ERROR**: " + str(e), 0
  1183. def chat_streamly(self, system, history, gen_conf):
  1184. if system:
  1185. self.system = system
  1186. if "claude" in self.model_name:
  1187. if "max_tokens" not in gen_conf:
  1188. gen_conf["max_tokens"] = 4096
  1189. ans = ""
  1190. total_tokens = 0
  1191. try:
  1192. response = self.client.messages.create(
  1193. model=self.model_name,
  1194. messages=history,
  1195. system=self.system,
  1196. stream=True,
  1197. **gen_conf,
  1198. )
  1199. for res in response.iter_lines():
  1200. res = res.decode("utf-8")
  1201. if "content_block_delta" in res and "data" in res:
  1202. text = json.loads(res[6:])["delta"]["text"]
  1203. ans += text
  1204. total_tokens += num_tokens_from_string(text)
  1205. except Exception as e:
  1206. yield ans + "\n**ERROR**: " + str(e)
  1207. yield total_tokens
  1208. else:
  1209. self.client._system_instruction = self.system
  1210. if "max_tokens" in gen_conf:
  1211. gen_conf["max_output_tokens"] = gen_conf["max_tokens"]
  1212. for k in list(gen_conf.keys()):
  1213. if k not in ["temperature", "top_p", "max_output_tokens"]:
  1214. del gen_conf[k]
  1215. for item in history:
  1216. if "role" in item and item["role"] == "assistant":
  1217. item["role"] = "model"
  1218. if "content" in item:
  1219. item["parts"] = item.pop("content")
  1220. ans = ""
  1221. try:
  1222. response = self.model.generate_content(
  1223. history, generation_config=gen_conf, stream=True
  1224. )
  1225. for resp in response:
  1226. ans += resp.text
  1227. yield ans
  1228. except Exception as e:
  1229. yield ans + "\n**ERROR**: " + str(e)
  1230. yield response._chunks[-1].usage_metadata.total_token_count