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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674
  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 cat_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 QWenChat(Base):
  480. _FACTORY_NAME = "Tongyi-Qianwen"
  481. def __init__(self, key, model_name=Generation.Models.qwen_turbo, base_url=None, **kwargs):
  482. if not base_url:
  483. base_url = "https://dashscope.aliyuncs.com/compatible-mode/v1"
  484. super().__init__(key, model_name, base_url=base_url, **kwargs)
  485. return
  486. class ZhipuChat(Base):
  487. _FACTORY_NAME = "ZHIPU-AI"
  488. def __init__(self, key, model_name="glm-3-turbo", base_url=None, **kwargs):
  489. super().__init__(key, model_name, base_url=base_url, **kwargs)
  490. self.client = ZhipuAI(api_key=key)
  491. self.model_name = model_name
  492. def _clean_conf(self, gen_conf):
  493. if "max_tokens" in gen_conf:
  494. del gen_conf["max_tokens"]
  495. if "presence_penalty" in gen_conf:
  496. del gen_conf["presence_penalty"]
  497. if "frequency_penalty" in gen_conf:
  498. del gen_conf["frequency_penalty"]
  499. return gen_conf
  500. def chat_with_tools(self, system: str, history: list, gen_conf: dict):
  501. if "presence_penalty" in gen_conf:
  502. del gen_conf["presence_penalty"]
  503. if "frequency_penalty" in gen_conf:
  504. del gen_conf["frequency_penalty"]
  505. return super().chat_with_tools(system, history, gen_conf)
  506. def chat_streamly(self, system, history, gen_conf):
  507. if system:
  508. history.insert(0, {"role": "system", "content": system})
  509. if "max_tokens" in gen_conf:
  510. del gen_conf["max_tokens"]
  511. if "presence_penalty" in gen_conf:
  512. del gen_conf["presence_penalty"]
  513. if "frequency_penalty" in gen_conf:
  514. del gen_conf["frequency_penalty"]
  515. ans = ""
  516. tk_count = 0
  517. try:
  518. response = self.client.chat.completions.create(model=self.model_name, messages=history, stream=True, **gen_conf)
  519. for resp in response:
  520. if not resp.choices[0].delta.content:
  521. continue
  522. delta = resp.choices[0].delta.content
  523. ans = delta
  524. if resp.choices[0].finish_reason == "length":
  525. if is_chinese(ans):
  526. ans += LENGTH_NOTIFICATION_CN
  527. else:
  528. ans += LENGTH_NOTIFICATION_EN
  529. tk_count = self.total_token_count(resp)
  530. if resp.choices[0].finish_reason == "stop":
  531. tk_count = self.total_token_count(resp)
  532. yield ans
  533. except Exception as e:
  534. yield ans + "\n**ERROR**: " + str(e)
  535. yield tk_count
  536. def chat_streamly_with_tools(self, system: str, history: list, gen_conf: dict):
  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 super().chat_streamly_with_tools(system, history, gen_conf)
  542. class OllamaChat(Base):
  543. _FACTORY_NAME = "Ollama"
  544. def __init__(self, key, model_name, base_url=None, **kwargs):
  545. super().__init__(key, model_name, base_url=base_url, **kwargs)
  546. self.client = Client(host=base_url) if not key or key == "x" else Client(host=base_url, headers={"Authorization": f"Bearer {key}"})
  547. self.model_name = model_name
  548. def _clean_conf(self, gen_conf):
  549. options = {}
  550. if "max_tokens" in gen_conf:
  551. options["num_predict"] = gen_conf["max_tokens"]
  552. for k in ["temperature", "top_p", "presence_penalty", "frequency_penalty"]:
  553. if k not in gen_conf:
  554. continue
  555. options[k] = gen_conf[k]
  556. return options
  557. def _chat(self, history, gen_conf):
  558. # Calculate context size
  559. ctx_size = self._calculate_dynamic_ctx(history)
  560. gen_conf["num_ctx"] = ctx_size
  561. response = self.client.chat(model=self.model_name, messages=history, options=gen_conf, keep_alive=-1)
  562. ans = response["message"]["content"].strip()
  563. token_count = response.get("eval_count", 0) + response.get("prompt_eval_count", 0)
  564. return ans, token_count
  565. def chat_streamly(self, system, history, gen_conf):
  566. if system:
  567. history.insert(0, {"role": "system", "content": system})
  568. if "max_tokens" in gen_conf:
  569. del gen_conf["max_tokens"]
  570. try:
  571. # Calculate context size
  572. ctx_size = self._calculate_dynamic_ctx(history)
  573. options = {"num_ctx": ctx_size}
  574. if "temperature" in gen_conf:
  575. options["temperature"] = gen_conf["temperature"]
  576. if "max_tokens" in gen_conf:
  577. options["num_predict"] = gen_conf["max_tokens"]
  578. if "top_p" in gen_conf:
  579. options["top_p"] = gen_conf["top_p"]
  580. if "presence_penalty" in gen_conf:
  581. options["presence_penalty"] = gen_conf["presence_penalty"]
  582. if "frequency_penalty" in gen_conf:
  583. options["frequency_penalty"] = gen_conf["frequency_penalty"]
  584. ans = ""
  585. try:
  586. response = self.client.chat(model=self.model_name, messages=history, stream=True, options=options, keep_alive=-1)
  587. for resp in response:
  588. if resp["done"]:
  589. token_count = resp.get("prompt_eval_count", 0) + resp.get("eval_count", 0)
  590. yield token_count
  591. ans = resp["message"]["content"]
  592. yield ans
  593. except Exception as e:
  594. yield ans + "\n**ERROR**: " + str(e)
  595. yield 0
  596. except Exception as e:
  597. yield "**ERROR**: " + str(e)
  598. yield 0
  599. class LocalAIChat(Base):
  600. _FACTORY_NAME = "LocalAI"
  601. def __init__(self, key, model_name, base_url=None, **kwargs):
  602. super().__init__(key, model_name, base_url=base_url, **kwargs)
  603. if not base_url:
  604. raise ValueError("Local llm url cannot be None")
  605. base_url = urljoin(base_url, "v1")
  606. self.client = OpenAI(api_key="empty", base_url=base_url)
  607. self.model_name = model_name.split("___")[0]
  608. class LocalLLM(Base):
  609. def __init__(self, key, model_name, base_url=None, **kwargs):
  610. super().__init__(key, model_name, base_url=base_url, **kwargs)
  611. from jina import Client
  612. self.client = Client(port=12345, protocol="grpc", asyncio=True)
  613. def _prepare_prompt(self, system, history, gen_conf):
  614. from rag.svr.jina_server import Prompt
  615. if system:
  616. history.insert(0, {"role": "system", "content": system})
  617. return Prompt(message=history, gen_conf=gen_conf)
  618. def _stream_response(self, endpoint, prompt):
  619. from rag.svr.jina_server import Generation
  620. answer = ""
  621. try:
  622. res = self.client.stream_doc(on=endpoint, inputs=prompt, return_type=Generation)
  623. loop = asyncio.get_event_loop()
  624. try:
  625. while True:
  626. answer = loop.run_until_complete(res.__anext__()).text
  627. yield answer
  628. except StopAsyncIteration:
  629. pass
  630. except Exception as e:
  631. yield answer + "\n**ERROR**: " + str(e)
  632. yield num_tokens_from_string(answer)
  633. def chat(self, system, history, gen_conf):
  634. if "max_tokens" in gen_conf:
  635. del gen_conf["max_tokens"]
  636. prompt = self._prepare_prompt(system, history, gen_conf)
  637. chat_gen = self._stream_response("/chat", prompt)
  638. ans = next(chat_gen)
  639. total_tokens = next(chat_gen)
  640. return ans, total_tokens
  641. def chat_streamly(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. return self._stream_response("/stream", prompt)
  646. class VolcEngineChat(Base):
  647. _FACTORY_NAME = "VolcEngine"
  648. def __init__(self, key, model_name, base_url="https://ark.cn-beijing.volces.com/api/v3", **kwargs):
  649. """
  650. Since do not want to modify the original database fields, and the VolcEngine authentication method is quite special,
  651. Assemble ark_api_key, ep_id into api_key, store it as a dictionary type, and parse it for use
  652. model_name is for display only
  653. """
  654. base_url = base_url if base_url else "https://ark.cn-beijing.volces.com/api/v3"
  655. ark_api_key = json.loads(key).get("ark_api_key", "")
  656. model_name = json.loads(key).get("ep_id", "") + json.loads(key).get("endpoint_id", "")
  657. super().__init__(ark_api_key, model_name, base_url, **kwargs)
  658. class MiniMaxChat(Base):
  659. _FACTORY_NAME = "MiniMax"
  660. def __init__(self, key, model_name, base_url="https://api.minimax.chat/v1/text/chatcompletion_v2", **kwargs):
  661. super().__init__(key, model_name, base_url=base_url, **kwargs)
  662. if not base_url:
  663. base_url = "https://api.minimax.chat/v1/text/chatcompletion_v2"
  664. self.base_url = base_url
  665. self.model_name = model_name
  666. self.api_key = key
  667. def _clean_conf(self, gen_conf):
  668. for k in list(gen_conf.keys()):
  669. if k not in ["temperature", "top_p", "max_tokens"]:
  670. del gen_conf[k]
  671. return gen_conf
  672. def _chat(self, history, gen_conf):
  673. headers = {
  674. "Authorization": f"Bearer {self.api_key}",
  675. "Content-Type": "application/json",
  676. }
  677. payload = json.dumps({"model": self.model_name, "messages": history, **gen_conf})
  678. response = requests.request("POST", url=self.base_url, headers=headers, data=payload)
  679. response = response.json()
  680. ans = response["choices"][0]["message"]["content"].strip()
  681. if response["choices"][0]["finish_reason"] == "length":
  682. if is_chinese(ans):
  683. ans += LENGTH_NOTIFICATION_CN
  684. else:
  685. ans += LENGTH_NOTIFICATION_EN
  686. return ans, self.total_token_count(response)
  687. def chat_streamly(self, system, history, gen_conf):
  688. if system:
  689. history.insert(0, {"role": "system", "content": system})
  690. for k in list(gen_conf.keys()):
  691. if k not in ["temperature", "top_p", "max_tokens"]:
  692. del gen_conf[k]
  693. ans = ""
  694. total_tokens = 0
  695. try:
  696. headers = {
  697. "Authorization": f"Bearer {self.api_key}",
  698. "Content-Type": "application/json",
  699. }
  700. payload = json.dumps(
  701. {
  702. "model": self.model_name,
  703. "messages": history,
  704. "stream": True,
  705. **gen_conf,
  706. }
  707. )
  708. response = requests.request(
  709. "POST",
  710. url=self.base_url,
  711. headers=headers,
  712. data=payload,
  713. )
  714. for resp in response.text.split("\n\n")[:-1]:
  715. resp = json.loads(resp[6:])
  716. text = ""
  717. if "choices" in resp and "delta" in resp["choices"][0]:
  718. text = resp["choices"][0]["delta"]["content"]
  719. ans = text
  720. tol = self.total_token_count(resp)
  721. if not tol:
  722. total_tokens += num_tokens_from_string(text)
  723. else:
  724. total_tokens = tol
  725. yield ans
  726. except Exception as e:
  727. yield ans + "\n**ERROR**: " + str(e)
  728. yield total_tokens
  729. class MistralChat(Base):
  730. _FACTORY_NAME = "Mistral"
  731. def __init__(self, key, model_name, base_url=None, **kwargs):
  732. super().__init__(key, model_name, base_url=base_url, **kwargs)
  733. from mistralai.client import MistralClient
  734. self.client = MistralClient(api_key=key)
  735. self.model_name = model_name
  736. def _clean_conf(self, gen_conf):
  737. for k in list(gen_conf.keys()):
  738. if k not in ["temperature", "top_p", "max_tokens"]:
  739. del gen_conf[k]
  740. return gen_conf
  741. def _chat(self, history, gen_conf):
  742. response = self.client.chat(model=self.model_name, messages=history, **gen_conf)
  743. ans = response.choices[0].message.content
  744. if response.choices[0].finish_reason == "length":
  745. if is_chinese(ans):
  746. ans += LENGTH_NOTIFICATION_CN
  747. else:
  748. ans += LENGTH_NOTIFICATION_EN
  749. return ans, self.total_token_count(response)
  750. def chat_streamly(self, system, history, gen_conf):
  751. if system:
  752. history.insert(0, {"role": "system", "content": system})
  753. for k in list(gen_conf.keys()):
  754. if k not in ["temperature", "top_p", "max_tokens"]:
  755. del gen_conf[k]
  756. ans = ""
  757. total_tokens = 0
  758. try:
  759. response = self.client.chat_stream(model=self.model_name, messages=history, **gen_conf)
  760. for resp in response:
  761. if not resp.choices or not resp.choices[0].delta.content:
  762. continue
  763. ans = resp.choices[0].delta.content
  764. total_tokens += 1
  765. if resp.choices[0].finish_reason == "length":
  766. if is_chinese(ans):
  767. ans += LENGTH_NOTIFICATION_CN
  768. else:
  769. ans += LENGTH_NOTIFICATION_EN
  770. yield ans
  771. except openai.APIError as e:
  772. yield ans + "\n**ERROR**: " + str(e)
  773. yield total_tokens
  774. class BedrockChat(Base):
  775. _FACTORY_NAME = "Bedrock"
  776. def __init__(self, key, model_name, base_url=None, **kwargs):
  777. super().__init__(key, model_name, base_url=base_url, **kwargs)
  778. import boto3
  779. self.bedrock_ak = json.loads(key).get("bedrock_ak", "")
  780. self.bedrock_sk = json.loads(key).get("bedrock_sk", "")
  781. self.bedrock_region = json.loads(key).get("bedrock_region", "")
  782. self.model_name = model_name
  783. if self.bedrock_ak == "" or self.bedrock_sk == "" or self.bedrock_region == "":
  784. # Try to create a client using the default credentials (AWS_PROFILE, AWS_DEFAULT_REGION, etc.)
  785. self.client = boto3.client("bedrock-runtime")
  786. else:
  787. 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)
  788. def _clean_conf(self, gen_conf):
  789. for k in list(gen_conf.keys()):
  790. if k not in ["temperature"]:
  791. del gen_conf[k]
  792. return gen_conf
  793. def _chat(self, history, gen_conf):
  794. system = history[0]["content"] if history and history[0]["role"] == "system" else ""
  795. hist = []
  796. for item in history:
  797. if item["role"] == "system":
  798. continue
  799. hist.append(deepcopy(item))
  800. if not isinstance(hist[-1]["content"], list) and not isinstance(hist[-1]["content"], tuple):
  801. hist[-1]["content"] = [{"text": hist[-1]["content"]}]
  802. # Send the message to the model, using a basic inference configuration.
  803. response = self.client.converse(
  804. modelId=self.model_name,
  805. messages=hist,
  806. inferenceConfig=gen_conf,
  807. system=[{"text": (system if system else "Answer the user's message.")}],
  808. )
  809. # Extract and print the response text.
  810. ans = response["output"]["message"]["content"][0]["text"]
  811. return ans, num_tokens_from_string(ans)
  812. def chat_streamly(self, system, history, gen_conf):
  813. from botocore.exceptions import ClientError
  814. for k in list(gen_conf.keys()):
  815. if k not in ["temperature"]:
  816. del gen_conf[k]
  817. for item in history:
  818. if not isinstance(item["content"], list) and not isinstance(item["content"], tuple):
  819. item["content"] = [{"text": item["content"]}]
  820. if self.model_name.split(".")[0] == "ai21":
  821. try:
  822. response = self.client.converse(modelId=self.model_name, messages=history, inferenceConfig=gen_conf, system=[{"text": (system if system else "Answer the user's message.")}])
  823. ans = response["output"]["message"]["content"][0]["text"]
  824. return ans, num_tokens_from_string(ans)
  825. except (ClientError, Exception) as e:
  826. return f"ERROR: Can't invoke '{self.model_name}'. Reason: {e}", 0
  827. ans = ""
  828. try:
  829. # Send the message to the model, using a basic inference configuration.
  830. streaming_response = self.client.converse_stream(
  831. modelId=self.model_name, messages=history, inferenceConfig=gen_conf, system=[{"text": (system if system else "Answer the user's message.")}]
  832. )
  833. # Extract and print the streamed response text in real-time.
  834. for resp in streaming_response["stream"]:
  835. if "contentBlockDelta" in resp:
  836. ans = resp["contentBlockDelta"]["delta"]["text"]
  837. yield ans
  838. except (ClientError, Exception) as e:
  839. yield ans + f"ERROR: Can't invoke '{self.model_name}'. Reason: {e}"
  840. yield num_tokens_from_string(ans)
  841. class GeminiChat(Base):
  842. _FACTORY_NAME = "Gemini"
  843. def __init__(self, key, model_name, base_url=None, **kwargs):
  844. super().__init__(key, model_name, base_url=base_url, **kwargs)
  845. from google.generativeai import GenerativeModel, client
  846. client.configure(api_key=key)
  847. _client = client.get_default_generative_client()
  848. self.model_name = "models/" + model_name
  849. self.model = GenerativeModel(model_name=self.model_name)
  850. self.model._client = _client
  851. def _clean_conf(self, gen_conf):
  852. for k in list(gen_conf.keys()):
  853. if k not in ["temperature", "top_p", "max_tokens"]:
  854. del gen_conf[k]
  855. return gen_conf
  856. def _chat(self, history, gen_conf):
  857. from google.generativeai.types import content_types
  858. system = history[0]["content"] if history and history[0]["role"] == "system" else ""
  859. hist = []
  860. for item in history:
  861. if item["role"] == "system":
  862. continue
  863. hist.append(deepcopy(item))
  864. item = hist[-1]
  865. if "role" in item and item["role"] == "assistant":
  866. item["role"] = "model"
  867. if "role" in item and item["role"] == "system":
  868. item["role"] = "user"
  869. if "content" in item:
  870. item["parts"] = item.pop("content")
  871. if system:
  872. self.model._system_instruction = content_types.to_content(system)
  873. response = self.model.generate_content(hist, generation_config=gen_conf)
  874. ans = response.text
  875. return ans, response.usage_metadata.total_token_count
  876. def chat_streamly(self, system, history, gen_conf):
  877. from google.generativeai.types import content_types
  878. gen_conf = self._clean_conf(gen_conf)
  879. if system:
  880. self.model._system_instruction = content_types.to_content(system)
  881. for item in history:
  882. if "role" in item and item["role"] == "assistant":
  883. item["role"] = "model"
  884. if "content" in item:
  885. item["parts"] = item.pop("content")
  886. ans = ""
  887. try:
  888. response = self.model.generate_content(history, generation_config=gen_conf, stream=True)
  889. for resp in response:
  890. ans = resp.text
  891. yield ans
  892. yield response._chunks[-1].usage_metadata.total_token_count
  893. except Exception as e:
  894. yield ans + "\n**ERROR**: " + str(e)
  895. yield 0
  896. class GroqChat(Base):
  897. _FACTORY_NAME = "Groq"
  898. def __init__(self, key, model_name, base_url=None, **kwargs):
  899. super().__init__(key, model_name, base_url=base_url, **kwargs)
  900. from groq import Groq
  901. self.client = Groq(api_key=key)
  902. self.model_name = model_name
  903. def _clean_conf(self, gen_conf):
  904. for k in list(gen_conf.keys()):
  905. if k not in ["temperature", "top_p", "max_tokens"]:
  906. del gen_conf[k]
  907. return gen_conf
  908. def chat_streamly(self, system, history, gen_conf):
  909. if system:
  910. history.insert(0, {"role": "system", "content": system})
  911. for k in list(gen_conf.keys()):
  912. if k not in ["temperature", "top_p", "max_tokens"]:
  913. del gen_conf[k]
  914. ans = ""
  915. total_tokens = 0
  916. try:
  917. response = self.client.chat.completions.create(model=self.model_name, messages=history, stream=True, **gen_conf)
  918. for resp in response:
  919. if not resp.choices or not resp.choices[0].delta.content:
  920. continue
  921. ans = resp.choices[0].delta.content
  922. total_tokens += 1
  923. if resp.choices[0].finish_reason == "length":
  924. if is_chinese(ans):
  925. ans += LENGTH_NOTIFICATION_CN
  926. else:
  927. ans += LENGTH_NOTIFICATION_EN
  928. yield ans
  929. except Exception as e:
  930. yield ans + "\n**ERROR**: " + str(e)
  931. yield total_tokens
  932. ## openrouter
  933. class OpenRouterChat(Base):
  934. _FACTORY_NAME = "OpenRouter"
  935. def __init__(self, key, model_name, base_url="https://openrouter.ai/api/v1", **kwargs):
  936. if not base_url:
  937. base_url = "https://openrouter.ai/api/v1"
  938. super().__init__(key, model_name, base_url, **kwargs)
  939. class StepFunChat(Base):
  940. _FACTORY_NAME = "StepFun"
  941. def __init__(self, key, model_name, base_url="https://api.stepfun.com/v1", **kwargs):
  942. if not base_url:
  943. base_url = "https://api.stepfun.com/v1"
  944. super().__init__(key, model_name, base_url, **kwargs)
  945. class NvidiaChat(Base):
  946. _FACTORY_NAME = "NVIDIA"
  947. def __init__(self, key, model_name, base_url="https://integrate.api.nvidia.com/v1", **kwargs):
  948. if not base_url:
  949. base_url = "https://integrate.api.nvidia.com/v1"
  950. super().__init__(key, model_name, base_url, **kwargs)
  951. class LmStudioChat(Base):
  952. _FACTORY_NAME = "LM-Studio"
  953. def __init__(self, key, model_name, base_url, **kwargs):
  954. if not base_url:
  955. raise ValueError("Local llm url cannot be None")
  956. base_url = urljoin(base_url, "v1")
  957. super().__init__(key, model_name, base_url, **kwargs)
  958. self.client = OpenAI(api_key="lm-studio", base_url=base_url)
  959. self.model_name = model_name
  960. class OpenAI_APIChat(Base):
  961. _FACTORY_NAME = ["VLLM", "OpenAI-API-Compatible"]
  962. def __init__(self, key, model_name, base_url):
  963. if not base_url:
  964. raise ValueError("url cannot be None")
  965. model_name = model_name.split("___")[0]
  966. super().__init__(key, model_name, base_url)
  967. class PPIOChat(Base):
  968. _FACTORY_NAME = "PPIO"
  969. def __init__(self, key, model_name, base_url="https://api.ppinfra.com/v3/openai", **kwargs):
  970. if not base_url:
  971. base_url = "https://api.ppinfra.com/v3/openai"
  972. super().__init__(key, model_name, base_url, **kwargs)
  973. class CoHereChat(Base):
  974. _FACTORY_NAME = "Cohere"
  975. def __init__(self, key, model_name, base_url=None, **kwargs):
  976. super().__init__(key, model_name, base_url=base_url, **kwargs)
  977. from cohere import Client
  978. self.client = Client(api_key=key)
  979. self.model_name = model_name
  980. def _clean_conf(self, gen_conf):
  981. if "max_tokens" in gen_conf:
  982. del gen_conf["max_tokens"]
  983. if "top_p" in gen_conf:
  984. gen_conf["p"] = gen_conf.pop("top_p")
  985. if "frequency_penalty" in gen_conf and "presence_penalty" in gen_conf:
  986. gen_conf.pop("presence_penalty")
  987. return gen_conf
  988. def _chat(self, history, gen_conf):
  989. hist = []
  990. for item in history:
  991. hist.append(deepcopy(item))
  992. item = hist[-1]
  993. if "role" in item and item["role"] == "user":
  994. item["role"] = "USER"
  995. if "role" in item and item["role"] == "assistant":
  996. item["role"] = "CHATBOT"
  997. if "content" in item:
  998. item["message"] = item.pop("content")
  999. mes = hist.pop()["message"]
  1000. response = self.client.chat(model=self.model_name, chat_history=hist, message=mes, **gen_conf)
  1001. ans = response.text
  1002. if response.finish_reason == "MAX_TOKENS":
  1003. ans += "...\nFor the content length reason, it stopped, continue?" if is_english([ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  1004. return (
  1005. ans,
  1006. response.meta.tokens.input_tokens + response.meta.tokens.output_tokens,
  1007. )
  1008. def chat_streamly(self, system, history, gen_conf):
  1009. if system:
  1010. history.insert(0, {"role": "system", "content": system})
  1011. if "max_tokens" in gen_conf:
  1012. del gen_conf["max_tokens"]
  1013. if "top_p" in gen_conf:
  1014. gen_conf["p"] = gen_conf.pop("top_p")
  1015. if "frequency_penalty" in gen_conf and "presence_penalty" in gen_conf:
  1016. gen_conf.pop("presence_penalty")
  1017. for item in history:
  1018. if "role" in item and item["role"] == "user":
  1019. item["role"] = "USER"
  1020. if "role" in item and item["role"] == "assistant":
  1021. item["role"] = "CHATBOT"
  1022. if "content" in item:
  1023. item["message"] = item.pop("content")
  1024. mes = history.pop()["message"]
  1025. ans = ""
  1026. total_tokens = 0
  1027. try:
  1028. response = self.client.chat_stream(model=self.model_name, chat_history=history, message=mes, **gen_conf)
  1029. for resp in response:
  1030. if resp.event_type == "text-generation":
  1031. ans = resp.text
  1032. total_tokens += num_tokens_from_string(resp.text)
  1033. elif resp.event_type == "stream-end":
  1034. if resp.finish_reason == "MAX_TOKENS":
  1035. ans += "...\nFor the content length reason, it stopped, continue?" if is_english([ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  1036. yield ans
  1037. except Exception as e:
  1038. yield ans + "\n**ERROR**: " + str(e)
  1039. yield total_tokens
  1040. class LeptonAIChat(Base):
  1041. _FACTORY_NAME = "LeptonAI"
  1042. def __init__(self, key, model_name, base_url=None, **kwargs):
  1043. if not base_url:
  1044. base_url = urljoin("https://" + model_name + ".lepton.run", "api/v1")
  1045. super().__init__(key, model_name, base_url, **kwargs)
  1046. class TogetherAIChat(Base):
  1047. _FACTORY_NAME = "TogetherAI"
  1048. def __init__(self, key, model_name, base_url="https://api.together.xyz/v1", **kwargs):
  1049. if not base_url:
  1050. base_url = "https://api.together.xyz/v1"
  1051. super().__init__(key, model_name, base_url, **kwargs)
  1052. class PerfXCloudChat(Base):
  1053. _FACTORY_NAME = "PerfXCloud"
  1054. def __init__(self, key, model_name, base_url="https://cloud.perfxlab.cn/v1", **kwargs):
  1055. if not base_url:
  1056. base_url = "https://cloud.perfxlab.cn/v1"
  1057. super().__init__(key, model_name, base_url, **kwargs)
  1058. class UpstageChat(Base):
  1059. _FACTORY_NAME = "Upstage"
  1060. def __init__(self, key, model_name, base_url="https://api.upstage.ai/v1/solar", **kwargs):
  1061. if not base_url:
  1062. base_url = "https://api.upstage.ai/v1/solar"
  1063. super().__init__(key, model_name, base_url, **kwargs)
  1064. class NovitaAIChat(Base):
  1065. _FACTORY_NAME = "NovitaAI"
  1066. def __init__(self, key, model_name, base_url="https://api.novita.ai/v3/openai", **kwargs):
  1067. if not base_url:
  1068. base_url = "https://api.novita.ai/v3/openai"
  1069. super().__init__(key, model_name, base_url, **kwargs)
  1070. class SILICONFLOWChat(Base):
  1071. _FACTORY_NAME = "SILICONFLOW"
  1072. def __init__(self, key, model_name, base_url="https://api.siliconflow.cn/v1", **kwargs):
  1073. if not base_url:
  1074. base_url = "https://api.siliconflow.cn/v1"
  1075. super().__init__(key, model_name, base_url, **kwargs)
  1076. class YiChat(Base):
  1077. _FACTORY_NAME = "01.AI"
  1078. def __init__(self, key, model_name, base_url="https://api.lingyiwanwu.com/v1", **kwargs):
  1079. if not base_url:
  1080. base_url = "https://api.lingyiwanwu.com/v1"
  1081. super().__init__(key, model_name, base_url, **kwargs)
  1082. class GiteeChat(Base):
  1083. _FACTORY_NAME = "GiteeAI"
  1084. def __init__(self, key, model_name, base_url="https://ai.gitee.com/v1/", **kwargs):
  1085. if not base_url:
  1086. base_url = "https://ai.gitee.com/v1/"
  1087. super().__init__(key, model_name, base_url, **kwargs)
  1088. class ReplicateChat(Base):
  1089. _FACTORY_NAME = "Replicate"
  1090. def __init__(self, key, model_name, base_url=None, **kwargs):
  1091. super().__init__(key, model_name, base_url=base_url, **kwargs)
  1092. from replicate.client import Client
  1093. self.model_name = model_name
  1094. self.client = Client(api_token=key)
  1095. def _chat(self, history, gen_conf):
  1096. system = history[0]["content"] if history and history[0]["role"] == "system" else ""
  1097. prompt = "\n".join([item["role"] + ":" + item["content"] for item in history[-5:] if item["role"] != "system"])
  1098. response = self.client.run(
  1099. self.model_name,
  1100. input={"system_prompt": system, "prompt": prompt, **gen_conf},
  1101. )
  1102. ans = "".join(response)
  1103. return ans, num_tokens_from_string(ans)
  1104. def chat_streamly(self, system, history, gen_conf):
  1105. if "max_tokens" in gen_conf:
  1106. del gen_conf["max_tokens"]
  1107. prompt = "\n".join([item["role"] + ":" + item["content"] for item in history[-5:]])
  1108. ans = ""
  1109. try:
  1110. response = self.client.run(
  1111. self.model_name,
  1112. input={"system_prompt": system, "prompt": prompt, **gen_conf},
  1113. )
  1114. for resp in response:
  1115. ans = resp
  1116. yield ans
  1117. except Exception as e:
  1118. yield ans + "\n**ERROR**: " + str(e)
  1119. yield num_tokens_from_string(ans)
  1120. class HunyuanChat(Base):
  1121. _FACTORY_NAME = "Tencent Hunyuan"
  1122. def __init__(self, key, model_name, base_url=None, **kwargs):
  1123. super().__init__(key, model_name, base_url=base_url, **kwargs)
  1124. from tencentcloud.common import credential
  1125. from tencentcloud.hunyuan.v20230901 import hunyuan_client
  1126. key = json.loads(key)
  1127. sid = key.get("hunyuan_sid", "")
  1128. sk = key.get("hunyuan_sk", "")
  1129. cred = credential.Credential(sid, sk)
  1130. self.model_name = model_name
  1131. self.client = hunyuan_client.HunyuanClient(cred, "")
  1132. def _clean_conf(self, gen_conf):
  1133. _gen_conf = {}
  1134. if "temperature" in gen_conf:
  1135. _gen_conf["Temperature"] = gen_conf["temperature"]
  1136. if "top_p" in gen_conf:
  1137. _gen_conf["TopP"] = gen_conf["top_p"]
  1138. return _gen_conf
  1139. def _chat(self, history, gen_conf):
  1140. from tencentcloud.hunyuan.v20230901 import models
  1141. hist = [{k.capitalize(): v for k, v in item.items()} for item in history]
  1142. req = models.ChatCompletionsRequest()
  1143. params = {"Model": self.model_name, "Messages": hist, **gen_conf}
  1144. req.from_json_string(json.dumps(params))
  1145. response = self.client.ChatCompletions(req)
  1146. ans = response.Choices[0].Message.Content
  1147. return ans, response.Usage.TotalTokens
  1148. def chat_streamly(self, system, history, gen_conf):
  1149. from tencentcloud.common.exception.tencent_cloud_sdk_exception import (
  1150. TencentCloudSDKException,
  1151. )
  1152. from tencentcloud.hunyuan.v20230901 import models
  1153. _gen_conf = {}
  1154. _history = [{k.capitalize(): v for k, v in item.items()} for item in history]
  1155. if system:
  1156. _history.insert(0, {"Role": "system", "Content": system})
  1157. if "max_tokens" in gen_conf:
  1158. del gen_conf["max_tokens"]
  1159. if "temperature" in gen_conf:
  1160. _gen_conf["Temperature"] = gen_conf["temperature"]
  1161. if "top_p" in gen_conf:
  1162. _gen_conf["TopP"] = gen_conf["top_p"]
  1163. req = models.ChatCompletionsRequest()
  1164. params = {
  1165. "Model": self.model_name,
  1166. "Messages": _history,
  1167. "Stream": True,
  1168. **_gen_conf,
  1169. }
  1170. req.from_json_string(json.dumps(params))
  1171. ans = ""
  1172. total_tokens = 0
  1173. try:
  1174. response = self.client.ChatCompletions(req)
  1175. for resp in response:
  1176. resp = json.loads(resp["data"])
  1177. if not resp["Choices"] or not resp["Choices"][0]["Delta"]["Content"]:
  1178. continue
  1179. ans = resp["Choices"][0]["Delta"]["Content"]
  1180. total_tokens += 1
  1181. yield ans
  1182. except TencentCloudSDKException as e:
  1183. yield ans + "\n**ERROR**: " + str(e)
  1184. yield total_tokens
  1185. class SparkChat(Base):
  1186. _FACTORY_NAME = "XunFei Spark"
  1187. def __init__(self, key, model_name, base_url="https://spark-api-open.xf-yun.com/v1", **kwargs):
  1188. if not base_url:
  1189. base_url = "https://spark-api-open.xf-yun.com/v1"
  1190. model2version = {
  1191. "Spark-Max": "generalv3.5",
  1192. "Spark-Lite": "general",
  1193. "Spark-Pro": "generalv3",
  1194. "Spark-Pro-128K": "pro-128k",
  1195. "Spark-4.0-Ultra": "4.0Ultra",
  1196. }
  1197. version2model = {v: k for k, v in model2version.items()}
  1198. assert model_name in model2version or model_name in version2model, f"The given model name is not supported yet. Support: {list(model2version.keys())}"
  1199. if model_name in model2version:
  1200. model_version = model2version[model_name]
  1201. else:
  1202. model_version = model_name
  1203. super().__init__(key, model_version, base_url, **kwargs)
  1204. class BaiduYiyanChat(Base):
  1205. _FACTORY_NAME = "BaiduYiyan"
  1206. def __init__(self, key, model_name, base_url=None, **kwargs):
  1207. super().__init__(key, model_name, base_url=base_url, **kwargs)
  1208. import qianfan
  1209. key = json.loads(key)
  1210. ak = key.get("yiyan_ak", "")
  1211. sk = key.get("yiyan_sk", "")
  1212. self.client = qianfan.ChatCompletion(ak=ak, sk=sk)
  1213. self.model_name = model_name.lower()
  1214. def _clean_conf(self, gen_conf):
  1215. gen_conf["penalty_score"] = ((gen_conf.get("presence_penalty", 0) + gen_conf.get("frequency_penalty", 0)) / 2) + 1
  1216. if "max_tokens" in gen_conf:
  1217. del gen_conf["max_tokens"]
  1218. return gen_conf
  1219. def _chat(self, history, gen_conf):
  1220. system = history[0]["content"] if history and history[0]["role"] == "system" else ""
  1221. response = self.client.do(model=self.model_name, messages=[h for h in history if h["role"] != "system"], system=system, **gen_conf).body
  1222. ans = response["result"]
  1223. return ans, self.total_token_count(response)
  1224. def chat_streamly(self, system, history, gen_conf):
  1225. gen_conf["penalty_score"] = ((gen_conf.get("presence_penalty", 0) + gen_conf.get("frequency_penalty", 0)) / 2) + 1
  1226. if "max_tokens" in gen_conf:
  1227. del gen_conf["max_tokens"]
  1228. ans = ""
  1229. total_tokens = 0
  1230. try:
  1231. response = self.client.do(model=self.model_name, messages=history, system=system, stream=True, **gen_conf)
  1232. for resp in response:
  1233. resp = resp.body
  1234. ans = resp["result"]
  1235. total_tokens = self.total_token_count(resp)
  1236. yield ans
  1237. except Exception as e:
  1238. return ans + "\n**ERROR**: " + str(e), 0
  1239. yield total_tokens
  1240. class AnthropicChat(Base):
  1241. _FACTORY_NAME = "Anthropic"
  1242. def __init__(self, key, model_name, base_url="https://api.anthropic.com/v1/", **kwargs):
  1243. if not base_url:
  1244. base_url = "https://api.anthropic.com/v1/"
  1245. super().__init__(key, model_name, base_url=base_url, **kwargs)
  1246. class GoogleChat(Base):
  1247. _FACTORY_NAME = "Google Cloud"
  1248. def __init__(self, key, model_name, base_url=None, **kwargs):
  1249. super().__init__(key, model_name, base_url=base_url, **kwargs)
  1250. import base64
  1251. from google.oauth2 import service_account
  1252. key = json.loads(key)
  1253. access_token = json.loads(base64.b64decode(key.get("google_service_account_key", "")))
  1254. project_id = key.get("google_project_id", "")
  1255. region = key.get("google_region", "")
  1256. scopes = ["https://www.googleapis.com/auth/cloud-platform"]
  1257. self.model_name = model_name
  1258. if "claude" in self.model_name:
  1259. from anthropic import AnthropicVertex
  1260. from google.auth.transport.requests import Request
  1261. if access_token:
  1262. credits = service_account.Credentials.from_service_account_info(access_token, scopes=scopes)
  1263. request = Request()
  1264. credits.refresh(request)
  1265. token = credits.token
  1266. self.client = AnthropicVertex(region=region, project_id=project_id, access_token=token)
  1267. else:
  1268. self.client = AnthropicVertex(region=region, project_id=project_id)
  1269. else:
  1270. import vertexai.generative_models as glm
  1271. from google.cloud import aiplatform
  1272. if access_token:
  1273. credits = service_account.Credentials.from_service_account_info(access_token)
  1274. aiplatform.init(credentials=credits, project=project_id, location=region)
  1275. else:
  1276. aiplatform.init(project=project_id, location=region)
  1277. self.client = glm.GenerativeModel(model_name=self.model_name)
  1278. def _clean_conf(self, gen_conf):
  1279. if "claude" in self.model_name:
  1280. if "max_tokens" in gen_conf:
  1281. del gen_conf["max_tokens"]
  1282. else:
  1283. if "max_tokens" in gen_conf:
  1284. gen_conf["max_output_tokens"] = gen_conf["max_tokens"]
  1285. for k in list(gen_conf.keys()):
  1286. if k not in ["temperature", "top_p", "max_output_tokens"]:
  1287. del gen_conf[k]
  1288. return gen_conf
  1289. def _chat(self, history, gen_conf):
  1290. system = history[0]["content"] if history and history[0]["role"] == "system" else ""
  1291. if "claude" in self.model_name:
  1292. response = self.client.messages.create(
  1293. model=self.model_name,
  1294. messages=[h for h in history if h["role"] != "system"],
  1295. system=system,
  1296. stream=False,
  1297. **gen_conf,
  1298. ).json()
  1299. ans = response["content"][0]["text"]
  1300. if response["stop_reason"] == "max_tokens":
  1301. ans += "...\nFor the content length reason, it stopped, continue?" if is_english([ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  1302. return (
  1303. ans,
  1304. response["usage"]["input_tokens"] + response["usage"]["output_tokens"],
  1305. )
  1306. self.client._system_instruction = system
  1307. hist = []
  1308. for item in history:
  1309. if item["role"] == "system":
  1310. continue
  1311. hist.append(deepcopy(item))
  1312. item = hist[-1]
  1313. if "role" in item and item["role"] == "assistant":
  1314. item["role"] = "model"
  1315. if "content" in item:
  1316. item["parts"] = [
  1317. {
  1318. "text": item.pop("content"),
  1319. }
  1320. ]
  1321. response = self.client.generate_content(hist, generation_config=gen_conf)
  1322. ans = response.text
  1323. return ans, response.usage_metadata.total_token_count
  1324. def chat_streamly(self, system, history, gen_conf):
  1325. if "claude" in self.model_name:
  1326. if "max_tokens" in gen_conf:
  1327. del gen_conf["max_tokens"]
  1328. ans = ""
  1329. total_tokens = 0
  1330. try:
  1331. response = self.client.messages.create(
  1332. model=self.model_name,
  1333. messages=history,
  1334. system=system,
  1335. stream=True,
  1336. **gen_conf,
  1337. )
  1338. for res in response.iter_lines():
  1339. res = res.decode("utf-8")
  1340. if "content_block_delta" in res and "data" in res:
  1341. text = json.loads(res[6:])["delta"]["text"]
  1342. ans = text
  1343. total_tokens += num_tokens_from_string(text)
  1344. except Exception as e:
  1345. yield ans + "\n**ERROR**: " + str(e)
  1346. yield total_tokens
  1347. else:
  1348. self.client._system_instruction = system
  1349. if "max_tokens" in gen_conf:
  1350. gen_conf["max_output_tokens"] = gen_conf["max_tokens"]
  1351. for k in list(gen_conf.keys()):
  1352. if k not in ["temperature", "top_p", "max_output_tokens"]:
  1353. del gen_conf[k]
  1354. for item in history:
  1355. if "role" in item and item["role"] == "assistant":
  1356. item["role"] = "model"
  1357. if "content" in item:
  1358. item["parts"] = item.pop("content")
  1359. ans = ""
  1360. try:
  1361. response = self.model.generate_content(history, generation_config=gen_conf, stream=True)
  1362. for resp in response:
  1363. ans = resp.text
  1364. yield ans
  1365. except Exception as e:
  1366. yield ans + "\n**ERROR**: " + str(e)
  1367. yield response._chunks[-1].usage_metadata.total_token_count
  1368. class GPUStackChat(Base):
  1369. _FACTORY_NAME = "GPUStack"
  1370. def __init__(self, key=None, model_name="", base_url="", **kwargs):
  1371. if not base_url:
  1372. raise ValueError("Local llm url cannot be None")
  1373. base_url = urljoin(base_url, "v1")
  1374. super().__init__(key, model_name, base_url, **kwargs)