chore: import upstream snapshot with attribution
CodeQL / Analyze (csharp) (push) Waiting to run
CodeQL / Analyze (python) (push) Waiting to run

This commit is contained in:
wehub-resource-sync
2026-07-13 13:21:23 +08:00
commit b957a53def
5423 changed files with 863745 additions and 0 deletions
@@ -0,0 +1,23 @@
# Copyright (c) Microsoft. All rights reserved.
from semantic_kernel.agents.strategies.selection.kernel_function_selection_strategy import (
KernelFunctionSelectionStrategy,
)
from semantic_kernel.agents.strategies.selection.selection_strategy import SelectionStrategy
from semantic_kernel.agents.strategies.selection.sequential_selection_strategy import SequentialSelectionStrategy
from semantic_kernel.agents.strategies.termination.aggregator_termination_strategy import AggregatorTerminationStrategy
from semantic_kernel.agents.strategies.termination.default_termination_strategy import DefaultTerminationStrategy
from semantic_kernel.agents.strategies.termination.kernel_function_termination_strategy import (
KernelFunctionTerminationStrategy,
)
from semantic_kernel.agents.strategies.termination.termination_strategy import TerminationStrategy
__all__ = [
"AggregatorTerminationStrategy",
"DefaultTerminationStrategy",
"KernelFunctionSelectionStrategy",
"KernelFunctionTerminationStrategy",
"SelectionStrategy",
"SequentialSelectionStrategy",
"TerminationStrategy",
]
@@ -0,0 +1,116 @@
# Copyright (c) Microsoft. All rights reserved.
import logging
import sys
if sys.version_info >= (3, 12):
from typing import override # pragma: no cover
else:
from typing_extensions import override # pragma: no cover
from collections.abc import Callable
from inspect import isawaitable
from typing import TYPE_CHECKING, ClassVar
from pydantic import Field
from semantic_kernel.agents.strategies.selection.selection_strategy import SelectionStrategy
from semantic_kernel.contents.chat_message_content import ChatMessageContent
from semantic_kernel.contents.history_reducer.chat_history_reducer import ChatHistoryReducer
from semantic_kernel.exceptions.agent_exceptions import AgentExecutionException
from semantic_kernel.functions.kernel_arguments import KernelArguments
from semantic_kernel.functions.kernel_function import KernelFunction
from semantic_kernel.kernel import Kernel
from semantic_kernel.utils.feature_stage_decorator import experimental
if TYPE_CHECKING:
from semantic_kernel.agents import Agent
logger: logging.Logger = logging.getLogger(__name__)
@experimental
class KernelFunctionSelectionStrategy(SelectionStrategy):
"""Determines agent selection based on the evaluation of a Kernel Function."""
DEFAULT_AGENT_VARIABLE_NAME: ClassVar[str] = "_agent_"
DEFAULT_HISTORY_VARIABLE_NAME: ClassVar[str] = "_history_"
agent_variable_name: str | None = Field(default=DEFAULT_AGENT_VARIABLE_NAME)
history_variable_name: str | None = Field(default=DEFAULT_HISTORY_VARIABLE_NAME)
arguments: KernelArguments | None = None
function: KernelFunction
kernel: Kernel
result_parser: Callable[..., str] = Field(default_factory=lambda: (lambda: ""))
history_reducer: ChatHistoryReducer | None = None
@override
async def select_agent(self, agents: list["Agent"], history: list[ChatMessageContent]) -> "Agent":
"""Select the next agent to interact with.
Args:
agents: The list of agents to select from.
history: The history of messages in the conversation.
Returns:
The next agent to interact with.
Raises:
AgentExecutionException: If the strategy fails to execute the function or select the next agent
"""
if self.history_reducer is not None:
self.history_reducer.messages = history
reduced_history = await self.history_reducer.reduce()
if reduced_history is not None:
history = reduced_history.messages
original_arguments = self.arguments or KernelArguments()
execution_settings = original_arguments.execution_settings or {}
messages = [message.to_dict(role_key="role", content_key="content") for message in history]
filtered_arguments = {
self.agent_variable_name: ",".join(agent.name for agent in agents),
self.history_variable_name: messages,
}
extracted_settings = {key: setting.model_dump() for key, setting in execution_settings.items()}
combined_arguments = {
**original_arguments,
**extracted_settings,
**{k: v for k, v in filtered_arguments.items()},
}
arguments = KernelArguments(
**combined_arguments,
)
logger.info(
f"Kernel Function Selection Strategy next method called, "
f"invoking function: {self.function.plugin_name}, {self.function.name}",
)
try:
result = await self.function.invoke(kernel=self.kernel, arguments=arguments)
except Exception as ex:
logger.error("Kernel Function Selection Strategy next method failed", exc_info=ex)
raise AgentExecutionException("Agent Failure - Strategy failed to execute function.") from ex
logger.info(
f"Kernel Function Selection Strategy next method completed: "
f"{self.function.plugin_name}, {self.function.name}, result: {result.value if result else None}",
)
agent_name = self.result_parser(result)
if isawaitable(agent_name):
agent_name = await agent_name
if agent_name is None:
raise AgentExecutionException("Agent Failure - Strategy unable to determine next agent.")
agent_turn = next((agent for agent in agents if agent.name == agent_name), None)
if agent_turn is None:
raise AgentExecutionException(f"Agent Failure - Strategy unable to select next agent: {agent_name}")
return agent_turn
@@ -0,0 +1,57 @@
# Copyright (c) Microsoft. All rights reserved.
from abc import ABC
from typing import TYPE_CHECKING
from semantic_kernel.agents import Agent
from semantic_kernel.exceptions.agent_exceptions import AgentExecutionException
from semantic_kernel.kernel_pydantic import KernelBaseModel
from semantic_kernel.utils.feature_stage_decorator import experimental
if TYPE_CHECKING:
from semantic_kernel.contents.chat_message_content import ChatMessageContent
@experimental
class SelectionStrategy(KernelBaseModel, ABC):
"""Base strategy class for selecting the next agent in a chat."""
has_selected: bool = False
initial_agent: Agent | None = None
async def next(
self,
agents: list[Agent],
history: list["ChatMessageContent"],
) -> Agent:
"""Select the next agent to interact with.
Args:
agents: The list of agents to select from.
history: The history of messages in the conversation.
Returns:
The agent who takes the next turn.
"""
if not agents and self.initial_agent is None:
raise AgentExecutionException("Agent Failure - No agents present to select.")
# If it's the first selection and we have an initial agent, use it
if not self.has_selected and self.initial_agent is not None:
agent = self.initial_agent
else:
agent = await self.select_agent(agents, history)
self.has_selected = True
return agent
async def select_agent(
self,
agents: list[Agent],
history: list["ChatMessageContent"],
) -> Agent:
"""Determines which agent goes next. Override for custom logic.
By default, this fallback returns the first agent in the list.
"""
return agents[0]
@@ -0,0 +1,80 @@
# Copyright (c) Microsoft. All rights reserved.
import logging
import sys
if sys.version_info >= (3, 12):
from typing import override # pragma: no cover
else:
from typing_extensions import override # pragma: no cover
from typing import TYPE_CHECKING
from pydantic import PrivateAttr
from semantic_kernel.agents.strategies.selection.selection_strategy import SelectionStrategy
from semantic_kernel.utils.feature_stage_decorator import experimental
if TYPE_CHECKING:
from semantic_kernel.agents import Agent
from semantic_kernel.contents.chat_message_content import ChatMessageContent
logger: logging.Logger = logging.getLogger(__name__)
@experimental
class SequentialSelectionStrategy(SelectionStrategy):
"""Round-robin turn-taking strategy. Agent order is based on the order in which they joined."""
_index: int = PrivateAttr(default=-1)
def reset(self) -> None:
"""Reset selection to the initial/first agent."""
self._index = -1
def _increment_index(self, agent_count: int) -> None:
"""Increment the index in a circular manner."""
self._index = (self._index + 1) % agent_count
@override
async def select_agent(
self,
agents: list["Agent"],
history: list["ChatMessageContent"],
) -> "Agent":
"""Select the next agent in a round-robin fashion.
Args:
agents: The list of agents to select from.
history: The history of messages in the conversation.
Returns:
The agent who takes the next turn.
"""
if self._index >= len(agents):
self._index = -1
if (
self.has_selected
and self.initial_agent is not None
and len(agents) > 0
and agents[0] == self.initial_agent
and self._index < 0
):
# Avoid selecting the same agent twice in a row
self._increment_index(len(agents))
# Main index increment
self._increment_index(len(agents))
# Pick the agent
agent = agents[self._index]
logger.info(
"Selected agent at index %d (ID: %s, name: %s)",
self._index,
agent.id,
agent.name,
)
return agent
@@ -0,0 +1,52 @@
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from enum import Enum
from typing import TYPE_CHECKING
from pydantic import Field
from semantic_kernel.agents.strategies.termination.termination_strategy import TerminationStrategy
from semantic_kernel.contents.chat_message_content import ChatMessageContent
from semantic_kernel.kernel_pydantic import KernelBaseModel
from semantic_kernel.utils.feature_stage_decorator import experimental
if TYPE_CHECKING:
from semantic_kernel.agents.agent import Agent
@experimental
class AggregateTerminationCondition(str, Enum):
"""The condition for terminating the aggregation process."""
ALL = "All"
ANY = "Any"
@experimental
class AggregatorTerminationStrategy(KernelBaseModel):
"""A strategy that aggregates multiple termination strategies."""
strategies: list[TerminationStrategy]
condition: AggregateTerminationCondition = Field(default=AggregateTerminationCondition.ALL)
async def should_terminate_async(
self,
agent: "Agent",
history: list[ChatMessageContent],
) -> bool:
"""Check if the agent should terminate.
Args:
agent: The agent to check.
history: The history of messages in the conversation.
Returns:
True if the agent should terminate, False otherwise
"""
strategy_execution = [strategy.should_terminate(agent, history) for strategy in self.strategies]
results = await asyncio.gather(*strategy_execution)
if self.condition == AggregateTerminationCondition.ALL:
return all(results)
return any(results)
@@ -0,0 +1,31 @@
# Copyright (c) Microsoft. All rights reserved.
from typing import TYPE_CHECKING
from pydantic import Field
from semantic_kernel.agents.strategies.termination.termination_strategy import TerminationStrategy
from semantic_kernel.utils.feature_stage_decorator import experimental
if TYPE_CHECKING:
from semantic_kernel.agents.agent import Agent
from semantic_kernel.contents.chat_message_content import ChatMessageContent
@experimental
class DefaultTerminationStrategy(TerminationStrategy):
"""A default termination strategy that never terminates."""
maximum_iterations: int = Field(default=5, description="The maximum number of iterations to run the agent.")
async def should_agent_terminate(self, agent: "Agent", history: list["ChatMessageContent"]) -> bool:
"""Check if the agent should terminate.
Args:
agent: The agent to check.
history: The history of messages in the conversation.
Returns:
Defaults to False for the default strategy
"""
return False
@@ -0,0 +1,99 @@
# Copyright (c) Microsoft. All rights reserved.
import logging
from collections.abc import Callable
from inspect import isawaitable
from typing import TYPE_CHECKING, ClassVar
from pydantic import Field
from semantic_kernel.agents.strategies.termination.termination_strategy import TerminationStrategy
from semantic_kernel.contents.chat_message_content import ChatMessageContent
from semantic_kernel.contents.history_reducer.chat_history_reducer import ChatHistoryReducer
from semantic_kernel.functions.kernel_arguments import KernelArguments
from semantic_kernel.functions.kernel_function import KernelFunction
from semantic_kernel.kernel import Kernel
from semantic_kernel.utils.feature_stage_decorator import experimental
if TYPE_CHECKING:
from semantic_kernel.agents import Agent
logger: logging.Logger = logging.getLogger(__name__)
@experimental
class KernelFunctionTerminationStrategy(TerminationStrategy):
"""A termination strategy that uses a kernel function to determine termination."""
DEFAULT_AGENT_VARIABLE_NAME: ClassVar[str] = "_agent_"
DEFAULT_HISTORY_VARIABLE_NAME: ClassVar[str] = "_history_"
agent_variable_name: str | None = Field(default=DEFAULT_AGENT_VARIABLE_NAME)
history_variable_name: str | None = Field(default=DEFAULT_HISTORY_VARIABLE_NAME)
arguments: KernelArguments | None = None
function: KernelFunction
kernel: Kernel
result_parser: Callable[..., bool] = Field(default_factory=lambda: (lambda: True))
history_reducer: ChatHistoryReducer | None = None
async def should_agent_terminate(
self,
agent: "Agent",
history: list[ChatMessageContent],
) -> bool:
"""Check if the agent should terminate.
Args:
agent: The agent to check.
history: The history of messages in the conversation.
Returns:
True if the agent should terminate, False otherwise
"""
if self.history_reducer is not None:
self.history_reducer.messages = history
reduced_history = await self.history_reducer.reduce()
if reduced_history is not None:
history = reduced_history.messages
original_arguments = self.arguments or KernelArguments()
execution_settings = original_arguments.execution_settings or {}
messages = [message.to_dict(role_key="role", content_key="content") for message in history]
filtered_arguments = {
self.agent_variable_name: agent.name or agent.id,
self.history_variable_name: messages,
}
extracted_settings = {key: setting.model_dump() for key, setting in execution_settings.items()}
combined_arguments = {
**original_arguments,
**extracted_settings,
**{k: v for k, v in filtered_arguments.items()},
}
arguments = KernelArguments(
**combined_arguments,
)
logger.info(f"should_agent_terminate, function invoking: `{self.function.fully_qualified_name}`")
result = await self.function.invoke(kernel=self.kernel, arguments=arguments)
if result is None:
logger.info(
f"should_agent_terminate, function `{self.function.fully_qualified_name}` invoked with result `None`",
)
return False
logger.info(
f"should_agent_terminate, function `{self.function.fully_qualified_name}` "
f"invoked with result `{result.value if result.value else None}`",
)
result_parsed = self.result_parser(result)
if isawaitable(result_parsed):
result_parsed = await result_parsed
return result_parsed
@@ -0,0 +1,57 @@
# Copyright (c) Microsoft. All rights reserved.
import logging
from typing import TYPE_CHECKING
from pydantic import Field
from semantic_kernel.agents.agent import Agent
from semantic_kernel.kernel_pydantic import KernelBaseModel
from semantic_kernel.utils.feature_stage_decorator import experimental
if TYPE_CHECKING:
from semantic_kernel.contents.chat_message_content import ChatMessageContent
logger: logging.Logger = logging.getLogger(__name__)
@experimental
class TerminationStrategy(KernelBaseModel):
"""A strategy for determining when an agent should terminate."""
maximum_iterations: int = Field(default=99)
automatic_reset: bool = False
agents: list[Agent] = Field(default_factory=list)
async def should_agent_terminate(self, agent: "Agent", history: list["ChatMessageContent"]) -> bool:
"""Check if the agent should terminate.
Args:
agent: The agent to check.
history: The history of messages in the conversation.
Returns:
True if the agent should terminate, False otherwise
"""
raise NotImplementedError("Subclasses should implement this method")
async def should_terminate(self, agent: "Agent", history: list["ChatMessageContent"]) -> bool:
"""Check if the agent should terminate.
Args:
agent: The agent to check.
history: The history of messages in the conversation.
Returns:
True if the agent should terminate, False otherwise
"""
logger.info(f"Evaluating termination criteria for {agent.id}")
if self.agents and not any(a.id == agent.id for a in self.agents):
logger.info(f"Agent {agent.id} is out of scope")
return False
should_terminate = await self.should_agent_terminate(agent, history)
logger.info(f"Evaluated criteria for {agent.id}, should terminate: {should_terminate}")
return should_terminate