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.

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