Skip to content

Python: Fix agent samples #11278

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 1, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,9 @@
import asyncio
import logging

from semantic_kernel.agents import (
ChatCompletionAgent,
ChatHistoryAgentThread,
)
from semantic_kernel.agents import ChatCompletionAgent, ChatHistoryAgentThread
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
from semantic_kernel.contents import (
ChatHistorySummarizationReducer,
)
from semantic_kernel.contents import ChatHistorySummarizationReducer

"""
The following sample demonstrates how to implement a truncation chat
Expand Down Expand Up @@ -55,9 +50,9 @@ async def main():
# Attempt reduction
is_reduced = await thread.reduce()
if is_reduced:
print(f"@ History reduced to {len(thread.messages)} messages.")
print(f"@ History reduced to {len(thread)} messages.")

print(f"@ Message Count: {len(thread.messages)}\n")
print(f"@ Message Count: {len(thread)}\n")

# If reduced, print summary if present
if is_reduced:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,10 @@ async def get_response(
raise AgentInvokeException("No response from agent.")

response = responses[-1]
await thread.on_new_message(response)
if response.role != AuthorRole.TOOL:
# Tool messages will be automatically added to the chat history by the auto function invocation loop,
# thus it's not considered a new message.
await thread.on_new_message(response)
return AgentResponseItem(message=response, thread=thread)

@trace_agent_invocation
Expand Down Expand Up @@ -311,7 +314,10 @@ async def invoke(
chat_history = await thread.get_messages()

async for response in self._inner_invoke(thread, chat_history, arguments, kernel, **kwargs):
await thread.on_new_message(response)
if response.role != AuthorRole.TOOL:
# Tool messages will be automatically added to the chat history by the auto function invocation loop,
# thus it's not considered a new message.
await thread.on_new_message(response)
yield AgentResponseItem(message=response, thread=thread)

@trace_agent_invocation
Expand Down Expand Up @@ -399,6 +405,8 @@ async def invoke_stream(

await self._capture_mutated_messages(agent_chat_history, message_count_before_completion, thread)
if role != AuthorRole.TOOL:
# Tool messages will be automatically added to the chat history by the auto function invocation loop,
# thus it's not considered a new message.
await thread.on_new_message(
ChatMessageContent(
role=role if role else AuthorRole.ASSISTANT, content="".join(response_builder), name=self.name
Expand Down
21 changes: 9 additions & 12 deletions python/semantic_kernel/core_plugins/math_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,30 +19,27 @@ class MathPlugin:
@kernel_function(name="Add")
def add(
self,
input: Annotated[int, "the first number to add"],
amount: Annotated[int, "the second number to add"],
) -> Annotated[int, "the output is a number"]:
input: Annotated[int | str, "The first number to add"],
amount: Annotated[int | str, "The second number to add"],
) -> Annotated[int, "The result"]:
"""Returns the Addition result of the values provided."""
if isinstance(input, str):
input = int(input)
if isinstance(amount, str):
amount = int(amount)
return MathPlugin.add_or_subtract(input, amount, add=True)

return input + amount

@kernel_function(name="Subtract")
def subtract(
self,
input: Annotated[int, "the first number"],
amount: Annotated[int, "the number to subtract"],
) -> int:
input: Annotated[int | str, "The number to subtract from"],
amount: Annotated[int | str, "The number to subtract"],
) -> Annotated[int, "The result"]:
"""Returns the difference of numbers provided."""
if isinstance(input, str):
input = int(input)
if isinstance(amount, str):
amount = int(amount)
return MathPlugin.add_or_subtract(input, amount, add=False)

@staticmethod
def add_or_subtract(input: int, amount: int, add: bool) -> int:
"""Helper function to perform addition or subtraction based on the add flag."""
return input + amount if add else input - amount
return input - amount
Loading