Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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