Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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