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.

chat_model.py 62KB

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