Skip to content

Python: Bug fix for azure ai agent truncate strategy. Add sample. #11503

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 3 commits into from
Apr 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
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
1 change: 1 addition & 0 deletions python/samples/concepts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
- [Azure AI Agent Message Callback](./agents/azure_ai_agent/azure_ai_agent_message_callback.py)
- [Azure AI Agent Streaming](./agents/azure_ai_agent/azure_ai_agent_streaming.py)
- [Azure AI Agent Structured Outputs](./agents/azure_ai_agent/azure_ai_agent_structured_outputs.py)
- [Azure AI Agent Truncation Strategy](./agents/azure_ai_agent/azure_ai_agent_truncation_strategy.py)

#### [Bedrock Agent](../../semantic_kernel/agents/bedrock/bedrock_agent.py)

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# Copyright (c) Microsoft. All rights reserved.

import asyncio

from azure.ai.projects.models import TruncationObject
from azure.identity.aio import DefaultAzureCredential

from semantic_kernel.agents import (
AzureAIAgent,
AzureAIAgentSettings,
AzureAIAgentThread,
)

"""
The following sample demonstrates how to create an Azure AI Agent Agent
and configure a truncation strategy for the agent.
"""

USER_INPUTS = [
"Why is the sky blue?",
"What is the speed of light?",
"What have we been talking about?",
]


async def main() -> None:
ai_agent_settings = AzureAIAgentSettings.create()

async with (
DefaultAzureCredential() as creds,
AzureAIAgent.create_client(
credential=creds,
conn_str=ai_agent_settings.project_connection_string.get_secret_value(),
) as client,
):
# Create the agent definition
agent_definition = await client.agents.create_agent(
model=ai_agent_settings.model_deployment_name,
name="TruncateAgent",
instructions="You are a helpful assistant that answers user questions in one sentence.",
)

# Create the AzureAI Agent
agent = AzureAIAgent(
client=client,
definition=agent_definition,
)

thread: AzureAIAgentThread | None = None

# Options are "auto" or "last_messages"
# If using "last_messages", specify the number of messages to keep with `last_messages` kwarg
truncation_strategy = TruncationObject(type="last_messages", last_messages=2)

try:
for user_input in USER_INPUTS:
print(f"# User: {user_input}")
# 4. Invoke the agent with the specified message for response
response = await agent.get_response(
messages=user_input, thread=thread, truncation_strategy=truncation_strategy
)
print(f"# {response.name}: {response}")
thread = response.thread
finally:
# 6. Cleanup: Delete the thread and agent
await thread.delete() if thread else None
await client.agents.delete_agent(agent.id)

"""
Sample Output:

# User: Why is the sky blue?
# TruncateAgent: The sky appears blue because molecules in the Earth's atmosphere scatter sunlight in all
directions, and blue light is scattered more than other colors due to its shorter wavelength.
# User: What is the speed of light?
# TruncateAgent: The speed of light in a vacuum is approximately 299,792,458 meters per second
(or about 186,282 miles per second).
# User: What have we been talking about?
# TruncateAgent: I'm sorry, but I don't have access to previous interactions. Could you remind me what
we've been discussing?
"""


if __name__ == "__main__":
asyncio.run(main())
Original file line number Diff line number Diff line change
Expand Up @@ -725,7 +725,7 @@ def _merge_options(
def _generate_options(cls: type[_T], **kwargs: Any) -> dict[str, Any]:
"""Generate a dictionary of options that can be passed directly to create_run."""
merged = cls._merge_options(**kwargs)
trunc_count = merged.get("truncation_message_count", None)
truncation_strategy = merged.get("truncation_strategy", None)
max_completion_tokens = merged.get("max_completion_tokens", None)
max_prompt_tokens = merged.get("max_prompt_tokens", None)
parallel_tool_calls = merged.get("parallel_tool_calls_enabled", None)
Expand All @@ -735,7 +735,7 @@ def _generate_options(cls: type[_T], **kwargs: Any) -> dict[str, Any]:
"top_p": merged.get("top_p"),
"response_format": merged.get("response_format"),
"temperature": merged.get("temperature"),
"truncation_strategy": trunc_count,
"truncation_strategy": truncation_strategy,
"metadata": merged.get("metadata"),
"max_completion_tokens": max_completion_tokens,
"max_prompt_tokens": max_prompt_tokens,
Expand Down
Loading