Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

chat_model.py 77KB

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