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

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