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 60KB

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