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

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