Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

chat_model.py 60KB

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