|
4 | 4 |
|
5 | 5 | from __future__ import annotations |
6 | 6 |
|
7 | | -import asyncio |
8 | | -import inspect |
9 | | -import json |
10 | | -from typing import Any, List, Optional |
| 7 | +from typing import Any |
11 | 8 |
|
12 | 9 | from agentrun.integration.agentscope.message_adapter import ( |
13 | 10 | AgentScopeMessageAdapter, |
@@ -60,163 +57,3 @@ def wrap_model(self, common_model: CommonModel) -> Any: |
60 | 57 | "http_client": AsyncClient(headers=info.headers), |
61 | 58 | }, |
62 | 59 | ) |
63 | | - |
64 | | - from agentscope.message import TextBlock, ToolUseBlock |
65 | | - from agentscope.model import ChatModelBase, ChatResponse |
66 | | - from agentscope.model._model_usage import ChatUsage |
67 | | - |
68 | | - message_adapter = self._message_adapter |
69 | | - |
70 | | - class AgentRunAgentScopeModel( |
71 | | - ChatModelBase |
72 | | - ): # pragma: no cover - thin wrapper |
73 | | - |
74 | | - def __init__(self, *, stream: bool = False): |
75 | | - super().__init__(common_model.name, stream=False) |
76 | | - self._common_model = common_model |
77 | | - self._message_adapter = message_adapter |
78 | | - |
79 | | - async def __call__( |
80 | | - self, |
81 | | - messages: Any, |
82 | | - tools: Any = None, |
83 | | - tool_choice: Optional[str] = None, |
84 | | - **kwargs: Any, |
85 | | - ) -> ChatResponse: |
86 | | - openai_messages = self._ensure_openai_messages(messages) |
87 | | - tool_payload = self._normalize_tools(tools) |
88 | | - |
89 | | - request_kwargs = { |
90 | | - "messages": openai_messages, |
91 | | - "stream": False, |
92 | | - } |
93 | | - if tool_payload: |
94 | | - request_kwargs["tools"] = tool_payload |
95 | | - if tool_choice: |
96 | | - request_kwargs["tool_choice"] = tool_choice |
97 | | - request_kwargs.update(kwargs) |
98 | | - |
99 | | - response = self._common_model.completions(**request_kwargs) |
100 | | - if inspect.isawaitable(response): |
101 | | - response = await response |
102 | | - elif inspect.isgenerator(response): |
103 | | - response = await asyncio.to_thread(list, response) |
104 | | - |
105 | | - return self._build_chat_response(response) |
106 | | - |
107 | | - def _ensure_openai_messages(self, messages: Any) -> List[dict]: |
108 | | - if not messages: |
109 | | - return [] |
110 | | - |
111 | | - first = messages[0] if isinstance(messages, list) else messages |
112 | | - if isinstance(first, dict) and "role" in first: |
113 | | - return list(messages) |
114 | | - |
115 | | - if self._message_adapter is None: |
116 | | - raise RuntimeError( |
117 | | - "AgentScope message adapter is not registered" |
118 | | - ) |
119 | | - |
120 | | - canonical = self._message_adapter.to_canonical(messages) |
121 | | - return [msg.to_dict() for msg in canonical] |
122 | | - |
123 | | - @staticmethod |
124 | | - def _normalize_tools(tools: Any) -> Optional[List[dict]]: |
125 | | - if tools is None: |
126 | | - return None |
127 | | - if isinstance(tools, list): |
128 | | - return tools |
129 | | - if hasattr(tools, "get_json_schemas"): |
130 | | - return tools.get_json_schemas() |
131 | | - return tools |
132 | | - |
133 | | - def _build_chat_response(self, response: Any) -> ChatResponse: |
134 | | - payload = self._to_plain_dict(response) |
135 | | - choices = payload.get("choices") or [] |
136 | | - |
137 | | - if not choices: |
138 | | - return ChatResponse( |
139 | | - content=[ |
140 | | - TextBlock(type="text", text=str(payload)), |
141 | | - ] |
142 | | - ) |
143 | | - |
144 | | - message = self._to_plain_dict(choices[0].get("message", {})) |
145 | | - blocks: List[dict] = [] |
146 | | - |
147 | | - content = message.get("content") |
148 | | - if isinstance(content, list): |
149 | | - for block in content: |
150 | | - if ( |
151 | | - isinstance(block, dict) |
152 | | - and block.get("type") == "text" |
153 | | - and block.get("text") |
154 | | - ): |
155 | | - blocks.append( |
156 | | - TextBlock( |
157 | | - type="text", |
158 | | - text=str(block.get("text")), |
159 | | - ) |
160 | | - ) |
161 | | - elif content: |
162 | | - blocks.append(TextBlock(type="text", text=str(content))) |
163 | | - |
164 | | - for call in message.get("tool_calls", []) or []: |
165 | | - arguments = call.get("function", {}).get("arguments", {}) |
166 | | - if isinstance(arguments, str): |
167 | | - try: |
168 | | - arguments = json.loads(arguments) |
169 | | - except json.JSONDecodeError: |
170 | | - pass |
171 | | - blocks.append( |
172 | | - ToolUseBlock( |
173 | | - type="tool_use", |
174 | | - id=str(call.get("id", "")), |
175 | | - name=call.get("function", {}).get("name", ""), |
176 | | - input=arguments |
177 | | - if isinstance(arguments, dict) |
178 | | - else {}, |
179 | | - ) |
180 | | - ) |
181 | | - |
182 | | - if not blocks: |
183 | | - blocks.append(TextBlock(type="text", text="")) |
184 | | - |
185 | | - usage_payload = payload.get("usage") or {} |
186 | | - usage = None |
187 | | - if usage_payload: |
188 | | - usage = ChatUsage( |
189 | | - input_tokens=int( |
190 | | - usage_payload.get("prompt_tokens") |
191 | | - or usage_payload.get("input_tokens") |
192 | | - or 0 |
193 | | - ), |
194 | | - output_tokens=int( |
195 | | - usage_payload.get("completion_tokens") |
196 | | - or usage_payload.get("output_tokens") |
197 | | - or 0 |
198 | | - ), |
199 | | - time=float(usage_payload.get("time", 0.0)), |
200 | | - ) |
201 | | - |
202 | | - return ChatResponse(content=blocks, usage=usage) |
203 | | - |
204 | | - @staticmethod |
205 | | - def _to_plain_dict(value: Any) -> dict: |
206 | | - if isinstance(value, dict): |
207 | | - return value |
208 | | - for attr in ("model_dump", "dict"): |
209 | | - if hasattr(value, attr): |
210 | | - try: |
211 | | - return getattr(value, attr)() |
212 | | - except Exception: # pragma: no cover - defensive |
213 | | - continue |
214 | | - if hasattr(value, "__dict__"): |
215 | | - return { |
216 | | - key: val |
217 | | - for key, val in value.__dict__.items() |
218 | | - if not key.startswith("_") |
219 | | - } |
220 | | - return {"content": str(value)} |
221 | | - |
222 | | - return AgentRunAgentScopeModel() |
0 commit comments