You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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