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.

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