temporalio-microsoft-agent-framework 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- temporalio/microsoft_agent_framework/__init__.py +67 -0
- temporalio/microsoft_agent_framework/_activities.py +403 -0
- temporalio/microsoft_agent_framework/_chat_client.py +226 -0
- temporalio/microsoft_agent_framework/_mcp.py +339 -0
- temporalio/microsoft_agent_framework/_plugin.py +294 -0
- temporalio/microsoft_agent_framework/_serde.py +578 -0
- temporalio/microsoft_agent_framework/_workflow_runtime.py +221 -0
- temporalio/microsoft_agent_framework/py.typed +1 -0
- temporalio/microsoft_agent_framework/testing.py +193 -0
- temporalio/microsoft_agent_framework/workflow.py +213 -0
- temporalio_microsoft_agent_framework-0.0.1.dist-info/METADATA +539 -0
- temporalio_microsoft_agent_framework-0.0.1.dist-info/RECORD +14 -0
- temporalio_microsoft_agent_framework-0.0.1.dist-info/WHEEL +4 -0
- temporalio_microsoft_agent_framework-0.0.1.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,578 @@
|
|
|
1
|
+
"""Dict forms of what crosses the model Activity boundary.
|
|
2
|
+
|
|
3
|
+
Agent Framework's messages, responses and updates are ``SerializationMixin``
|
|
4
|
+
objects whose ``to_dict`` and ``from_dict`` produce JSON-native dicts and leave
|
|
5
|
+
out ``raw_representation`` (the provider SDK's objects), so the plugin needs no
|
|
6
|
+
payload converter of its own. Tools cross as their JSON schema specs and come
|
|
7
|
+
back as declaration-only ``FunctionTool`` objects, so the provider advertises
|
|
8
|
+
them and returns the model's calls without executing anything. A Pydantic
|
|
9
|
+
``response_format`` crosses as its JSON schema.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import copy
|
|
15
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from agent_framework import ChatResponse, ChatResponseUpdate, FunctionTool, Message
|
|
19
|
+
from pydantic import BaseModel
|
|
20
|
+
|
|
21
|
+
from temporalio.microsoft_agent_framework.workflow import (
|
|
22
|
+
MicrosoftAgentFrameworkWorkflowError,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def dump_messages(messages: Sequence[Message]) -> list[dict[str, Any]]:
|
|
27
|
+
"""Serialize the messages of one model call."""
|
|
28
|
+
return [message.to_dict() for message in messages]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def load_messages(data: Sequence[dict[str, Any]]) -> list[Message]:
|
|
32
|
+
"""Rebuild the messages of one model call."""
|
|
33
|
+
return [Message.from_dict(item) for item in data]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def dump_options(options: Mapping[str, Any]) -> dict[str, Any]:
|
|
37
|
+
"""Serialize the chat options of one model call.
|
|
38
|
+
|
|
39
|
+
Raises:
|
|
40
|
+
MicrosoftAgentFrameworkWorkflowError: If a tool or an option value cannot be
|
|
41
|
+
recorded in workflow history.
|
|
42
|
+
"""
|
|
43
|
+
dumped: dict[str, Any] = {}
|
|
44
|
+
for key, value in options.items():
|
|
45
|
+
if key == "tools" and value is not None:
|
|
46
|
+
value = [_dump_tool(tool) for tool in value]
|
|
47
|
+
elif key == "response_format":
|
|
48
|
+
value = _dump_response_format(value)
|
|
49
|
+
_require_json(key, value)
|
|
50
|
+
dumped[key] = value
|
|
51
|
+
return dumped
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
HostedMCPHeaders = Mapping[str, str] | Callable[[], Mapping[str, str]]
|
|
55
|
+
"""Headers for one hosted MCP server: a mapping, or a callable that returns one per call."""
|
|
56
|
+
|
|
57
|
+
# Keys of a hosted MCP tool mapping that carry credentials for the provider's
|
|
58
|
+
# calls to the MCP server. Workflow code must not set them: the mapping is
|
|
59
|
+
# recorded in workflow history.
|
|
60
|
+
_HOSTED_MCP_CREDENTIAL_KEYS = ("headers", "authorization")
|
|
61
|
+
# Where a hosted MCP mapping names its server, in the shapes the providers build.
|
|
62
|
+
_HOSTED_MCP_NAME_KEYS = ("server_label", "name", "server_url", "url")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def load_options(
|
|
66
|
+
options: Mapping[str, Any],
|
|
67
|
+
hosted_mcp_headers: Mapping[str, HostedMCPHeaders] | None = None,
|
|
68
|
+
) -> dict[str, Any]:
|
|
69
|
+
"""Rebuild the chat options of one model call for the provider client.
|
|
70
|
+
|
|
71
|
+
``hosted_mcp_headers`` supplies the headers of hosted MCP tools, keyed by
|
|
72
|
+
the server's label or URL; they are added to the tool here, on the worker.
|
|
73
|
+
"""
|
|
74
|
+
loaded = dict(options)
|
|
75
|
+
tools = loaded.get("tools")
|
|
76
|
+
if tools is not None:
|
|
77
|
+
loaded["tools"] = [_load_tool(tool, hosted_mcp_headers) for tool in tools]
|
|
78
|
+
return loaded
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
# Header names that carry credentials. ``client_kwargs`` are recorded in
|
|
82
|
+
# workflow history, so an ``extra_headers`` entry with one of these names is
|
|
83
|
+
# refused; the header belongs on the provider client built in the factory.
|
|
84
|
+
_CREDENTIAL_HEADER_NAMES = frozenset({"authorization", "x-api-key", "api-key"})
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def dump_kwargs(kwargs: Mapping[str, Any]) -> dict[str, Any]:
|
|
88
|
+
"""Serialize the ``client_kwargs`` of one model call.
|
|
89
|
+
|
|
90
|
+
Raises:
|
|
91
|
+
MicrosoftAgentFrameworkWorkflowError: If a value cannot be recorded in workflow
|
|
92
|
+
history, or ``extra_headers`` carries a credential header
|
|
93
|
+
(``authorization``, ``x-api-key`` or ``api-key``, in any case).
|
|
94
|
+
"""
|
|
95
|
+
_require_json("client_kwargs", kwargs)
|
|
96
|
+
headers = kwargs.get("extra_headers")
|
|
97
|
+
if isinstance(headers, Mapping):
|
|
98
|
+
present = [
|
|
99
|
+
key
|
|
100
|
+
for key in headers
|
|
101
|
+
if isinstance(key, str) and key.lower() in _CREDENTIAL_HEADER_NAMES
|
|
102
|
+
]
|
|
103
|
+
if present:
|
|
104
|
+
raise _credentials_in_workflow_error(
|
|
105
|
+
"client_kwargs extra_headers",
|
|
106
|
+
present,
|
|
107
|
+
"Set the header on the provider client built in the chat client "
|
|
108
|
+
"factory instead.",
|
|
109
|
+
)
|
|
110
|
+
return dict(kwargs)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _credentials_in_workflow_error(
|
|
114
|
+
what: str, keys: Sequence[str], fix: str
|
|
115
|
+
) -> MicrosoftAgentFrameworkWorkflowError:
|
|
116
|
+
return MicrosoftAgentFrameworkWorkflowError(
|
|
117
|
+
f"{what} sets {', '.join(keys)} in workflow code, which would record the "
|
|
118
|
+
f"credentials in workflow history; credentials stay on the worker. {fix}"
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def dump_response(response: ChatResponse) -> dict[str, Any]:
|
|
123
|
+
"""Serialize a provider response."""
|
|
124
|
+
data = response.to_dict()
|
|
125
|
+
for message in data.get("messages") or []:
|
|
126
|
+
_drop_declaration_markers(message.get("contents") or [])
|
|
127
|
+
return data
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def load_response(data: dict[str, Any], response_format: Any = None) -> ChatResponse:
|
|
131
|
+
"""Rebuild a provider response; ``response_format`` is what ``value`` parses with."""
|
|
132
|
+
if response_format is None:
|
|
133
|
+
return ChatResponse.from_dict(data)
|
|
134
|
+
return ChatResponse.from_dict({**data, "response_format": response_format})
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def dump_update(update: ChatResponseUpdate) -> dict[str, Any]:
|
|
138
|
+
"""Serialize one streamed update."""
|
|
139
|
+
data = update.to_dict()
|
|
140
|
+
_drop_declaration_markers(data.get("contents") or [])
|
|
141
|
+
return data
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _drop_declaration_markers(contents: list[dict[str, Any]]) -> None:
|
|
145
|
+
# Every tool reaches the provider as declaration-only, so its function
|
|
146
|
+
# invocation layer marks each returned call as needing caller input. The
|
|
147
|
+
# workflow's own loop decides that for the real tools, so the marker from
|
|
148
|
+
# the worker side must not reach history.
|
|
149
|
+
for content in contents:
|
|
150
|
+
if content.get("type") == "function_call":
|
|
151
|
+
content.pop("user_input_request", None)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def load_update(data: dict[str, Any]) -> ChatResponseUpdate:
|
|
155
|
+
"""Rebuild one streamed update."""
|
|
156
|
+
return ChatResponseUpdate.from_dict(data)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class StreamRecorder:
|
|
160
|
+
"""Builds the Activity result of one streamed call from the provider's updates.
|
|
161
|
+
|
|
162
|
+
Two things differ from the raw update list. The provider's function
|
|
163
|
+
invocation layer, which sees every tool as declaration-only, follows each
|
|
164
|
+
function call with a marked copy of it (the framework's pause for caller
|
|
165
|
+
input); the copy repeats a call already streamed, so it is dropped. Text
|
|
166
|
+
and tool-call arguments arrive one token per update, and a long answer or
|
|
167
|
+
a large argument would put megabytes of update envelopes into history, so
|
|
168
|
+
adjacent text-only updates that share their envelope, their ``merge_mode``
|
|
169
|
+
(none or ``append``, as the OpenAI clients emit) and their other
|
|
170
|
+
properties are merged into one entry, with their ``logprobs`` lists
|
|
171
|
+
concatenated and empty ones dropped; so are adjacent
|
|
172
|
+
``merge_mode="append"`` argument deltas of one call (matched by
|
|
173
|
+
``call_id``, or by the provider's ``tool_call_index`` when a continuation
|
|
174
|
+
chunk carries no id). A ``replace`` update with the full text or
|
|
175
|
+
arguments stays its own entry. ``ChatResponse.from_updates`` rebuilds the
|
|
176
|
+
same response either way. ``add`` returns the serialized update to publish,
|
|
177
|
+
before merging, or ``None`` for a dropped copy; ``updates`` is the record.
|
|
178
|
+
"""
|
|
179
|
+
|
|
180
|
+
def __init__(self) -> None:
|
|
181
|
+
"""Start an empty record."""
|
|
182
|
+
self._updates: list[dict[str, Any]] = []
|
|
183
|
+
self._streamed_calls: set[str] = set()
|
|
184
|
+
# The open run of deltas: the content dict of the last entry that
|
|
185
|
+
# receives them, the key under it, and the pieces so far. They are
|
|
186
|
+
# joined once when the run ends; appending to the string on every
|
|
187
|
+
# delta would copy it each time, quadratic in the length of the stream.
|
|
188
|
+
self._run_content: dict[str, Any] | None = None
|
|
189
|
+
self._run_key = ""
|
|
190
|
+
self._run_pieces: list[str] = []
|
|
191
|
+
|
|
192
|
+
@property
|
|
193
|
+
def updates(self) -> list[dict[str, Any]]:
|
|
194
|
+
"""The recorded entries, with the open run of deltas joined."""
|
|
195
|
+
self._close_run()
|
|
196
|
+
return self._updates
|
|
197
|
+
|
|
198
|
+
def add(self, update: ChatResponseUpdate) -> dict[str, Any] | None:
|
|
199
|
+
"""Record ``update``; return its serialized form, or ``None`` if dropped."""
|
|
200
|
+
if self._is_pause_copy(update):
|
|
201
|
+
return None
|
|
202
|
+
for content in update.contents:
|
|
203
|
+
if content.type == "function_call" and content.call_id:
|
|
204
|
+
self._streamed_calls.add(content.call_id)
|
|
205
|
+
serialized = dump_update(update)
|
|
206
|
+
previous = self._updates[-1] if self._updates else None
|
|
207
|
+
delta = _argument_delta(serialized)
|
|
208
|
+
if previous is not None and same_envelope(previous, serialized):
|
|
209
|
+
if (
|
|
210
|
+
_mergeable_text(serialized)
|
|
211
|
+
and _mergeable_text(previous)
|
|
212
|
+
and _same_text_run(previous["contents"][0], serialized["contents"][0])
|
|
213
|
+
):
|
|
214
|
+
target = previous["contents"][0]
|
|
215
|
+
self._extend_run(target, "text", serialized["contents"][0]["text"])
|
|
216
|
+
_merge_logprobs(target, serialized["contents"][0])
|
|
217
|
+
return serialized
|
|
218
|
+
earlier = _argument_delta(previous)
|
|
219
|
+
if delta is not None and earlier is not None and _same_call(earlier, delta):
|
|
220
|
+
self._extend_run(earlier, "arguments", delta["arguments"])
|
|
221
|
+
return serialized
|
|
222
|
+
self._close_run()
|
|
223
|
+
if _mergeable_text(serialized) or delta is not None:
|
|
224
|
+
# The caller publishes ``serialized`` as is, possibly later in a
|
|
225
|
+
# batch; the record gets its own copy, which later deltas are
|
|
226
|
+
# merged into.
|
|
227
|
+
self._updates.append(
|
|
228
|
+
{
|
|
229
|
+
**serialized,
|
|
230
|
+
"contents": [_copy_content(c) for c in serialized["contents"]],
|
|
231
|
+
}
|
|
232
|
+
)
|
|
233
|
+
else:
|
|
234
|
+
self._updates.append(serialized)
|
|
235
|
+
return serialized
|
|
236
|
+
|
|
237
|
+
def _extend_run(self, content: dict[str, Any], key: str, piece: str) -> None:
|
|
238
|
+
if self._run_content is not content or self._run_key != key:
|
|
239
|
+
self._close_run()
|
|
240
|
+
self._run_content = content
|
|
241
|
+
self._run_key = key
|
|
242
|
+
self._run_pieces = [content[key]]
|
|
243
|
+
self._run_pieces.append(piece)
|
|
244
|
+
|
|
245
|
+
def _close_run(self) -> None:
|
|
246
|
+
if self._run_content is not None:
|
|
247
|
+
self._run_content[self._run_key] = "".join(self._run_pieces)
|
|
248
|
+
if self._run_key == "text":
|
|
249
|
+
_drop_empty_logprobs(self._run_content)
|
|
250
|
+
self._run_content = None
|
|
251
|
+
self._run_pieces = []
|
|
252
|
+
|
|
253
|
+
def _is_pause_copy(self, update: ChatResponseUpdate) -> bool:
|
|
254
|
+
if not update.contents:
|
|
255
|
+
return False
|
|
256
|
+
return all(
|
|
257
|
+
content.type == "function_call"
|
|
258
|
+
and content.user_input_request is True
|
|
259
|
+
and content.call_id in self._streamed_calls
|
|
260
|
+
for content in update.contents
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
_TEXT_CONTENT_KEYS = {"type", "text", "merge_mode", "additional_properties"}
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _mergeable_text(update: dict[str, Any]) -> bool:
|
|
268
|
+
"""Whether ``update`` is one text delta, with nothing a merge would lose."""
|
|
269
|
+
contents = update.get("contents") or []
|
|
270
|
+
if len(contents) != 1 or update.get("finish_reason") is not None:
|
|
271
|
+
return False
|
|
272
|
+
(content,) = contents
|
|
273
|
+
return (
|
|
274
|
+
content.get("type") == "text"
|
|
275
|
+
and isinstance(content.get("text"), str)
|
|
276
|
+
and set(content) <= _TEXT_CONTENT_KEYS
|
|
277
|
+
and content.get("merge_mode") in (None, "append")
|
|
278
|
+
and isinstance(content.get("additional_properties", {}), dict)
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _same_text_run(earlier: dict[str, Any], content: dict[str, Any]) -> bool:
|
|
283
|
+
"""Whether two text deltas agree on everything a merge keeps once: mode and properties."""
|
|
284
|
+
return earlier.get("merge_mode") == content.get("merge_mode") and (
|
|
285
|
+
_without_logprobs(earlier.get("additional_properties"))
|
|
286
|
+
== _without_logprobs(content.get("additional_properties"))
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _without_logprobs(properties: Any) -> dict[str, Any]:
|
|
291
|
+
if not isinstance(properties, dict):
|
|
292
|
+
return {}
|
|
293
|
+
rest = {k: v for k, v in properties.items() if k != "logprobs"}
|
|
294
|
+
openai = rest.get("openai")
|
|
295
|
+
if isinstance(openai, dict):
|
|
296
|
+
openai = {k: v for k, v in openai.items() if k != "logprobs"}
|
|
297
|
+
if openai:
|
|
298
|
+
rest["openai"] = openai
|
|
299
|
+
else:
|
|
300
|
+
rest.pop("openai")
|
|
301
|
+
return rest
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _merge_logprobs(target: dict[str, Any], incoming: dict[str, Any]) -> None:
|
|
305
|
+
"""Append the incoming delta's ``logprobs`` (top level and under ``openai``) to the record's."""
|
|
306
|
+
source = incoming.get("additional_properties")
|
|
307
|
+
if not isinstance(source, dict):
|
|
308
|
+
return
|
|
309
|
+
properties = target.setdefault("additional_properties", {})
|
|
310
|
+
for namespace in (None, "openai"):
|
|
311
|
+
holder = source if namespace is None else source.get(namespace)
|
|
312
|
+
if not isinstance(holder, dict) or not isinstance(holder.get("logprobs"), list):
|
|
313
|
+
continue
|
|
314
|
+
destination = (
|
|
315
|
+
properties if namespace is None else properties.setdefault(namespace, {})
|
|
316
|
+
)
|
|
317
|
+
existing = destination.get("logprobs")
|
|
318
|
+
if isinstance(existing, list):
|
|
319
|
+
existing.extend(holder["logprobs"])
|
|
320
|
+
else:
|
|
321
|
+
destination["logprobs"] = list(holder["logprobs"])
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _drop_empty_logprobs(content: dict[str, Any]) -> None:
|
|
325
|
+
properties = content.get("additional_properties")
|
|
326
|
+
if not isinstance(properties, dict):
|
|
327
|
+
return
|
|
328
|
+
if properties.get("logprobs") == []:
|
|
329
|
+
properties.pop("logprobs")
|
|
330
|
+
openai = properties.get("openai")
|
|
331
|
+
if isinstance(openai, dict):
|
|
332
|
+
if openai.get("logprobs") == []:
|
|
333
|
+
openai.pop("logprobs")
|
|
334
|
+
if not openai:
|
|
335
|
+
properties.pop("openai")
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def _copy_content(content: dict[str, Any]) -> dict[str, Any]:
|
|
339
|
+
"""Copy a content dict so merging into the record never touches the published one."""
|
|
340
|
+
copied = dict(content)
|
|
341
|
+
properties = content.get("additional_properties")
|
|
342
|
+
if isinstance(properties, dict):
|
|
343
|
+
copied["additional_properties"] = copy.deepcopy(properties)
|
|
344
|
+
return copied
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _argument_delta(update: dict[str, Any]) -> dict[str, Any] | None:
|
|
348
|
+
"""Return the content of a single append-mode tool-call argument delta, or ``None``."""
|
|
349
|
+
contents = update.get("contents") or []
|
|
350
|
+
if len(contents) != 1 or update.get("finish_reason") is not None:
|
|
351
|
+
return None
|
|
352
|
+
(content,) = contents
|
|
353
|
+
if (
|
|
354
|
+
content.get("type") == "function_call"
|
|
355
|
+
and content.get("merge_mode") == "append"
|
|
356
|
+
and isinstance(content.get("arguments"), str)
|
|
357
|
+
):
|
|
358
|
+
return content
|
|
359
|
+
return None
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def _same_call(earlier: dict[str, Any], delta: dict[str, Any]) -> bool:
|
|
363
|
+
"""Whether ``delta`` continues the call ``earlier`` started."""
|
|
364
|
+
call_id = delta.get("call_id")
|
|
365
|
+
if call_id:
|
|
366
|
+
return earlier.get("call_id") == call_id
|
|
367
|
+
# The Chat Completions client leaves the id off continuation chunks and
|
|
368
|
+
# numbers the call instead.
|
|
369
|
+
index = (delta.get("additional_properties") or {}).get("tool_call_index")
|
|
370
|
+
return index is not None and (
|
|
371
|
+
(earlier.get("additional_properties") or {}).get("tool_call_index") == index
|
|
372
|
+
)
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def same_envelope(left: dict[str, Any], right: dict[str, Any]) -> bool:
|
|
376
|
+
"""Whether two serialized updates agree on everything but their contents."""
|
|
377
|
+
return {k: v for k, v in left.items() if k != "contents"} == {
|
|
378
|
+
k: v for k, v in right.items() if k != "contents"
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def _dump_tool(tool: Any) -> dict[str, Any]:
|
|
383
|
+
if isinstance(tool, FunctionTool):
|
|
384
|
+
return tool.to_json_schema_spec()
|
|
385
|
+
if isinstance(tool, Mapping):
|
|
386
|
+
if tool.get("type") == "mcp":
|
|
387
|
+
present = [key for key in _HOSTED_MCP_CREDENTIAL_KEYS if tool.get(key)]
|
|
388
|
+
if present:
|
|
389
|
+
raise _credentials_in_workflow_error(
|
|
390
|
+
f"Hosted MCP tool {_hosted_mcp_name(tool)!r}",
|
|
391
|
+
present,
|
|
392
|
+
"Remove them from the tool and pass them with "
|
|
393
|
+
"MicrosoftAgentFrameworkPlugin(hosted_mcp_headers=...) keyed by "
|
|
394
|
+
"the server label or URL.",
|
|
395
|
+
)
|
|
396
|
+
return dict(tool)
|
|
397
|
+
raise MicrosoftAgentFrameworkWorkflowError(
|
|
398
|
+
f"Tool {tool!r} of type {type(tool).__qualname__} cannot be sent to the "
|
|
399
|
+
"model Activity. Use a @tool function, a FunctionTool, activity_as_tool(...), "
|
|
400
|
+
"a provider tool mapping, or a TemporalMCPToolProvider in context_providers."
|
|
401
|
+
)
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def _hosted_mcp_name(tool: Mapping[str, Any]) -> str | None:
|
|
405
|
+
for key in _HOSTED_MCP_NAME_KEYS:
|
|
406
|
+
value = tool.get(key)
|
|
407
|
+
if isinstance(value, str) and value:
|
|
408
|
+
return value
|
|
409
|
+
return None
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def _with_hosted_mcp_headers(
|
|
413
|
+
spec: Mapping[str, Any], hosted_mcp_headers: Mapping[str, HostedMCPHeaders] | None
|
|
414
|
+
) -> dict[str, Any]:
|
|
415
|
+
tool = dict(spec)
|
|
416
|
+
if not hosted_mcp_headers:
|
|
417
|
+
return tool
|
|
418
|
+
for key in _HOSTED_MCP_NAME_KEYS:
|
|
419
|
+
value = spec.get(key)
|
|
420
|
+
if isinstance(value, str) and value in hosted_mcp_headers:
|
|
421
|
+
headers = hosted_mcp_headers[value]
|
|
422
|
+
resolved = dict(headers() if callable(headers) else headers)
|
|
423
|
+
if spec.get("connector_id"):
|
|
424
|
+
# An OpenAI connector takes its OAuth token in the tool's
|
|
425
|
+
# authorization field, not in a header, and as the bare token.
|
|
426
|
+
for name in [n for n in resolved if n.lower() == "authorization"]:
|
|
427
|
+
tool["authorization"] = _bare_token(resolved.pop(name))
|
|
428
|
+
if resolved:
|
|
429
|
+
tool["headers"] = resolved
|
|
430
|
+
return tool
|
|
431
|
+
return tool
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def _bare_token(value: str) -> str:
|
|
435
|
+
"""Drop a leading ``Bearer`` (any case) from a header-style credential value."""
|
|
436
|
+
scheme, _, token = value.strip().partition(" ")
|
|
437
|
+
if scheme.lower() == "bearer" and token.strip():
|
|
438
|
+
return token.strip()
|
|
439
|
+
return value
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def _load_tool(
|
|
443
|
+
spec: Any, hosted_mcp_headers: Mapping[str, HostedMCPHeaders] | None = None
|
|
444
|
+
) -> Any:
|
|
445
|
+
if not isinstance(spec, Mapping):
|
|
446
|
+
return spec
|
|
447
|
+
if spec.get("type") == "mcp":
|
|
448
|
+
return _with_hosted_mcp_headers(spec, hosted_mcp_headers)
|
|
449
|
+
if spec.get("type") != "function":
|
|
450
|
+
return spec
|
|
451
|
+
function = spec.get("function")
|
|
452
|
+
if not isinstance(function, Mapping):
|
|
453
|
+
return spec
|
|
454
|
+
parameters = function.get("parameters")
|
|
455
|
+
return FunctionTool(
|
|
456
|
+
name=str(function["name"]),
|
|
457
|
+
description=str(function.get("description") or ""),
|
|
458
|
+
func=None,
|
|
459
|
+
input_model=dict(parameters) if isinstance(parameters, Mapping) else None,
|
|
460
|
+
)
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def _dump_response_format(value: Any) -> Any:
|
|
464
|
+
if value is None:
|
|
465
|
+
return None
|
|
466
|
+
if isinstance(value, type) and issubclass(value, BaseModel):
|
|
467
|
+
# The form the OpenAI clients send natively for a Pydantic class: the
|
|
468
|
+
# strict schema under the class name, with strict=True, so the
|
|
469
|
+
# provider holds the model to it.
|
|
470
|
+
schema = value.model_json_schema()
|
|
471
|
+
return {
|
|
472
|
+
"type": "json_schema",
|
|
473
|
+
"json_schema": {
|
|
474
|
+
"name": value.__name__,
|
|
475
|
+
"schema": _strict_json_schema(schema, root=schema),
|
|
476
|
+
"strict": True,
|
|
477
|
+
},
|
|
478
|
+
}
|
|
479
|
+
if isinstance(value, Mapping):
|
|
480
|
+
return dict(value)
|
|
481
|
+
raise MicrosoftAgentFrameworkWorkflowError(
|
|
482
|
+
f"response_format {value!r} is not a Pydantic model class or a mapping, "
|
|
483
|
+
"so it cannot be sent to the model Activity."
|
|
484
|
+
)
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
def _strict_json_schema(
|
|
488
|
+
schema: dict[str, Any], *, root: dict[str, Any]
|
|
489
|
+
) -> dict[str, Any]:
|
|
490
|
+
"""Rewrite ``schema`` in place into the providers' strict form, as the OpenAI SDK does.
|
|
491
|
+
|
|
492
|
+
Every object gets ``additionalProperties: false`` and all of its
|
|
493
|
+
properties required; ``$defs``, ``items``, ``anyOf`` and ``allOf`` are
|
|
494
|
+
walked, a single-entry ``allOf`` is flattened, a ``None`` default is
|
|
495
|
+
dropped, and a ``$ref`` with sibling keys is inlined.
|
|
496
|
+
"""
|
|
497
|
+
for key in ("$defs", "definitions"):
|
|
498
|
+
definitions = schema.get(key)
|
|
499
|
+
if isinstance(definitions, dict):
|
|
500
|
+
for definition in definitions.values():
|
|
501
|
+
if isinstance(definition, dict):
|
|
502
|
+
_strict_json_schema(definition, root=root)
|
|
503
|
+
if schema.get("type") == "object" and "additionalProperties" not in schema:
|
|
504
|
+
schema["additionalProperties"] = False
|
|
505
|
+
properties = schema.get("properties")
|
|
506
|
+
if isinstance(properties, dict):
|
|
507
|
+
schema["required"] = list(properties)
|
|
508
|
+
for prop in properties.values():
|
|
509
|
+
if isinstance(prop, dict):
|
|
510
|
+
_strict_json_schema(prop, root=root)
|
|
511
|
+
items = schema.get("items")
|
|
512
|
+
if isinstance(items, dict):
|
|
513
|
+
_strict_json_schema(items, root=root)
|
|
514
|
+
any_of = schema.get("anyOf")
|
|
515
|
+
if isinstance(any_of, list):
|
|
516
|
+
for variant in any_of:
|
|
517
|
+
if isinstance(variant, dict):
|
|
518
|
+
_strict_json_schema(variant, root=root)
|
|
519
|
+
all_of = schema.get("allOf")
|
|
520
|
+
if isinstance(all_of, list):
|
|
521
|
+
if len(all_of) == 1 and isinstance(all_of[0], dict):
|
|
522
|
+
schema.pop("allOf")
|
|
523
|
+
schema.update(_strict_json_schema(all_of[0], root=root))
|
|
524
|
+
else:
|
|
525
|
+
for entry in all_of:
|
|
526
|
+
if isinstance(entry, dict):
|
|
527
|
+
_strict_json_schema(entry, root=root)
|
|
528
|
+
if "default" in schema and schema["default"] is None:
|
|
529
|
+
schema.pop("default")
|
|
530
|
+
ref = schema.get("$ref")
|
|
531
|
+
if isinstance(ref, str) and len(schema) > 1:
|
|
532
|
+
resolved = _resolve_ref(root, ref)
|
|
533
|
+
if isinstance(resolved, dict):
|
|
534
|
+
# The schema's own keys take priority over the referenced ones.
|
|
535
|
+
schema.update({**resolved, **schema})
|
|
536
|
+
schema.pop("$ref")
|
|
537
|
+
return _strict_json_schema(schema, root=root)
|
|
538
|
+
return schema
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def _resolve_ref(root: dict[str, Any], ref: str) -> Any:
|
|
542
|
+
if not ref.startswith("#/"):
|
|
543
|
+
return None
|
|
544
|
+
node: Any = root
|
|
545
|
+
for part in ref[2:].split("/"):
|
|
546
|
+
if not isinstance(node, dict) or part not in node:
|
|
547
|
+
return None
|
|
548
|
+
node = node[part]
|
|
549
|
+
return node
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def _require_json(key: str, value: Any) -> None:
|
|
553
|
+
offender = _first_non_json(value)
|
|
554
|
+
if offender is not None:
|
|
555
|
+
raise MicrosoftAgentFrameworkWorkflowError(
|
|
556
|
+
f"Option {key!r} holds a {type(offender).__qualname__} value, which "
|
|
557
|
+
"cannot be recorded in workflow history; pass JSON-compatible option values."
|
|
558
|
+
)
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def _first_non_json(value: Any) -> Any:
|
|
562
|
+
if value is None or isinstance(value, (str, int, float, bool)):
|
|
563
|
+
return None
|
|
564
|
+
if isinstance(value, (list, tuple)):
|
|
565
|
+
for item in value:
|
|
566
|
+
offender = _first_non_json(item)
|
|
567
|
+
if offender is not None:
|
|
568
|
+
return offender
|
|
569
|
+
return None
|
|
570
|
+
if isinstance(value, Mapping):
|
|
571
|
+
for item_key, item in value.items():
|
|
572
|
+
if not isinstance(item_key, str):
|
|
573
|
+
return item_key
|
|
574
|
+
offender = _first_non_json(item)
|
|
575
|
+
if offender is not None:
|
|
576
|
+
return offender
|
|
577
|
+
return None
|
|
578
|
+
return value
|