1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
| import os import json from dataclasses import dataclass
from openai import OpenAI from volcenginesdkarkruntime import Ark from zhipuai import ZhipuAI from dotenv import load_dotenv
from model import FinishReason
load_dotenv()
@dataclass class LLMBase:
client = None default_model = None
def chat_completions(self, chat_messages): if 'model' not in chat_messages: chat_messages['model'] = self.default_model
response = self.client.chat.completions.create(**chat_messages) return response
async def handle_completions(self, client_session, response, chat_messages): """非流式会话响应处理 """ choice = response.choices[0] finish_reason = choice.finish_reason if finish_reason == FinishReason.STOP: return response
if finish_reason == FinishReason.TOOL_CALLS:
tool_calls_message_info = choice.message if isinstance(self, (LLMHuoShan, LLMZhipu)): tool_calls_message_info = choice.message.dict()
chat_messages.get('messages').extend([ tool_calls_message_info ])
tool_calls = choice.message.tool_calls for tool in tool_calls: tool_info = { "role": 'tool', "tool_call_id": tool.id }
tool_name = tool.function.name tool_args = json.loads(tool.function.arguments) if tool.function.arguments else {}
resp = await client_session.call_tool(tool_name, tool_args) func_call_content = resp.content[0] if resp and resp.content else None if func_call_content: text_data = json.loads(func_call_content.text) call_result = text_data.get('data', None) call_result = json.dumps(call_result) if call_result else '' else: call_result = None tool_info['content'] = call_result
chat_messages.get('messages').extend([ tool_info ])
return chat_messages
return response
async def handle_completions_stream(self, client_session, response, chat_messages): if isinstance(self, (LLMDeepseek, LLMAliYun, LLMOpenAI)): async for result in self.handle_completions_stream_t1(client_session, response, chat_messages): yield result
if isinstance(self, (LLMHuoShan, LLMZhipu)): async for result in self.handle_completions_stream_t2(client_session, response, chat_messages): yield result
async def handle_completions_stream_t1(self, client_session, response, chat_messages): """流式会话响应处理 """ finish_reason = '' tool_infos = {} for resp in response: choice = resp.choices[0] finish_reason = choice.finish_reason tool_calls = choice.delta.tool_calls content = choice.delta.content
if all([finish_reason is None, tool_calls is None, content in ['', None]]): continue
if finish_reason == FinishReason.TOOL_CALLS: break
if not tool_calls: if finish_reason is None or finish_reason == FinishReason.STOP: yield resp else: tool = tool_calls[0] tool_idx = tool.index tool_id = tool.id arguments = tool.function.arguments if tool_idx not in tool_infos: tool_infos[tool_idx] = { 'tool_id': tool_id, 'tool_name': tool.function.name, 'arguments': arguments } else: if arguments: tool_infos[tool_idx]['arguments'] += arguments
if finish_reason == FinishReason.TOOL_CALLS and tool_infos: chat_messages = await self._handle_function_call_stream_t1(client_session, tool_infos, chat_messages) yield chat_messages
@staticmethod async def _handle_function_call_stream_t1(client_session, tool_infos, chat_messages): tool_call_list, tool_call_results = [], [] for idx, val in tool_infos.items(): tool_id = val.get('tool_id') tool_name = val.get('tool_name') arguments = val.get('arguments') func_args = json.loads(arguments) if arguments else {}
tool_call_list.append( { "id": tool_id, "function": { "arguments": arguments, "name": tool_name, }, "type": 'function', "index": idx } )
resp = await client_session.call_tool(tool_name, func_args) func_call_content = resp.content[0] if resp and resp.content else None if func_call_content: text_data = json.loads(func_call_content.text) call_result = text_data.get('data', None) call_result = json.dumps(call_result) if call_result else ''
tool_call_results.extend( [ { "role": 'tool', "tool_call_id": tool_id, "content": call_result, },
] )
chat_messages.get('messages').extend([{ "role": 'assistant', "content": '', "tool_calls": tool_call_list }]) chat_messages.get('messages').extend(tool_call_results)
return chat_messages
async def handle_completions_stream_t2(self, client_session, response, chat_messages): """流式会话响应处理 """ for resp in response: choice = resp.choices[0] finish_reason = choice.finish_reason if finish_reason is None or finish_reason == FinishReason.STOP: yield resp
if finish_reason == FinishReason.TOOL_CALLS and choice.delta.tool_calls: chat_messages = await self._handle_function_call_stream_t2(client_session, resp, chat_messages)
yield chat_messages
@staticmethod async def _handle_function_call_stream_t2(client_session, response, chat_messages): if response and chat_messages: choice = response.choices[0] dump_content = choice.delta tool_calls = dump_content.tool_calls for tool in tool_calls: tool_id = tool.id func_name = tool.function.name func_args = json.loads(tool.function.arguments)
resp = await client_session.call_tool(func_name, func_args) func_call_content = resp.content[0] if resp and resp.content else None if func_call_content: text_data = json.loads(func_call_content.text) call_result = text_data.get('data', None) call_result = json.dumps(call_result) if call_result else ''
chat_messages.get('messages').extend( [ dump_content.model_dump(), { "role": 'tool', "tool_call_id": tool_id, "content": call_result, "name": func_name } ] ) else: return chat_messages return chat_messages
@dataclass class LLMDeepseek(LLMBase):
client = OpenAI( base_url=os.getenv("DEEPSEEK_BASE_URL"), api_key=os.getenv("DEEPSEEK_API_KEY"), )
default_model = os.getenv("DEEPSEEK_DEFAULT_MODEL")
@dataclass class LLMAliYun(LLMBase):
client = OpenAI( base_url=os.getenv("ALI_YUN_BASE_URL"), api_key=os.getenv("ALI_YUN_API_KEY"), )
default_model = os.getenv("ALI_YUN_DEFAULT_MODEL")
@dataclass class LLMHuoShan(LLMBase):
client = Ark( api_key=os.getenv("HUO_SHAN_API_KEY") )
default_model = os.getenv("HUO_SHAN_DEFAULT_MODEL")
class LLMZhipu(LLMBase):
client = ZhipuAI(api_key=os.getenv("ZHIPU_API_KEY"))
default_model = os.getenv("ZHIPU_DEFAULT_MODEL")
@dataclass class LLMOpenAI(LLMBase): client = OpenAI( api_key=os.getenv("OPENAI_API_KEY"), )
default_model = os.getenv("OPENAI_DEFAULT_MODEL")
LLM_RESOURCES = { "deepseek": LLMDeepseek, "aliyun": LLMAliYun, "volcengine": LLMHuoShan, "zhipu": LLMZhipu, "openai": LLMOpenAI }
|