You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

chat_model.py 82KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003
  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. import openai
  25. import requests
  26. from dashscope import Generation
  27. from ollama import Client
  28. from openai import OpenAI
  29. from openai.lib.azure import AzureOpenAI
  30. from zhipuai import ZhipuAI
  31. from rag.nlp import is_chinese, is_english
  32. from rag.utils import num_tokens_from_string
  33. # Error message constants
  34. ERROR_PREFIX = "**ERROR**"
  35. ERROR_RATE_LIMIT = "RATE_LIMIT_EXCEEDED"
  36. ERROR_AUTHENTICATION = "AUTH_ERROR"
  37. ERROR_INVALID_REQUEST = "INVALID_REQUEST"
  38. ERROR_SERVER = "SERVER_ERROR"
  39. ERROR_TIMEOUT = "TIMEOUT"
  40. ERROR_CONNECTION = "CONNECTION_ERROR"
  41. ERROR_MODEL = "MODEL_ERROR"
  42. ERROR_CONTENT_FILTER = "CONTENT_FILTERED"
  43. ERROR_QUOTA = "QUOTA_EXCEEDED"
  44. ERROR_MAX_RETRIES = "MAX_RETRIES_EXCEEDED"
  45. ERROR_GENERIC = "GENERIC_ERROR"
  46. LENGTH_NOTIFICATION_CN = "······\n由于大模型的上下文窗口大小限制,回答已经被大模型截断。"
  47. LENGTH_NOTIFICATION_EN = "...\nThe answer is truncated by your chosen LLM due to its limitation on context length."
  48. class Base(ABC):
  49. def __init__(self, key, model_name, base_url):
  50. timeout = int(os.environ.get("LM_TIMEOUT_SECONDS", 600))
  51. self.client = OpenAI(api_key=key, base_url=base_url, timeout=timeout)
  52. self.model_name = model_name
  53. # Configure retry parameters
  54. self.max_retries = int(os.environ.get("LLM_MAX_RETRIES", 5))
  55. self.base_delay = float(os.environ.get("LLM_BASE_DELAY", 2.0))
  56. self.is_tools = False
  57. def _get_delay(self, attempt):
  58. """Calculate retry delay time"""
  59. return self.base_delay * (2**attempt) + random.uniform(0, 0.5)
  60. def _classify_error(self, error):
  61. """Classify error based on error message content"""
  62. error_str = str(error).lower()
  63. 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:
  64. return ERROR_RATE_LIMIT
  65. 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:
  66. return ERROR_AUTHENTICATION
  67. 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:
  68. return ERROR_INVALID_REQUEST
  69. 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:
  70. return ERROR_SERVER
  71. elif "timeout" in error_str or "timed out" in error_str:
  72. return ERROR_TIMEOUT
  73. elif "connect" in error_str or "network" in error_str or "unreachable" in error_str or "dns" in error_str:
  74. return ERROR_CONNECTION
  75. 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:
  76. return ERROR_QUOTA
  77. 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:
  78. return ERROR_CONTENT_FILTER
  79. elif "model" in error_str or "not found" in error_str or "does not exist" in error_str or "not available" in error_str:
  80. return ERROR_MODEL
  81. else:
  82. return ERROR_GENERIC
  83. def bind_tools(self, toolcall_session, tools):
  84. if not (toolcall_session and tools):
  85. return
  86. self.is_tools = True
  87. self.toolcall_session = toolcall_session
  88. self.tools = tools
  89. def chat_with_tools(self, system: str, history: list, gen_conf: dict):
  90. if "max_tokens" in gen_conf:
  91. del gen_conf["max_tokens"]
  92. tools = self.tools
  93. if system:
  94. history.insert(0, {"role": "system", "content": system})
  95. ans = ""
  96. tk_count = 0
  97. # Implement exponential backoff retry strategy
  98. for attempt in range(self.max_retries):
  99. try:
  100. response = self.client.chat.completions.create(model=self.model_name, messages=history, tools=tools, **gen_conf)
  101. assistant_output = response.choices[0].message
  102. if not ans and "tool_calls" not in assistant_output and "reasoning_content" in assistant_output:
  103. ans += "<think>" + ans + "</think>"
  104. ans += response.choices[0].message.content
  105. if not response.choices[0].message.tool_calls:
  106. tk_count += self.total_token_count(response)
  107. if response.choices[0].finish_reason == "length":
  108. if is_chinese([ans]):
  109. ans += LENGTH_NOTIFICATION_CN
  110. else:
  111. ans += LENGTH_NOTIFICATION_EN
  112. return ans, tk_count
  113. tk_count += self.total_token_count(response)
  114. history.append(assistant_output)
  115. for tool_call in response.choices[0].message.tool_calls:
  116. name = tool_call.function.name
  117. args = json.loads(tool_call.function.arguments)
  118. tool_response = self.toolcall_session.tool_call(name, args)
  119. # if tool_response.choices[0].finish_reason == "length":
  120. # if is_chinese(ans):
  121. # ans += LENGTH_NOTIFICATION_CN
  122. # else:
  123. # ans += LENGTH_NOTIFICATION_EN
  124. # return ans, tk_count + self.total_token_count(tool_response)
  125. history.append({"role": "tool", "tool_call_id": tool_call.id, "content": str(tool_response)})
  126. final_response = self.client.chat.completions.create(model=self.model_name, messages=history, tools=tools, **gen_conf)
  127. assistant_output = final_response.choices[0].message
  128. if "tool_calls" not in assistant_output and "reasoning_content" in assistant_output:
  129. ans += "<think>" + ans + "</think>"
  130. ans += final_response.choices[0].message.content
  131. if final_response.choices[0].finish_reason == "length":
  132. tk_count += self.total_token_count(response)
  133. if is_chinese([ans]):
  134. ans += LENGTH_NOTIFICATION_CN
  135. else:
  136. ans += LENGTH_NOTIFICATION_EN
  137. return ans, tk_count
  138. return ans, tk_count
  139. except Exception as e:
  140. logging.exception("OpenAI cat_with_tools")
  141. # Classify the error
  142. error_code = self._classify_error(e)
  143. # Check if it's a rate limit error or server error and not the last attempt
  144. should_retry = (error_code == ERROR_RATE_LIMIT or error_code == ERROR_SERVER) and attempt < self.max_retries - 1
  145. if should_retry:
  146. delay = self._get_delay(attempt)
  147. logging.warning(f"Error: {error_code}. Retrying in {delay:.2f} seconds... (Attempt {attempt + 1}/{self.max_retries})")
  148. time.sleep(delay)
  149. else:
  150. # For non-rate limit errors or the last attempt, return an error message
  151. if attempt == self.max_retries - 1:
  152. error_code = ERROR_MAX_RETRIES
  153. return f"{ERROR_PREFIX}: {error_code} - {str(e)}", 0
  154. def chat(self, system, history, gen_conf):
  155. if system:
  156. history.insert(0, {"role": "system", "content": system})
  157. if "max_tokens" in gen_conf:
  158. del gen_conf["max_tokens"]
  159. # Implement exponential backoff retry strategy
  160. for attempt in range(self.max_retries):
  161. try:
  162. response = self.client.chat.completions.create(model=self.model_name, messages=history, **gen_conf)
  163. if any([not response.choices, not response.choices[0].message, not response.choices[0].message.content]):
  164. return "", 0
  165. ans = response.choices[0].message.content.strip()
  166. if response.choices[0].finish_reason == "length":
  167. if is_chinese(ans):
  168. ans += LENGTH_NOTIFICATION_CN
  169. else:
  170. ans += LENGTH_NOTIFICATION_EN
  171. return ans, self.total_token_count(response)
  172. except Exception as e:
  173. logging.exception("chat_model.Base.chat got exception")
  174. # Classify the error
  175. error_code = self._classify_error(e)
  176. # Check if it's a rate limit error or server error and not the last attempt
  177. should_retry = (error_code == ERROR_RATE_LIMIT or error_code == ERROR_SERVER) and attempt < self.max_retries - 1
  178. if should_retry:
  179. delay = self._get_delay(attempt)
  180. logging.warning(f"Error: {error_code}. Retrying in {delay:.2f} seconds... (Attempt {attempt + 1}/{self.max_retries})")
  181. time.sleep(delay)
  182. else:
  183. # For non-rate limit errors or the last attempt, return an error message
  184. if attempt == self.max_retries - 1:
  185. error_code = ERROR_MAX_RETRIES
  186. return f"{ERROR_PREFIX}: {error_code} - {str(e)}", 0
  187. def _wrap_toolcall_message(self, stream):
  188. final_tool_calls = {}
  189. for chunk in stream:
  190. for tool_call in chunk.choices[0].delta.tool_calls or []:
  191. index = tool_call.index
  192. if index not in final_tool_calls:
  193. final_tool_calls[index] = tool_call
  194. final_tool_calls[index].function.arguments += tool_call.function.arguments
  195. return final_tool_calls
  196. def chat_streamly_with_tools(self, system: str, history: list, gen_conf: dict):
  197. if "max_tokens" in gen_conf:
  198. del gen_conf["max_tokens"]
  199. tools = self.tools
  200. if system:
  201. history.insert(0, {"role": "system", "content": system})
  202. ans = ""
  203. total_tokens = 0
  204. reasoning_start = False
  205. finish_completion = False
  206. final_tool_calls = {}
  207. try:
  208. response = self.client.chat.completions.create(model=self.model_name, messages=history, stream=True, tools=tools, **gen_conf)
  209. while not finish_completion:
  210. for resp in response:
  211. if resp.choices[0].delta.tool_calls:
  212. for tool_call in resp.choices[0].delta.tool_calls or []:
  213. index = tool_call.index
  214. if index not in final_tool_calls:
  215. final_tool_calls[index] = tool_call
  216. final_tool_calls[index].function.arguments += tool_call.function.arguments
  217. if resp.choices[0].finish_reason != "stop":
  218. continue
  219. else:
  220. if not resp.choices:
  221. continue
  222. if not resp.choices[0].delta.content:
  223. resp.choices[0].delta.content = ""
  224. if hasattr(resp.choices[0].delta, "reasoning_content") and resp.choices[0].delta.reasoning_content:
  225. ans = ""
  226. if not reasoning_start:
  227. reasoning_start = True
  228. ans = "<think>"
  229. ans += resp.choices[0].delta.reasoning_content + "</think>"
  230. else:
  231. reasoning_start = False
  232. ans = resp.choices[0].delta.content
  233. tol = self.total_token_count(resp)
  234. if not tol:
  235. total_tokens += num_tokens_from_string(resp.choices[0].delta.content)
  236. else:
  237. total_tokens += tol
  238. finish_reason = resp.choices[0].finish_reason
  239. if finish_reason == "tool_calls" and final_tool_calls:
  240. for tool_call in final_tool_calls.values():
  241. name = tool_call.function.name
  242. try:
  243. if name == "get_current_weather":
  244. args = json.loads('{"location":"Shanghai"}')
  245. else:
  246. args = json.loads(tool_call.function.arguments)
  247. except Exception:
  248. continue
  249. # args = json.loads(tool_call.function.arguments)
  250. tool_response = self.toolcall_session.tool_call(name, args)
  251. history.append(
  252. {
  253. "role": "assistant",
  254. "refusal": "",
  255. "content": "",
  256. "audio": "",
  257. "function_call": "",
  258. "tool_calls": [
  259. {
  260. "index": tool_call.index,
  261. "id": tool_call.id,
  262. "function": tool_call.function,
  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 + self.total_token_count(resp)
  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):
  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):
  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):
  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_streamly(self, system, history, gen_conf):
  744. if system:
  745. history.insert(0, {"role": "system", "content": system})
  746. if "max_tokens" in gen_conf:
  747. del gen_conf["max_tokens"]
  748. if "presence_penalty" in gen_conf:
  749. del gen_conf["presence_penalty"]
  750. if "frequency_penalty" in gen_conf:
  751. del gen_conf["frequency_penalty"]
  752. ans = ""
  753. tk_count = 0
  754. try:
  755. response = self.client.chat.completions.create(model=self.model_name, messages=history, stream=True, **gen_conf)
  756. for resp in response:
  757. if not resp.choices[0].delta.content:
  758. continue
  759. delta = resp.choices[0].delta.content
  760. ans = delta
  761. if resp.choices[0].finish_reason == "length":
  762. if is_chinese(ans):
  763. ans += LENGTH_NOTIFICATION_CN
  764. else:
  765. ans += LENGTH_NOTIFICATION_EN
  766. tk_count = self.total_token_count(resp)
  767. if resp.choices[0].finish_reason == "stop":
  768. tk_count = self.total_token_count(resp)
  769. yield ans
  770. except Exception as e:
  771. yield ans + "\n**ERROR**: " + str(e)
  772. yield tk_count
  773. class OllamaChat(Base):
  774. def __init__(self, key, model_name, **kwargs):
  775. super().__init__(key, model_name, base_url=None)
  776. self.client = Client(host=kwargs["base_url"]) if not key or key == "x" else Client(host=kwargs["base_url"], headers={"Authorization": f"Bearer {key}"})
  777. self.model_name = model_name
  778. def chat(self, system, history, gen_conf):
  779. if system:
  780. history.insert(0, {"role": "system", "content": system})
  781. if "max_tokens" in gen_conf:
  782. del gen_conf["max_tokens"]
  783. try:
  784. # Calculate context size
  785. ctx_size = self._calculate_dynamic_ctx(history)
  786. options = {"num_ctx": ctx_size}
  787. if "temperature" in gen_conf:
  788. options["temperature"] = gen_conf["temperature"]
  789. if "max_tokens" in gen_conf:
  790. options["num_predict"] = gen_conf["max_tokens"]
  791. if "top_p" in gen_conf:
  792. options["top_p"] = gen_conf["top_p"]
  793. if "presence_penalty" in gen_conf:
  794. options["presence_penalty"] = gen_conf["presence_penalty"]
  795. if "frequency_penalty" in gen_conf:
  796. options["frequency_penalty"] = gen_conf["frequency_penalty"]
  797. response = self.client.chat(model=self.model_name, messages=history, options=options, keep_alive=10)
  798. ans = response["message"]["content"].strip()
  799. token_count = response.get("eval_count", 0) + response.get("prompt_eval_count", 0)
  800. return ans, token_count
  801. except Exception as e:
  802. return "**ERROR**: " + str(e), 0
  803. def chat_streamly(self, system, history, gen_conf):
  804. if system:
  805. history.insert(0, {"role": "system", "content": system})
  806. if "max_tokens" in gen_conf:
  807. del gen_conf["max_tokens"]
  808. try:
  809. # Calculate context size
  810. ctx_size = self._calculate_dynamic_ctx(history)
  811. options = {"num_ctx": ctx_size}
  812. if "temperature" in gen_conf:
  813. options["temperature"] = gen_conf["temperature"]
  814. if "max_tokens" in gen_conf:
  815. options["num_predict"] = gen_conf["max_tokens"]
  816. if "top_p" in gen_conf:
  817. options["top_p"] = gen_conf["top_p"]
  818. if "presence_penalty" in gen_conf:
  819. options["presence_penalty"] = gen_conf["presence_penalty"]
  820. if "frequency_penalty" in gen_conf:
  821. options["frequency_penalty"] = gen_conf["frequency_penalty"]
  822. ans = ""
  823. try:
  824. response = self.client.chat(model=self.model_name, messages=history, stream=True, options=options, keep_alive=10)
  825. for resp in response:
  826. if resp["done"]:
  827. token_count = resp.get("prompt_eval_count", 0) + resp.get("eval_count", 0)
  828. yield token_count
  829. ans = resp["message"]["content"]
  830. yield ans
  831. except Exception as e:
  832. yield ans + "\n**ERROR**: " + str(e)
  833. yield 0
  834. except Exception as e:
  835. yield "**ERROR**: " + str(e)
  836. yield 0
  837. class LocalAIChat(Base):
  838. def __init__(self, key, model_name, base_url):
  839. super().__init__(key, model_name, base_url=None)
  840. if not base_url:
  841. raise ValueError("Local llm url cannot be None")
  842. if base_url.split("/")[-1] != "v1":
  843. base_url = os.path.join(base_url, "v1")
  844. self.client = OpenAI(api_key="empty", base_url=base_url)
  845. self.model_name = model_name.split("___")[0]
  846. class LocalLLM(Base):
  847. class RPCProxy:
  848. def __init__(self, host, port):
  849. self.host = host
  850. self.port = int(port)
  851. self.__conn()
  852. def __conn(self):
  853. from multiprocessing.connection import Client
  854. self._connection = Client((self.host, self.port), authkey=b"infiniflow-token4kevinhu")
  855. def __getattr__(self, name):
  856. import pickle
  857. def do_rpc(*args, **kwargs):
  858. for _ in range(3):
  859. try:
  860. self._connection.send(pickle.dumps((name, args, kwargs)))
  861. return pickle.loads(self._connection.recv())
  862. except Exception:
  863. self.__conn()
  864. raise Exception("RPC connection lost!")
  865. return do_rpc
  866. def __init__(self, key, model_name):
  867. super().__init__(key, model_name, base_url=None)
  868. from jina import Client
  869. self.client = Client(port=12345, protocol="grpc", asyncio=True)
  870. def _prepare_prompt(self, system, history, gen_conf):
  871. from rag.svr.jina_server import Prompt
  872. if system:
  873. history.insert(0, {"role": "system", "content": system})
  874. return Prompt(message=history, gen_conf=gen_conf)
  875. def _stream_response(self, endpoint, prompt):
  876. from rag.svr.jina_server import Generation
  877. answer = ""
  878. try:
  879. res = self.client.stream_doc(on=endpoint, inputs=prompt, return_type=Generation)
  880. loop = asyncio.get_event_loop()
  881. try:
  882. while True:
  883. answer = loop.run_until_complete(res.__anext__()).text
  884. yield answer
  885. except StopAsyncIteration:
  886. pass
  887. except Exception as e:
  888. yield answer + "\n**ERROR**: " + str(e)
  889. yield num_tokens_from_string(answer)
  890. def chat(self, system, history, gen_conf):
  891. if "max_tokens" in gen_conf:
  892. del gen_conf["max_tokens"]
  893. prompt = self._prepare_prompt(system, history, gen_conf)
  894. chat_gen = self._stream_response("/chat", prompt)
  895. ans = next(chat_gen)
  896. total_tokens = next(chat_gen)
  897. return ans, total_tokens
  898. def chat_streamly(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. return self._stream_response("/stream", prompt)
  903. class VolcEngineChat(Base):
  904. def __init__(self, key, model_name, base_url="https://ark.cn-beijing.volces.com/api/v3"):
  905. super().__init__(key, model_name, base_url=None)
  906. """
  907. Since do not want to modify the original database fields, and the VolcEngine authentication method is quite special,
  908. Assemble ark_api_key, ep_id into api_key, store it as a dictionary type, and parse it for use
  909. model_name is for display only
  910. """
  911. base_url = base_url if base_url else "https://ark.cn-beijing.volces.com/api/v3"
  912. ark_api_key = json.loads(key).get("ark_api_key", "")
  913. model_name = json.loads(key).get("ep_id", "") + json.loads(key).get("endpoint_id", "")
  914. super().__init__(ark_api_key, model_name, base_url)
  915. class MiniMaxChat(Base):
  916. def __init__(
  917. self,
  918. key,
  919. model_name,
  920. base_url="https://api.minimax.chat/v1/text/chatcompletion_v2",
  921. ):
  922. super().__init__(key, model_name, base_url=None)
  923. if not base_url:
  924. base_url = "https://api.minimax.chat/v1/text/chatcompletion_v2"
  925. self.base_url = base_url
  926. self.model_name = model_name
  927. self.api_key = key
  928. def chat(self, system, history, gen_conf):
  929. if system:
  930. history.insert(0, {"role": "system", "content": system})
  931. for k in list(gen_conf.keys()):
  932. if k not in ["temperature", "top_p", "max_tokens"]:
  933. del gen_conf[k]
  934. headers = {
  935. "Authorization": f"Bearer {self.api_key}",
  936. "Content-Type": "application/json",
  937. }
  938. payload = json.dumps({"model": self.model_name, "messages": history, **gen_conf})
  939. try:
  940. response = requests.request("POST", url=self.base_url, headers=headers, data=payload)
  941. response = response.json()
  942. ans = response["choices"][0]["message"]["content"].strip()
  943. if response["choices"][0]["finish_reason"] == "length":
  944. if is_chinese(ans):
  945. ans += LENGTH_NOTIFICATION_CN
  946. else:
  947. ans += LENGTH_NOTIFICATION_EN
  948. return ans, self.total_token_count(response)
  949. except Exception as e:
  950. return "**ERROR**: " + str(e), 0
  951. def chat_streamly(self, system, history, gen_conf):
  952. if system:
  953. history.insert(0, {"role": "system", "content": system})
  954. for k in list(gen_conf.keys()):
  955. if k not in ["temperature", "top_p", "max_tokens"]:
  956. del gen_conf[k]
  957. ans = ""
  958. total_tokens = 0
  959. try:
  960. headers = {
  961. "Authorization": f"Bearer {self.api_key}",
  962. "Content-Type": "application/json",
  963. }
  964. payload = json.dumps(
  965. {
  966. "model": self.model_name,
  967. "messages": history,
  968. "stream": True,
  969. **gen_conf,
  970. }
  971. )
  972. response = requests.request(
  973. "POST",
  974. url=self.base_url,
  975. headers=headers,
  976. data=payload,
  977. )
  978. for resp in response.text.split("\n\n")[:-1]:
  979. resp = json.loads(resp[6:])
  980. text = ""
  981. if "choices" in resp and "delta" in resp["choices"][0]:
  982. text = resp["choices"][0]["delta"]["content"]
  983. ans = text
  984. tol = self.total_token_count(resp)
  985. if not tol:
  986. total_tokens += num_tokens_from_string(text)
  987. else:
  988. total_tokens = tol
  989. yield ans
  990. except Exception as e:
  991. yield ans + "\n**ERROR**: " + str(e)
  992. yield total_tokens
  993. class MistralChat(Base):
  994. def __init__(self, key, model_name, base_url=None):
  995. super().__init__(key, model_name, base_url=None)
  996. from mistralai.client import MistralClient
  997. self.client = MistralClient(api_key=key)
  998. self.model_name = model_name
  999. def chat(self, system, history, gen_conf):
  1000. if system:
  1001. history.insert(0, {"role": "system", "content": system})
  1002. for k in list(gen_conf.keys()):
  1003. if k not in ["temperature", "top_p", "max_tokens"]:
  1004. del gen_conf[k]
  1005. try:
  1006. response = self.client.chat(model=self.model_name, messages=history, **gen_conf)
  1007. ans = response.choices[0].message.content
  1008. if response.choices[0].finish_reason == "length":
  1009. if is_chinese(ans):
  1010. ans += LENGTH_NOTIFICATION_CN
  1011. else:
  1012. ans += LENGTH_NOTIFICATION_EN
  1013. return ans, self.total_token_count(response)
  1014. except openai.APIError as e:
  1015. return "**ERROR**: " + str(e), 0
  1016. def chat_streamly(self, system, history, gen_conf):
  1017. if system:
  1018. history.insert(0, {"role": "system", "content": system})
  1019. for k in list(gen_conf.keys()):
  1020. if k not in ["temperature", "top_p", "max_tokens"]:
  1021. del gen_conf[k]
  1022. ans = ""
  1023. total_tokens = 0
  1024. try:
  1025. response = self.client.chat_stream(model=self.model_name, messages=history, **gen_conf)
  1026. for resp in response:
  1027. if not resp.choices or not resp.choices[0].delta.content:
  1028. continue
  1029. ans = resp.choices[0].delta.content
  1030. total_tokens += 1
  1031. if resp.choices[0].finish_reason == "length":
  1032. if is_chinese(ans):
  1033. ans += LENGTH_NOTIFICATION_CN
  1034. else:
  1035. ans += LENGTH_NOTIFICATION_EN
  1036. yield ans
  1037. except openai.APIError as e:
  1038. yield ans + "\n**ERROR**: " + str(e)
  1039. yield total_tokens
  1040. class BedrockChat(Base):
  1041. def __init__(self, key, model_name, **kwargs):
  1042. super().__init__(key, model_name, base_url=None)
  1043. import boto3
  1044. self.bedrock_ak = json.loads(key).get("bedrock_ak", "")
  1045. self.bedrock_sk = json.loads(key).get("bedrock_sk", "")
  1046. self.bedrock_region = json.loads(key).get("bedrock_region", "")
  1047. self.model_name = model_name
  1048. if self.bedrock_ak == "" or self.bedrock_sk == "" or self.bedrock_region == "":
  1049. # Try to create a client using the default credentials (AWS_PROFILE, AWS_DEFAULT_REGION, etc.)
  1050. self.client = boto3.client("bedrock-runtime")
  1051. else:
  1052. 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)
  1053. def chat(self, system, history, gen_conf):
  1054. from botocore.exceptions import ClientError
  1055. for k in list(gen_conf.keys()):
  1056. if k not in ["temperature"]:
  1057. del gen_conf[k]
  1058. for item in history:
  1059. if not isinstance(item["content"], list) and not isinstance(item["content"], tuple):
  1060. item["content"] = [{"text": item["content"]}]
  1061. try:
  1062. # Send the message to the model, using a basic inference configuration.
  1063. response = self.client.converse(
  1064. modelId=self.model_name,
  1065. messages=history,
  1066. inferenceConfig=gen_conf,
  1067. system=[{"text": (system if system else "Answer the user's message.")}],
  1068. )
  1069. # Extract and print the response text.
  1070. ans = response["output"]["message"]["content"][0]["text"]
  1071. return ans, num_tokens_from_string(ans)
  1072. except (ClientError, Exception) as e:
  1073. return f"ERROR: Can't invoke '{self.model_name}'. Reason: {e}", 0
  1074. def chat_streamly(self, system, history, gen_conf):
  1075. from botocore.exceptions import ClientError
  1076. for k in list(gen_conf.keys()):
  1077. if k not in ["temperature"]:
  1078. del gen_conf[k]
  1079. for item in history:
  1080. if not isinstance(item["content"], list) and not isinstance(item["content"], tuple):
  1081. item["content"] = [{"text": item["content"]}]
  1082. if self.model_name.split(".")[0] == "ai21":
  1083. try:
  1084. response = self.client.converse(modelId=self.model_name, messages=history, inferenceConfig=gen_conf, system=[{"text": (system if system else "Answer the user's message.")}])
  1085. ans = response["output"]["message"]["content"][0]["text"]
  1086. return ans, num_tokens_from_string(ans)
  1087. except (ClientError, Exception) as e:
  1088. return f"ERROR: Can't invoke '{self.model_name}'. Reason: {e}", 0
  1089. ans = ""
  1090. try:
  1091. # Send the message to the model, using a basic inference configuration.
  1092. streaming_response = self.client.converse_stream(
  1093. modelId=self.model_name, messages=history, inferenceConfig=gen_conf, system=[{"text": (system if system else "Answer the user's message.")}]
  1094. )
  1095. # Extract and print the streamed response text in real-time.
  1096. for resp in streaming_response["stream"]:
  1097. if "contentBlockDelta" in resp:
  1098. ans = resp["contentBlockDelta"]["delta"]["text"]
  1099. yield ans
  1100. except (ClientError, Exception) as e:
  1101. yield ans + f"ERROR: Can't invoke '{self.model_name}'. Reason: {e}"
  1102. yield num_tokens_from_string(ans)
  1103. class GeminiChat(Base):
  1104. def __init__(self, key, model_name, base_url=None):
  1105. super().__init__(key, model_name, base_url=None)
  1106. from google.generativeai import GenerativeModel, client
  1107. client.configure(api_key=key)
  1108. _client = client.get_default_generative_client()
  1109. self.model_name = "models/" + model_name
  1110. self.model = GenerativeModel(model_name=self.model_name)
  1111. self.model._client = _client
  1112. def chat(self, system, history, gen_conf):
  1113. from google.generativeai.types import content_types
  1114. if system:
  1115. self.model._system_instruction = content_types.to_content(system)
  1116. for k in list(gen_conf.keys()):
  1117. if k not in ["temperature", "top_p", "max_tokens"]:
  1118. del gen_conf[k]
  1119. for item in history:
  1120. if "role" in item and item["role"] == "assistant":
  1121. item["role"] = "model"
  1122. if "role" in item and item["role"] == "system":
  1123. item["role"] = "user"
  1124. if "content" in item:
  1125. item["parts"] = item.pop("content")
  1126. try:
  1127. response = self.model.generate_content(history, generation_config=gen_conf)
  1128. ans = response.text
  1129. return ans, response.usage_metadata.total_token_count
  1130. except Exception as e:
  1131. return "**ERROR**: " + str(e), 0
  1132. def chat_streamly(self, system, history, gen_conf):
  1133. from google.generativeai.types import content_types
  1134. if system:
  1135. self.model._system_instruction = content_types.to_content(system)
  1136. for k in list(gen_conf.keys()):
  1137. if k not in ["temperature", "top_p", "max_tokens"]:
  1138. del gen_conf[k]
  1139. for item in history:
  1140. if "role" in item and item["role"] == "assistant":
  1141. item["role"] = "model"
  1142. if "content" in item:
  1143. item["parts"] = item.pop("content")
  1144. ans = ""
  1145. try:
  1146. response = self.model.generate_content(history, generation_config=gen_conf, stream=True)
  1147. for resp in response:
  1148. ans = resp.text
  1149. yield ans
  1150. yield response._chunks[-1].usage_metadata.total_token_count
  1151. except Exception as e:
  1152. yield ans + "\n**ERROR**: " + str(e)
  1153. yield 0
  1154. class GroqChat(Base):
  1155. def __init__(self, key, model_name, base_url=""):
  1156. super().__init__(key, model_name, base_url=None)
  1157. from groq import Groq
  1158. self.client = Groq(api_key=key)
  1159. self.model_name = model_name
  1160. def chat(self, system, history, gen_conf):
  1161. if system:
  1162. history.insert(0, {"role": "system", "content": system})
  1163. for k in list(gen_conf.keys()):
  1164. if k not in ["temperature", "top_p", "max_tokens"]:
  1165. del gen_conf[k]
  1166. ans = ""
  1167. try:
  1168. response = self.client.chat.completions.create(model=self.model_name, messages=history, **gen_conf)
  1169. ans = response.choices[0].message.content
  1170. if response.choices[0].finish_reason == "length":
  1171. if is_chinese(ans):
  1172. ans += LENGTH_NOTIFICATION_CN
  1173. else:
  1174. ans += LENGTH_NOTIFICATION_EN
  1175. return ans, self.total_token_count(response)
  1176. except Exception as e:
  1177. return ans + "\n**ERROR**: " + str(e), 0
  1178. def chat_streamly(self, system, history, gen_conf):
  1179. if system:
  1180. history.insert(0, {"role": "system", "content": system})
  1181. for k in list(gen_conf.keys()):
  1182. if k not in ["temperature", "top_p", "max_tokens"]:
  1183. del gen_conf[k]
  1184. ans = ""
  1185. total_tokens = 0
  1186. try:
  1187. response = self.client.chat.completions.create(model=self.model_name, messages=history, stream=True, **gen_conf)
  1188. for resp in response:
  1189. if not resp.choices or not resp.choices[0].delta.content:
  1190. continue
  1191. ans = resp.choices[0].delta.content
  1192. total_tokens += 1
  1193. if resp.choices[0].finish_reason == "length":
  1194. if is_chinese(ans):
  1195. ans += LENGTH_NOTIFICATION_CN
  1196. else:
  1197. ans += LENGTH_NOTIFICATION_EN
  1198. yield ans
  1199. except Exception as e:
  1200. yield ans + "\n**ERROR**: " + str(e)
  1201. yield total_tokens
  1202. ## openrouter
  1203. class OpenRouterChat(Base):
  1204. def __init__(self, key, model_name, base_url="https://openrouter.ai/api/v1"):
  1205. if not base_url:
  1206. base_url = "https://openrouter.ai/api/v1"
  1207. super().__init__(key, model_name, base_url)
  1208. class StepFunChat(Base):
  1209. def __init__(self, key, model_name, base_url="https://api.stepfun.com/v1"):
  1210. if not base_url:
  1211. base_url = "https://api.stepfun.com/v1"
  1212. super().__init__(key, model_name, base_url)
  1213. class NvidiaChat(Base):
  1214. def __init__(self, key, model_name, base_url="https://integrate.api.nvidia.com/v1"):
  1215. if not base_url:
  1216. base_url = "https://integrate.api.nvidia.com/v1"
  1217. super().__init__(key, model_name, base_url)
  1218. class LmStudioChat(Base):
  1219. def __init__(self, key, model_name, base_url):
  1220. if not base_url:
  1221. raise ValueError("Local llm url cannot be None")
  1222. if base_url.split("/")[-1] != "v1":
  1223. base_url = os.path.join(base_url, "v1")
  1224. super().__init__(key, model_name, base_url)
  1225. self.client = OpenAI(api_key="lm-studio", base_url=base_url)
  1226. self.model_name = model_name
  1227. class OpenAI_APIChat(Base):
  1228. def __init__(self, key, model_name, base_url):
  1229. if not base_url:
  1230. raise ValueError("url cannot be None")
  1231. model_name = model_name.split("___")[0]
  1232. super().__init__(key, model_name, base_url)
  1233. class PPIOChat(Base):
  1234. def __init__(self, key, model_name, base_url="https://api.ppinfra.com/v3/openai"):
  1235. if not base_url:
  1236. base_url = "https://api.ppinfra.com/v3/openai"
  1237. super().__init__(key, model_name, base_url)
  1238. class CoHereChat(Base):
  1239. def __init__(self, key, model_name, base_url=""):
  1240. super().__init__(key, model_name, base_url=None)
  1241. from cohere import Client
  1242. self.client = Client(api_key=key)
  1243. self.model_name = model_name
  1244. def chat(self, system, history, gen_conf):
  1245. if system:
  1246. history.insert(0, {"role": "system", "content": system})
  1247. if "max_tokens" in gen_conf:
  1248. del gen_conf["max_tokens"]
  1249. if "top_p" in gen_conf:
  1250. gen_conf["p"] = gen_conf.pop("top_p")
  1251. if "frequency_penalty" in gen_conf and "presence_penalty" in gen_conf:
  1252. gen_conf.pop("presence_penalty")
  1253. for item in history:
  1254. if "role" in item and item["role"] == "user":
  1255. item["role"] = "USER"
  1256. if "role" in item and item["role"] == "assistant":
  1257. item["role"] = "CHATBOT"
  1258. if "content" in item:
  1259. item["message"] = item.pop("content")
  1260. mes = history.pop()["message"]
  1261. ans = ""
  1262. try:
  1263. response = self.client.chat(model=self.model_name, chat_history=history, message=mes, **gen_conf)
  1264. ans = response.text
  1265. if response.finish_reason == "MAX_TOKENS":
  1266. ans += "...\nFor the content length reason, it stopped, continue?" if is_english([ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  1267. return (
  1268. ans,
  1269. response.meta.tokens.input_tokens + response.meta.tokens.output_tokens,
  1270. )
  1271. except Exception as e:
  1272. return ans + "\n**ERROR**: " + str(e), 0
  1273. def chat_streamly(self, system, history, gen_conf):
  1274. if system:
  1275. history.insert(0, {"role": "system", "content": system})
  1276. if "max_tokens" in gen_conf:
  1277. del gen_conf["max_tokens"]
  1278. if "top_p" in gen_conf:
  1279. gen_conf["p"] = gen_conf.pop("top_p")
  1280. if "frequency_penalty" in gen_conf and "presence_penalty" in gen_conf:
  1281. gen_conf.pop("presence_penalty")
  1282. for item in history:
  1283. if "role" in item and item["role"] == "user":
  1284. item["role"] = "USER"
  1285. if "role" in item and item["role"] == "assistant":
  1286. item["role"] = "CHATBOT"
  1287. if "content" in item:
  1288. item["message"] = item.pop("content")
  1289. mes = history.pop()["message"]
  1290. ans = ""
  1291. total_tokens = 0
  1292. try:
  1293. response = self.client.chat_stream(model=self.model_name, chat_history=history, message=mes, **gen_conf)
  1294. for resp in response:
  1295. if resp.event_type == "text-generation":
  1296. ans = resp.text
  1297. total_tokens += num_tokens_from_string(resp.text)
  1298. elif resp.event_type == "stream-end":
  1299. if resp.finish_reason == "MAX_TOKENS":
  1300. ans += "...\nFor the content length reason, it stopped, continue?" if is_english([ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  1301. yield ans
  1302. except Exception as e:
  1303. yield ans + "\n**ERROR**: " + str(e)
  1304. yield total_tokens
  1305. class LeptonAIChat(Base):
  1306. def __init__(self, key, model_name, base_url=None):
  1307. if not base_url:
  1308. base_url = os.path.join("https://" + model_name + ".lepton.run", "api", "v1")
  1309. super().__init__(key, model_name, base_url)
  1310. class TogetherAIChat(Base):
  1311. def __init__(self, key, model_name, base_url="https://api.together.xyz/v1"):
  1312. if not base_url:
  1313. base_url = "https://api.together.xyz/v1"
  1314. super().__init__(key, model_name, base_url)
  1315. class PerfXCloudChat(Base):
  1316. def __init__(self, key, model_name, base_url="https://cloud.perfxlab.cn/v1"):
  1317. if not base_url:
  1318. base_url = "https://cloud.perfxlab.cn/v1"
  1319. super().__init__(key, model_name, base_url)
  1320. class UpstageChat(Base):
  1321. def __init__(self, key, model_name, base_url="https://api.upstage.ai/v1/solar"):
  1322. if not base_url:
  1323. base_url = "https://api.upstage.ai/v1/solar"
  1324. super().__init__(key, model_name, base_url)
  1325. class NovitaAIChat(Base):
  1326. def __init__(self, key, model_name, base_url="https://api.novita.ai/v3/openai"):
  1327. if not base_url:
  1328. base_url = "https://api.novita.ai/v3/openai"
  1329. super().__init__(key, model_name, base_url)
  1330. class SILICONFLOWChat(Base):
  1331. def __init__(self, key, model_name, base_url="https://api.siliconflow.cn/v1"):
  1332. if not base_url:
  1333. base_url = "https://api.siliconflow.cn/v1"
  1334. super().__init__(key, model_name, base_url)
  1335. class YiChat(Base):
  1336. def __init__(self, key, model_name, base_url="https://api.lingyiwanwu.com/v1"):
  1337. if not base_url:
  1338. base_url = "https://api.lingyiwanwu.com/v1"
  1339. super().__init__(key, model_name, base_url)
  1340. class ReplicateChat(Base):
  1341. def __init__(self, key, model_name, base_url=None):
  1342. super().__init__(key, model_name, base_url=None)
  1343. from replicate.client import Client
  1344. self.model_name = model_name
  1345. self.client = Client(api_token=key)
  1346. self.system = ""
  1347. def chat(self, system, history, gen_conf):
  1348. if "max_tokens" in gen_conf:
  1349. del gen_conf["max_tokens"]
  1350. if system:
  1351. self.system = system
  1352. prompt = "\n".join([item["role"] + ":" + item["content"] for item in history[-5:]])
  1353. ans = ""
  1354. try:
  1355. response = self.client.run(
  1356. self.model_name,
  1357. input={"system_prompt": self.system, "prompt": prompt, **gen_conf},
  1358. )
  1359. ans = "".join(response)
  1360. return ans, num_tokens_from_string(ans)
  1361. except Exception as e:
  1362. return ans + "\n**ERROR**: " + str(e), 0
  1363. def chat_streamly(self, system, history, gen_conf):
  1364. if "max_tokens" in gen_conf:
  1365. del gen_conf["max_tokens"]
  1366. if system:
  1367. self.system = system
  1368. prompt = "\n".join([item["role"] + ":" + item["content"] for item in history[-5:]])
  1369. ans = ""
  1370. try:
  1371. response = self.client.run(
  1372. self.model_name,
  1373. input={"system_prompt": self.system, "prompt": prompt, **gen_conf},
  1374. )
  1375. for resp in response:
  1376. ans = resp
  1377. yield ans
  1378. except Exception as e:
  1379. yield ans + "\n**ERROR**: " + str(e)
  1380. yield num_tokens_from_string(ans)
  1381. class HunyuanChat(Base):
  1382. def __init__(self, key, model_name, base_url=None):
  1383. super().__init__(key, model_name, base_url=None)
  1384. from tencentcloud.common import credential
  1385. from tencentcloud.hunyuan.v20230901 import hunyuan_client
  1386. key = json.loads(key)
  1387. sid = key.get("hunyuan_sid", "")
  1388. sk = key.get("hunyuan_sk", "")
  1389. cred = credential.Credential(sid, sk)
  1390. self.model_name = model_name
  1391. self.client = hunyuan_client.HunyuanClient(cred, "")
  1392. def chat(self, system, history, gen_conf):
  1393. from tencentcloud.common.exception.tencent_cloud_sdk_exception import (
  1394. TencentCloudSDKException,
  1395. )
  1396. from tencentcloud.hunyuan.v20230901 import models
  1397. _gen_conf = {}
  1398. _history = [{k.capitalize(): v for k, v in item.items()} for item in history]
  1399. if system:
  1400. _history.insert(0, {"Role": "system", "Content": system})
  1401. if "max_tokens" in gen_conf:
  1402. del gen_conf["max_tokens"]
  1403. if "temperature" in gen_conf:
  1404. _gen_conf["Temperature"] = gen_conf["temperature"]
  1405. if "top_p" in gen_conf:
  1406. _gen_conf["TopP"] = gen_conf["top_p"]
  1407. req = models.ChatCompletionsRequest()
  1408. params = {"Model": self.model_name, "Messages": _history, **_gen_conf}
  1409. req.from_json_string(json.dumps(params))
  1410. ans = ""
  1411. try:
  1412. response = self.client.ChatCompletions(req)
  1413. ans = response.Choices[0].Message.Content
  1414. return ans, response.Usage.TotalTokens
  1415. except TencentCloudSDKException as e:
  1416. return ans + "\n**ERROR**: " + str(e), 0
  1417. def chat_streamly(self, system, history, gen_conf):
  1418. from tencentcloud.common.exception.tencent_cloud_sdk_exception import (
  1419. TencentCloudSDKException,
  1420. )
  1421. from tencentcloud.hunyuan.v20230901 import models
  1422. _gen_conf = {}
  1423. _history = [{k.capitalize(): v for k, v in item.items()} for item in history]
  1424. if system:
  1425. _history.insert(0, {"Role": "system", "Content": system})
  1426. if "max_tokens" in gen_conf:
  1427. del gen_conf["max_tokens"]
  1428. if "temperature" in gen_conf:
  1429. _gen_conf["Temperature"] = gen_conf["temperature"]
  1430. if "top_p" in gen_conf:
  1431. _gen_conf["TopP"] = gen_conf["top_p"]
  1432. req = models.ChatCompletionsRequest()
  1433. params = {
  1434. "Model": self.model_name,
  1435. "Messages": _history,
  1436. "Stream": True,
  1437. **_gen_conf,
  1438. }
  1439. req.from_json_string(json.dumps(params))
  1440. ans = ""
  1441. total_tokens = 0
  1442. try:
  1443. response = self.client.ChatCompletions(req)
  1444. for resp in response:
  1445. resp = json.loads(resp["data"])
  1446. if not resp["Choices"] or not resp["Choices"][0]["Delta"]["Content"]:
  1447. continue
  1448. ans = resp["Choices"][0]["Delta"]["Content"]
  1449. total_tokens += 1
  1450. yield ans
  1451. except TencentCloudSDKException as e:
  1452. yield ans + "\n**ERROR**: " + str(e)
  1453. yield total_tokens
  1454. class SparkChat(Base):
  1455. def __init__(self, key, model_name, base_url="https://spark-api-open.xf-yun.com/v1"):
  1456. if not base_url:
  1457. base_url = "https://spark-api-open.xf-yun.com/v1"
  1458. model2version = {
  1459. "Spark-Max": "generalv3.5",
  1460. "Spark-Lite": "general",
  1461. "Spark-Pro": "generalv3",
  1462. "Spark-Pro-128K": "pro-128k",
  1463. "Spark-4.0-Ultra": "4.0Ultra",
  1464. }
  1465. version2model = {v: k for k, v in model2version.items()}
  1466. assert model_name in model2version or model_name in version2model, f"The given model name is not supported yet. Support: {list(model2version.keys())}"
  1467. if model_name in model2version:
  1468. model_version = model2version[model_name]
  1469. else:
  1470. model_version = model_name
  1471. super().__init__(key, model_version, base_url)
  1472. class BaiduYiyanChat(Base):
  1473. def __init__(self, key, model_name, base_url=None):
  1474. super().__init__(key, model_name, base_url=None)
  1475. import qianfan
  1476. key = json.loads(key)
  1477. ak = key.get("yiyan_ak", "")
  1478. sk = key.get("yiyan_sk", "")
  1479. self.client = qianfan.ChatCompletion(ak=ak, sk=sk)
  1480. self.model_name = model_name.lower()
  1481. self.system = ""
  1482. def chat(self, system, history, gen_conf):
  1483. if system:
  1484. self.system = system
  1485. gen_conf["penalty_score"] = ((gen_conf.get("presence_penalty", 0) + gen_conf.get("frequency_penalty", 0)) / 2) + 1
  1486. if "max_tokens" in gen_conf:
  1487. del gen_conf["max_tokens"]
  1488. ans = ""
  1489. try:
  1490. response = self.client.do(model=self.model_name, messages=history, system=self.system, **gen_conf).body
  1491. ans = response["result"]
  1492. return ans, self.total_token_count(response)
  1493. except Exception as e:
  1494. return ans + "\n**ERROR**: " + str(e), 0
  1495. def chat_streamly(self, system, history, gen_conf):
  1496. if system:
  1497. self.system = system
  1498. gen_conf["penalty_score"] = ((gen_conf.get("presence_penalty", 0) + gen_conf.get("frequency_penalty", 0)) / 2) + 1
  1499. if "max_tokens" in gen_conf:
  1500. del gen_conf["max_tokens"]
  1501. ans = ""
  1502. total_tokens = 0
  1503. try:
  1504. response = self.client.do(model=self.model_name, messages=history, system=self.system, stream=True, **gen_conf)
  1505. for resp in response:
  1506. resp = resp.body
  1507. ans = resp["result"]
  1508. total_tokens = self.total_token_count(resp)
  1509. yield ans
  1510. except Exception as e:
  1511. return ans + "\n**ERROR**: " + str(e), 0
  1512. yield total_tokens
  1513. class AnthropicChat(Base):
  1514. def __init__(self, key, model_name, base_url=None):
  1515. super().__init__(key, model_name, base_url=None)
  1516. import anthropic
  1517. self.client = anthropic.Anthropic(api_key=key)
  1518. self.model_name = model_name
  1519. self.system = ""
  1520. def chat(self, system, history, gen_conf):
  1521. if system:
  1522. self.system = system
  1523. if "presence_penalty" in gen_conf:
  1524. del gen_conf["presence_penalty"]
  1525. if "frequency_penalty" in gen_conf:
  1526. del gen_conf["frequency_penalty"]
  1527. gen_conf["max_tokens"] = 8192
  1528. if "haiku" in self.model_name or "opus" in self.model_name:
  1529. gen_conf["max_tokens"] = 4096
  1530. ans = ""
  1531. try:
  1532. response = self.client.messages.create(
  1533. model=self.model_name,
  1534. messages=history,
  1535. system=self.system,
  1536. stream=False,
  1537. **gen_conf,
  1538. ).to_dict()
  1539. ans = response["content"][0]["text"]
  1540. if response["stop_reason"] == "max_tokens":
  1541. ans += "...\nFor the content length reason, it stopped, continue?" if is_english([ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  1542. return (
  1543. ans,
  1544. response["usage"]["input_tokens"] + response["usage"]["output_tokens"],
  1545. )
  1546. except Exception as e:
  1547. return ans + "\n**ERROR**: " + str(e), 0
  1548. def chat_streamly(self, system, history, gen_conf):
  1549. if system:
  1550. self.system = system
  1551. if "presence_penalty" in gen_conf:
  1552. del gen_conf["presence_penalty"]
  1553. if "frequency_penalty" in gen_conf:
  1554. del gen_conf["frequency_penalty"]
  1555. gen_conf["max_tokens"] = 8192
  1556. if "haiku" in self.model_name or "opus" in self.model_name:
  1557. gen_conf["max_tokens"] = 4096
  1558. ans = ""
  1559. total_tokens = 0
  1560. reasoning_start = False
  1561. try:
  1562. response = self.client.messages.create(
  1563. model=self.model_name,
  1564. messages=history,
  1565. system=system,
  1566. stream=True,
  1567. **gen_conf,
  1568. )
  1569. for res in response:
  1570. if res.type == "content_block_delta":
  1571. if res.delta.type == "thinking_delta" and res.delta.thinking:
  1572. ans = ""
  1573. if not reasoning_start:
  1574. reasoning_start = True
  1575. ans = "<think>"
  1576. ans += res.delta.thinking + "</think>"
  1577. else:
  1578. reasoning_start = False
  1579. text = res.delta.text
  1580. ans = text
  1581. total_tokens += num_tokens_from_string(text)
  1582. yield ans
  1583. except Exception as e:
  1584. yield ans + "\n**ERROR**: " + str(e)
  1585. yield total_tokens
  1586. class GoogleChat(Base):
  1587. def __init__(self, key, model_name, base_url=None):
  1588. super().__init__(key, model_name, base_url=None)
  1589. import base64
  1590. from google.oauth2 import service_account
  1591. key = json.loads(key)
  1592. access_token = json.loads(base64.b64decode(key.get("google_service_account_key", "")))
  1593. project_id = key.get("google_project_id", "")
  1594. region = key.get("google_region", "")
  1595. scopes = ["https://www.googleapis.com/auth/cloud-platform"]
  1596. self.model_name = model_name
  1597. self.system = ""
  1598. if "claude" in self.model_name:
  1599. from anthropic import AnthropicVertex
  1600. from google.auth.transport.requests import Request
  1601. if access_token:
  1602. credits = service_account.Credentials.from_service_account_info(access_token, scopes=scopes)
  1603. request = Request()
  1604. credits.refresh(request)
  1605. token = credits.token
  1606. self.client = AnthropicVertex(region=region, project_id=project_id, access_token=token)
  1607. else:
  1608. self.client = AnthropicVertex(region=region, project_id=project_id)
  1609. else:
  1610. import vertexai.generative_models as glm
  1611. from google.cloud import aiplatform
  1612. if access_token:
  1613. credits = service_account.Credentials.from_service_account_info(access_token)
  1614. aiplatform.init(credentials=credits, project=project_id, location=region)
  1615. else:
  1616. aiplatform.init(project=project_id, location=region)
  1617. self.client = glm.GenerativeModel(model_name=self.model_name)
  1618. def chat(self, system, history, gen_conf):
  1619. if system:
  1620. self.system = system
  1621. if "claude" in self.model_name:
  1622. if "max_tokens" in gen_conf:
  1623. del gen_conf["max_tokens"]
  1624. try:
  1625. response = self.client.messages.create(
  1626. model=self.model_name,
  1627. messages=history,
  1628. system=self.system,
  1629. stream=False,
  1630. **gen_conf,
  1631. ).json()
  1632. ans = response["content"][0]["text"]
  1633. if response["stop_reason"] == "max_tokens":
  1634. ans += "...\nFor the content length reason, it stopped, continue?" if is_english([ans]) else "······\n由于长度的原因,回答被截断了,要继续吗?"
  1635. return (
  1636. ans,
  1637. response["usage"]["input_tokens"] + response["usage"]["output_tokens"],
  1638. )
  1639. except Exception as e:
  1640. return "\n**ERROR**: " + str(e), 0
  1641. else:
  1642. self.client._system_instruction = self.system
  1643. if "max_tokens" in gen_conf:
  1644. gen_conf["max_output_tokens"] = gen_conf["max_tokens"]
  1645. for k in list(gen_conf.keys()):
  1646. if k not in ["temperature", "top_p", "max_output_tokens"]:
  1647. del gen_conf[k]
  1648. for item in history:
  1649. if "role" in item and item["role"] == "assistant":
  1650. item["role"] = "model"
  1651. if "content" in item:
  1652. item["parts"] = item.pop("content")
  1653. try:
  1654. response = self.client.generate_content(history, generation_config=gen_conf)
  1655. ans = response.text
  1656. return ans, response.usage_metadata.total_token_count
  1657. except Exception as e:
  1658. return "**ERROR**: " + str(e), 0
  1659. def chat_streamly(self, system, history, gen_conf):
  1660. if system:
  1661. self.system = system
  1662. if "claude" in self.model_name:
  1663. if "max_tokens" in gen_conf:
  1664. del gen_conf["max_tokens"]
  1665. ans = ""
  1666. total_tokens = 0
  1667. try:
  1668. response = self.client.messages.create(
  1669. model=self.model_name,
  1670. messages=history,
  1671. system=self.system,
  1672. stream=True,
  1673. **gen_conf,
  1674. )
  1675. for res in response.iter_lines():
  1676. res = res.decode("utf-8")
  1677. if "content_block_delta" in res and "data" in res:
  1678. text = json.loads(res[6:])["delta"]["text"]
  1679. ans = text
  1680. total_tokens += num_tokens_from_string(text)
  1681. except Exception as e:
  1682. yield ans + "\n**ERROR**: " + str(e)
  1683. yield total_tokens
  1684. else:
  1685. self.client._system_instruction = self.system
  1686. if "max_tokens" in gen_conf:
  1687. gen_conf["max_output_tokens"] = gen_conf["max_tokens"]
  1688. for k in list(gen_conf.keys()):
  1689. if k not in ["temperature", "top_p", "max_output_tokens"]:
  1690. del gen_conf[k]
  1691. for item in history:
  1692. if "role" in item and item["role"] == "assistant":
  1693. item["role"] = "model"
  1694. if "content" in item:
  1695. item["parts"] = item.pop("content")
  1696. ans = ""
  1697. try:
  1698. response = self.model.generate_content(history, generation_config=gen_conf, stream=True)
  1699. for resp in response:
  1700. ans = resp.text
  1701. yield ans
  1702. except Exception as e:
  1703. yield ans + "\n**ERROR**: " + str(e)
  1704. yield response._chunks[-1].usage_metadata.total_token_count
  1705. class GPUStackChat(Base):
  1706. def __init__(self, key=None, model_name="", base_url=""):
  1707. if not base_url:
  1708. raise ValueError("Local llm url cannot be None")
  1709. if base_url.split("/")[-1] != "v1":
  1710. base_url = os.path.join(base_url, "v1")
  1711. super().__init__(key, model_name, base_url)