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.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415
  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. super().__init__(key, model_name, base_url)
  96. class DeepSeekChat(Base):
  97. def __init__(self, key, model_name="deepseek-chat", base_url="https://api.deepseek.com/v1"):
  98. if not base_url: base_url="https://api.deepseek.com/v1"
  99. super().__init__(key, model_name, base_url)
  100. class AzureChat(Base):
  101. def __init__(self, key, model_name, **kwargs):
  102. self.client = AzureOpenAI(api_key=key, azure_endpoint=kwargs["base_url"], api_version="2024-02-01")
  103. self.model_name = model_name
  104. class BaiChuanChat(Base):
  105. def __init__(self, key, model_name="Baichuan3-Turbo", base_url="https://api.baichuan-ai.com/v1"):
  106. if not base_url:
  107. base_url = "https://api.baichuan-ai.com/v1"
  108. super().__init__(key, model_name, base_url)
  109. @staticmethod
  110. def _format_params(params):
  111. return {
  112. "temperature": params.get("temperature", 0.3),
  113. "max_tokens": params.get("max_tokens", 2048),
  114. "top_p": params.get("top_p", 0.85),
  115. }
  116. def chat(self, system, history, gen_conf):
  117. if system:
  118. history.insert(0, {"role": "system", "content": system})
  119. try:
  120. response = self.client.chat.completions.create(
  121. model=self.model_name,
  122. messages=history,
  123. extra_body={
  124. "tools": [{
  125. "type": "web_search",
  126. "web_search": {
  127. "enable": True,
  128. "search_mode": "performance_first"
  129. }
  130. }]
  131. },
  132. **self._format_params(gen_conf))
  133. ans = response.choices[0].message.content.strip()
  134. if response.choices[0].finish_reason == "length":
  135. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  136. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  137. return ans, response.usage.total_tokens
  138. except openai.APIError as e:
  139. return "**ERROR**: " + str(e), 0
  140. def chat_streamly(self, system, history, gen_conf):
  141. if system:
  142. history.insert(0, {"role": "system", "content": system})
  143. ans = ""
  144. total_tokens = 0
  145. try:
  146. response = self.client.chat.completions.create(
  147. model=self.model_name,
  148. messages=history,
  149. extra_body={
  150. "tools": [{
  151. "type": "web_search",
  152. "web_search": {
  153. "enable": True,
  154. "search_mode": "performance_first"
  155. }
  156. }]
  157. },
  158. stream=True,
  159. **self._format_params(gen_conf))
  160. for resp in response:
  161. if not resp.choices:continue
  162. if not resp.choices[0].delta.content:
  163. resp.choices[0].delta.content = ""
  164. ans += resp.choices[0].delta.content
  165. total_tokens = (
  166. (
  167. total_tokens
  168. + num_tokens_from_string(resp.choices[0].delta.content)
  169. )
  170. if not hasattr(resp, "usage")
  171. else resp.usage["total_tokens"]
  172. )
  173. if resp.choices[0].finish_reason == "length":
  174. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  175. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  176. yield ans
  177. except Exception as e:
  178. yield ans + "\n**ERROR**: " + str(e)
  179. yield total_tokens
  180. class QWenChat(Base):
  181. def __init__(self, key, model_name=Generation.Models.qwen_turbo, **kwargs):
  182. import dashscope
  183. dashscope.api_key = key
  184. self.model_name = model_name
  185. def chat(self, system, history, gen_conf):
  186. from http import HTTPStatus
  187. if system:
  188. history.insert(0, {"role": "system", "content": system})
  189. response = Generation.call(
  190. self.model_name,
  191. messages=history,
  192. result_format='message',
  193. **gen_conf
  194. )
  195. ans = ""
  196. tk_count = 0
  197. if response.status_code == HTTPStatus.OK:
  198. ans += response.output.choices[0]['message']['content']
  199. tk_count += response.usage.total_tokens
  200. if response.output.choices[0].get("finish_reason", "") == "length":
  201. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  202. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  203. return ans, tk_count
  204. return "**ERROR**: " + response.message, tk_count
  205. def chat_streamly(self, system, history, gen_conf):
  206. from http import HTTPStatus
  207. if system:
  208. history.insert(0, {"role": "system", "content": system})
  209. ans = ""
  210. tk_count = 0
  211. try:
  212. response = Generation.call(
  213. self.model_name,
  214. messages=history,
  215. result_format='message',
  216. stream=True,
  217. **gen_conf
  218. )
  219. for resp in response:
  220. if resp.status_code == HTTPStatus.OK:
  221. ans = resp.output.choices[0]['message']['content']
  222. tk_count = resp.usage.total_tokens
  223. if resp.output.choices[0].get("finish_reason", "") == "length":
  224. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  225. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  226. yield ans
  227. else:
  228. 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.**"
  229. except Exception as e:
  230. yield ans + "\n**ERROR**: " + str(e)
  231. yield tk_count
  232. class ZhipuChat(Base):
  233. def __init__(self, key, model_name="glm-3-turbo", **kwargs):
  234. self.client = ZhipuAI(api_key=key)
  235. self.model_name = model_name
  236. def chat(self, system, history, gen_conf):
  237. if system:
  238. history.insert(0, {"role": "system", "content": system})
  239. try:
  240. if "presence_penalty" in gen_conf: del gen_conf["presence_penalty"]
  241. if "frequency_penalty" in gen_conf: del gen_conf["frequency_penalty"]
  242. response = self.client.chat.completions.create(
  243. model=self.model_name,
  244. messages=history,
  245. **gen_conf
  246. )
  247. ans = response.choices[0].message.content.strip()
  248. if response.choices[0].finish_reason == "length":
  249. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  250. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  251. return ans, response.usage.total_tokens
  252. except Exception as e:
  253. return "**ERROR**: " + str(e), 0
  254. def chat_streamly(self, system, history, gen_conf):
  255. if system:
  256. history.insert(0, {"role": "system", "content": system})
  257. if "presence_penalty" in gen_conf: del gen_conf["presence_penalty"]
  258. if "frequency_penalty" in gen_conf: del gen_conf["frequency_penalty"]
  259. ans = ""
  260. tk_count = 0
  261. try:
  262. response = self.client.chat.completions.create(
  263. model=self.model_name,
  264. messages=history,
  265. stream=True,
  266. **gen_conf
  267. )
  268. for resp in response:
  269. if not resp.choices[0].delta.content:continue
  270. delta = resp.choices[0].delta.content
  271. ans += delta
  272. if resp.choices[0].finish_reason == "length":
  273. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  274. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  275. tk_count = resp.usage.total_tokens
  276. if resp.choices[0].finish_reason == "stop": tk_count = resp.usage.total_tokens
  277. yield ans
  278. except Exception as e:
  279. yield ans + "\n**ERROR**: " + str(e)
  280. yield tk_count
  281. class OllamaChat(Base):
  282. def __init__(self, key, model_name, **kwargs):
  283. self.client = Client(host=kwargs["base_url"])
  284. self.model_name = model_name
  285. def chat(self, system, history, gen_conf):
  286. if system:
  287. history.insert(0, {"role": "system", "content": system})
  288. try:
  289. options = {}
  290. if "temperature" in gen_conf: options["temperature"] = gen_conf["temperature"]
  291. if "max_tokens" in gen_conf: options["num_predict"] = gen_conf["max_tokens"]
  292. if "top_p" in gen_conf: options["top_k"] = gen_conf["top_p"]
  293. if "presence_penalty" in gen_conf: options["presence_penalty"] = gen_conf["presence_penalty"]
  294. if "frequency_penalty" in gen_conf: options["frequency_penalty"] = gen_conf["frequency_penalty"]
  295. response = self.client.chat(
  296. model=self.model_name,
  297. messages=history,
  298. options=options,
  299. keep_alive=-1
  300. )
  301. ans = response["message"]["content"].strip()
  302. return ans, response["eval_count"] + response.get("prompt_eval_count", 0)
  303. except Exception as e:
  304. return "**ERROR**: " + str(e), 0
  305. def chat_streamly(self, system, history, gen_conf):
  306. if system:
  307. history.insert(0, {"role": "system", "content": system})
  308. options = {}
  309. if "temperature" in gen_conf: options["temperature"] = gen_conf["temperature"]
  310. if "max_tokens" in gen_conf: options["num_predict"] = gen_conf["max_tokens"]
  311. if "top_p" in gen_conf: options["top_k"] = gen_conf["top_p"]
  312. if "presence_penalty" in gen_conf: options["presence_penalty"] = gen_conf["presence_penalty"]
  313. if "frequency_penalty" in gen_conf: options["frequency_penalty"] = gen_conf["frequency_penalty"]
  314. ans = ""
  315. try:
  316. response = self.client.chat(
  317. model=self.model_name,
  318. messages=history,
  319. stream=True,
  320. options=options,
  321. keep_alive=-1
  322. )
  323. for resp in response:
  324. if resp["done"]:
  325. yield resp.get("prompt_eval_count", 0) + resp.get("eval_count", 0)
  326. ans += resp["message"]["content"]
  327. yield ans
  328. except Exception as e:
  329. yield ans + "\n**ERROR**: " + str(e)
  330. yield 0
  331. class LocalAIChat(Base):
  332. def __init__(self, key, model_name, base_url):
  333. if not base_url:
  334. raise ValueError("Local llm url cannot be None")
  335. if base_url.split("/")[-1] != "v1":
  336. base_url = os.path.join(base_url, "v1")
  337. self.client = OpenAI(api_key="empty", base_url=base_url)
  338. self.model_name = model_name.split("___")[0]
  339. class LocalLLM(Base):
  340. class RPCProxy:
  341. def __init__(self, host, port):
  342. self.host = host
  343. self.port = int(port)
  344. self.__conn()
  345. def __conn(self):
  346. from multiprocessing.connection import Client
  347. self._connection = Client(
  348. (self.host, self.port), authkey=b"infiniflow-token4kevinhu"
  349. )
  350. def __getattr__(self, name):
  351. import pickle
  352. def do_rpc(*args, **kwargs):
  353. for _ in range(3):
  354. try:
  355. self._connection.send(pickle.dumps((name, args, kwargs)))
  356. return pickle.loads(self._connection.recv())
  357. except Exception as e:
  358. self.__conn()
  359. raise Exception("RPC connection lost!")
  360. return do_rpc
  361. def __init__(self, key, model_name):
  362. from jina import Client
  363. self.client = Client(port=12345, protocol="grpc", asyncio=True)
  364. def _prepare_prompt(self, system, history, gen_conf):
  365. from rag.svr.jina_server import Prompt,Generation
  366. if system:
  367. history.insert(0, {"role": "system", "content": system})
  368. if "max_tokens" in gen_conf:
  369. gen_conf["max_new_tokens"] = gen_conf.pop("max_tokens")
  370. return Prompt(message=history, gen_conf=gen_conf)
  371. def _stream_response(self, endpoint, prompt):
  372. from rag.svr.jina_server import Prompt,Generation
  373. answer = ""
  374. try:
  375. res = self.client.stream_doc(
  376. on=endpoint, inputs=prompt, return_type=Generation
  377. )
  378. loop = asyncio.get_event_loop()
  379. try:
  380. while True:
  381. answer = loop.run_until_complete(res.__anext__()).text
  382. yield answer
  383. except StopAsyncIteration:
  384. pass
  385. except Exception as e:
  386. yield answer + "\n**ERROR**: " + str(e)
  387. yield num_tokens_from_string(answer)
  388. def chat(self, system, history, gen_conf):
  389. prompt = self._prepare_prompt(system, history, gen_conf)
  390. chat_gen = self._stream_response("/chat", prompt)
  391. ans = next(chat_gen)
  392. total_tokens = next(chat_gen)
  393. return ans, total_tokens
  394. def chat_streamly(self, system, history, gen_conf):
  395. prompt = self._prepare_prompt(system, history, gen_conf)
  396. return self._stream_response("/stream", prompt)
  397. class VolcEngineChat(Base):
  398. def __init__(self, key, model_name, base_url='https://ark.cn-beijing.volces.com/api/v3'):
  399. """
  400. Since do not want to modify the original database fields, and the VolcEngine authentication method is quite special,
  401. Assemble ark_api_key, ep_id into api_key, store it as a dictionary type, and parse it for use
  402. model_name is for display only
  403. """
  404. base_url = base_url if base_url else 'https://ark.cn-beijing.volces.com/api/v3'
  405. ark_api_key = json.loads(key).get('ark_api_key', '')
  406. model_name = json.loads(key).get('ep_id', '') + json.loads(key).get('endpoint_id', '')
  407. super().__init__(ark_api_key, model_name, base_url)
  408. class MiniMaxChat(Base):
  409. def __init__(
  410. self,
  411. key,
  412. model_name,
  413. base_url="https://api.minimax.chat/v1/text/chatcompletion_v2",
  414. ):
  415. if not base_url:
  416. base_url = "https://api.minimax.chat/v1/text/chatcompletion_v2"
  417. self.base_url = base_url
  418. self.model_name = model_name
  419. self.api_key = key
  420. def chat(self, system, history, gen_conf):
  421. if system:
  422. history.insert(0, {"role": "system", "content": system})
  423. for k in list(gen_conf.keys()):
  424. if k not in ["temperature", "top_p", "max_tokens"]:
  425. del gen_conf[k]
  426. headers = {
  427. "Authorization": f"Bearer {self.api_key}",
  428. "Content-Type": "application/json",
  429. }
  430. payload = json.dumps(
  431. {"model": self.model_name, "messages": history, **gen_conf}
  432. )
  433. try:
  434. response = requests.request(
  435. "POST", url=self.base_url, headers=headers, data=payload
  436. )
  437. response = response.json()
  438. ans = response["choices"][0]["message"]["content"].strip()
  439. if response["choices"][0]["finish_reason"] == "length":
  440. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  441. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  442. return ans, response["usage"]["total_tokens"]
  443. except Exception as e:
  444. return "**ERROR**: " + str(e), 0
  445. def chat_streamly(self, system, history, gen_conf):
  446. if system:
  447. history.insert(0, {"role": "system", "content": system})
  448. ans = ""
  449. total_tokens = 0
  450. try:
  451. headers = {
  452. "Authorization": f"Bearer {self.api_key}",
  453. "Content-Type": "application/json",
  454. }
  455. payload = json.dumps(
  456. {
  457. "model": self.model_name,
  458. "messages": history,
  459. "stream": True,
  460. **gen_conf,
  461. }
  462. )
  463. response = requests.request(
  464. "POST",
  465. url=self.base_url,
  466. headers=headers,
  467. data=payload,
  468. )
  469. for resp in response.text.split("\n\n")[:-1]:
  470. resp = json.loads(resp[6:])
  471. text = ""
  472. if "choices" in resp and "delta" in resp["choices"][0]:
  473. text = resp["choices"][0]["delta"]["content"]
  474. ans += text
  475. total_tokens = (
  476. total_tokens + num_tokens_from_string(text)
  477. if "usage" not in resp
  478. else resp["usage"]["total_tokens"]
  479. )
  480. yield ans
  481. except Exception as e:
  482. yield ans + "\n**ERROR**: " + str(e)
  483. yield total_tokens
  484. class MistralChat(Base):
  485. def __init__(self, key, model_name, base_url=None):
  486. from mistralai.client import MistralClient
  487. self.client = MistralClient(api_key=key)
  488. self.model_name = model_name
  489. def chat(self, system, history, gen_conf):
  490. if system:
  491. history.insert(0, {"role": "system", "content": system})
  492. for k in list(gen_conf.keys()):
  493. if k not in ["temperature", "top_p", "max_tokens"]:
  494. del gen_conf[k]
  495. try:
  496. response = self.client.chat(
  497. model=self.model_name,
  498. messages=history,
  499. **gen_conf)
  500. ans = response.choices[0].message.content
  501. if response.choices[0].finish_reason == "length":
  502. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  503. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  504. return ans, response.usage.total_tokens
  505. except openai.APIError as e:
  506. return "**ERROR**: " + str(e), 0
  507. def chat_streamly(self, system, history, gen_conf):
  508. if system:
  509. history.insert(0, {"role": "system", "content": system})
  510. for k in list(gen_conf.keys()):
  511. if k not in ["temperature", "top_p", "max_tokens"]:
  512. del gen_conf[k]
  513. ans = ""
  514. total_tokens = 0
  515. try:
  516. response = self.client.chat_stream(
  517. model=self.model_name,
  518. messages=history,
  519. **gen_conf)
  520. for resp in response:
  521. if not resp.choices or not resp.choices[0].delta.content:continue
  522. ans += resp.choices[0].delta.content
  523. total_tokens += 1
  524. if resp.choices[0].finish_reason == "length":
  525. ans += "...\nFor the content length reason, it stopped, continue?" if is_english(
  526. [ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  527. yield ans
  528. except openai.APIError as e:
  529. yield ans + "\n**ERROR**: " + str(e)
  530. yield total_tokens
  531. class BedrockChat(Base):
  532. def __init__(self, key, model_name, **kwargs):
  533. import boto3
  534. self.bedrock_ak = json.loads(key).get('bedrock_ak', '')
  535. self.bedrock_sk = json.loads(key).get('bedrock_sk', '')
  536. self.bedrock_region = json.loads(key).get('bedrock_region', '')
  537. self.model_name = model_name
  538. self.client = boto3.client(service_name='bedrock-runtime', region_name=self.bedrock_region,
  539. aws_access_key_id=self.bedrock_ak, aws_secret_access_key=self.bedrock_sk)
  540. def chat(self, system, history, gen_conf):
  541. from botocore.exceptions import ClientError
  542. for k in list(gen_conf.keys()):
  543. if k not in ["temperature", "top_p", "max_tokens"]:
  544. del gen_conf[k]
  545. if "max_tokens" in gen_conf:
  546. gen_conf["maxTokens"] = gen_conf["max_tokens"]
  547. _ = gen_conf.pop("max_tokens")
  548. if "top_p" in gen_conf:
  549. gen_conf["topP"] = gen_conf["top_p"]
  550. _ = gen_conf.pop("top_p")
  551. for item in history:
  552. if not isinstance(item["content"],list) and not isinstance(item["content"],tuple):
  553. item["content"] = [{"text":item["content"]}]
  554. try:
  555. # Send the message to the model, using a basic inference configuration.
  556. response = self.client.converse(
  557. modelId=self.model_name,
  558. messages=history,
  559. inferenceConfig=gen_conf,
  560. system=[{"text": system}] if system else None,
  561. )
  562. # Extract and print the response text.
  563. ans = response["output"]["message"]["content"][0]["text"]
  564. return ans, num_tokens_from_string(ans)
  565. except (ClientError, Exception) as e:
  566. return f"ERROR: Can't invoke '{self.model_name}'. Reason: {e}", 0
  567. def chat_streamly(self, system, history, gen_conf):
  568. from botocore.exceptions import ClientError
  569. for k in list(gen_conf.keys()):
  570. if k not in ["temperature", "top_p", "max_tokens"]:
  571. del gen_conf[k]
  572. if "max_tokens" in gen_conf:
  573. gen_conf["maxTokens"] = gen_conf["max_tokens"]
  574. _ = gen_conf.pop("max_tokens")
  575. if "top_p" in gen_conf:
  576. gen_conf["topP"] = gen_conf["top_p"]
  577. _ = gen_conf.pop("top_p")
  578. for item in history:
  579. if not isinstance(item["content"],list) and not isinstance(item["content"],tuple):
  580. item["content"] = [{"text":item["content"]}]
  581. if self.model_name.split('.')[0] == 'ai21':
  582. try:
  583. response = self.client.converse(
  584. modelId=self.model_name,
  585. messages=history,
  586. inferenceConfig=gen_conf,
  587. system=[{"text": system}] if system else None,
  588. )
  589. ans = response["output"]["message"]["content"][0]["text"]
  590. return ans, num_tokens_from_string(ans)
  591. except (ClientError, Exception) as e:
  592. return f"ERROR: Can't invoke '{self.model_name}'. Reason: {e}", 0
  593. ans = ""
  594. try:
  595. # Send the message to the model, using a basic inference configuration.
  596. streaming_response = self.client.converse_stream(
  597. modelId=self.model_name,
  598. messages=history,
  599. inferenceConfig=gen_conf
  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.01.ai/v1"):
  853. if not base_url:
  854. base_url = "https://api.01.ai/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 ans + "\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