11# Copyright (c) Microsoft. All rights reserved.
22
3+ import logging
34import sys
45import types
6+ from contextvars import ContextVar
57from enum import Enum
8+ from functools import reduce
9+ from operator import or_
610from typing import Annotated , Any , ClassVar , ForwardRef , Literal , Union , get_args , get_origin , get_type_hints
711
812from semantic_kernel .const import PARSED_ANNOTATION_UNION_DELIMITER
913from semantic_kernel .exceptions .function_exceptions import FunctionInvalidParameterConfiguration
1014from semantic_kernel .kernel_pydantic import KernelBaseModel
1115
16+ logger = logging .getLogger (__name__ )
17+
18+ # The models whose schema is being built further up the call stack.
19+ _models_in_progress : ContextVar [tuple [Any , ...]] = ContextVar ("_models_in_progress" , default = ())
20+
1221TYPE_MAPPING = {
1322 int : "integer" ,
1423 str : "string" ,
@@ -79,6 +88,11 @@ def build_model_schema(
7988 """
8089 # TODO (moonbox3): add support for handling forward references, which is not currently tested
8190 # https://github.com/microsoft/semantic-kernel/issues/6464
91+ in_progress = _models_in_progress .get ()
92+ if any (model is seen for seen in in_progress ):
93+ # A resolved reference back to a model being built has no finite inline schema; use the placeholder.
94+ return cls .build_from_type_name ("object" , description )
95+
8296 properties = {}
8397 required = []
8498
@@ -110,7 +124,11 @@ def build_model_schema(
110124 break
111125 if not cls ._is_optional (field_type ):
112126 required .append (field_name )
113- properties [field_name ] = cls .build (field_type , field_description , structured_output )
127+ token = _models_in_progress .set ((* in_progress , model ))
128+ try :
129+ properties [field_name ] = cls .build (field_type , field_description , structured_output )
130+ finally :
131+ _models_in_progress .reset (token )
114132
115133 schema = {"type" : "object" , "properties" : properties }
116134 if required :
@@ -124,26 +142,28 @@ def build_model_schema(
124142
125143 @classmethod
126144 def resolve_forward_refs (cls , annotation : Any , globalns : dict [str , Any ]) -> Any :
127- """Resolves forward references sitting inside a generic alias .
145+ """Resolves forward references that annotation evaluation leaves behind .
128146
129- On Python 3.10, ``get_type_hints`` evaluates an annotation that *is* a string and
130- ``ForwardRef`` objects nested inside a generic alias, but not a bare ``str`` sitting in a
131- PEP 585 alias's ``__args__``. ``list["Inner"]`` goes through ``list.__class_getitem__``,
132- which stores ``"Inner"`` verbatim with no ``ForwardRef`` wrapper, so nothing resolves it and
133- the element type falls through to the ``{"type": "object"}`` placeholder.
134- ``typing.Optional["Inner"]`` does wrap the string, which is why the top-level and
135- ``Optional`` forms already work.
147+ Kernel function parameters come from ``signature(func, eval_str=True)``, which evaluates an
148+ annotation that *is* a string and nothing below it, on every Python version. ``list["Inner"]``
149+ keeps its string, and unwrapping ``Optional["Inner"]`` or ``Annotated["Inner", ...]`` leaves a bare
150+ ``ForwardRef``. Unresolved, these fall through to the ``{"type": "object"}`` placeholder.
136151
137- Python 3.11 made ``get_type_hints`` wrap those strings itself (gh-85542), so on 3.11+ the
138- hints arrive fully resolved and this is a no-op that returns the annotation unchanged.
152+ Model fields come from ``get_type_hints``. On Python 3.10 it evaluates ``ForwardRef`` objects but
153+ not a bare ``str`` in a PEP 585 alias's ``__args__``, because ``list.__class_getitem__`` stores
154+ ``"Inner"`` verbatim. Python 3.11 made it wrap those strings itself (gh-85542), so on 3.11+ model
155+ field hints arrive fully resolved and come back from here unchanged.
139156
140157 Args:
141158 annotation: The annotation to resolve.
142159 globalns: The namespace of the module owning the annotation.
143160
144161 Returns:
145- Any: The annotation, rebuilt with resolvable string arguments replaced by their types.
162+ Any: The annotation, rebuilt with resolvable references replaced by their types. An alias
163+ that cannot be rebuilt is returned unchanged and a warning is logged.
146164 """
165+ if isinstance (annotation , (str , ForwardRef )):
166+ return cls ._resolve_forward_ref_arg (annotation , globalns )
147167 origin = get_origin (annotation )
148168 args = get_args (annotation )
149169 if origin is None or not args :
@@ -160,11 +180,34 @@ def resolve_forward_refs(cls, annotation: Any, globalns: dict[str, Any]) -> Any:
160180 return annotation
161181
162182 try :
163- return origin [resolved_args ]
164- except TypeError :
165- # Not every alias can be rebuilt from its origin and args; keep the original.
183+ return cls ._rebuild_alias (origin , resolved_args )
184+ except TypeError as ex :
185+ # A failure here must not stop a function from being decorated, so keep the original alias and its
186+ # placeholder schema, but say so: a reference that did resolve has just been thrown away.
187+ logger .warning (f"Could not rebuild { annotation !r} with its forward references resolved: { ex } " )
166188 return annotation
167189
190+ @staticmethod
191+ def _rebuild_alias (origin : Any , args : tuple [Any , ...]) -> Any :
192+ """Rebuilds a generic alias from its origin and resolved arguments.
193+
194+ Args:
195+ origin: The origin of the alias, as returned by ``get_origin``.
196+ args: The resolved arguments of the alias.
197+
198+ Returns:
199+ Any: The rebuilt alias.
200+
201+ Raises:
202+ TypeError: If the origin cannot be parameterized with these arguments.
203+ """
204+ if origin is types .UnionType :
205+ # Before Python 3.14 this is the origin of PEP 604 unions only and it is not subscriptable. From 3.14
206+ # it is also typing.Union, and joining the arguments is still correct for both spellings.
207+ return reduce (or_ , args )
208+ # Special forms such as ClassVar and Final accept a single type, not a one element tuple.
209+ return origin [args [0 ] if len (args ) == 1 else args ]
210+
168211 @classmethod
169212 def _resolve_forward_ref_arg (cls , arg : Any , globalns : dict [str , Any ]) -> Any :
170213 """Resolves a single generic argument, recursing into nested generic aliases.
@@ -180,29 +223,42 @@ def _resolve_forward_ref_arg(cls, arg: Any, globalns: dict[str, Any]) -> Any:
180223 return cls ._lookup_type (arg , globalns , default = arg )
181224 if isinstance (arg , ForwardRef ):
182225 return cls ._lookup_type (arg .__forward_arg__ , globalns , default = arg )
226+ if isinstance (arg , list ):
227+ # Callable keeps its parameter types in a nested list.
228+ return [cls ._resolve_forward_ref_arg (item , globalns ) for item in arg ]
183229 return cls .resolve_forward_refs (arg , globalns )
184230
185231 @staticmethod
186232 def _lookup_type (name : str , globalns : dict [str , Any ], default : Any ) -> Any :
187- """Looks a name up in the namespace, substituting it only when it names a type.
233+ """Looks a name up in the namespace, substituting it only when it names a usable type.
188234
189235 A forward reference that happens to share its name with a module, a function or a plain
190236 value must not be rebuilt around that object: a module reaches ``build_model_schema`` and
191- fails on ``__module__``, and a function or value would produce a misleading schema. Keeping
237+ fails on ``__module__``, and a function or value would produce a misleading schema. The same
238+ goes for a class whose own type hints do not evaluate, for example hints on names imported only
239+ under ``TYPE_CHECKING``: ``build_model_schema`` would raise at function registration. Keeping
192240 the original reference lets the existing placeholder fallback apply instead.
193241
194242 Args:
195243 name: The referenced name.
196244 globalns: The namespace to look it up in.
197- default: What to return when the name is missing or does not name a type.
245+ default: What to return when the name is missing or does not name a usable type.
198246
199247 Returns:
200248 Any: The class or typing construct the name refers to, or ``default``.
201249 """
202250 value = globalns .get (name , default )
203- if isinstance ( value , type ) or get_origin (value ) is not None :
251+ if get_origin (value ) is not None :
204252 return value
205- return default
253+ if not isinstance (value , type ):
254+ return default
255+ try :
256+ get_type_hints (value , globalns = vars (sys .modules [value .__module__ ]), localns = {})
257+ except Exception as ex :
258+ # Evaluating annotation strings can raise anything.
259+ logger .warning (f"Keeping forward reference { name !r} unresolved, its type hints do not evaluate: { ex } " )
260+ return default
261+ return value
206262
207263 @classmethod
208264 def _is_optional (cls , field_type : Any ) -> bool :
0 commit comments