-
Notifications
You must be signed in to change notification settings - Fork 1k
Python: Added custom args and thread object to ai_function kwargs #2769
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
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
f8e479b
Added an example of using kwargs in ai_function
dmytrostruk 521e27c
Added thread object to ai_function kwargs
dmytrostruk db2ddff
Updated docs
dmytrostruk c610983
Small fix
dmytrostruk b28f6ef
Added thread parameter filtering
dmytrostruk 7b1abb0
Merge branch 'main' into ai-function-args
dmytrostruk File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
53 changes: 53 additions & 0 deletions
53
python/samples/getting_started/tools/ai_function_with_kwargs.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| # Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| import asyncio | ||
| from typing import Annotated, Any | ||
|
|
||
| from agent_framework import ai_function | ||
| from agent_framework.openai import OpenAIResponsesClient | ||
| from pydantic import Field | ||
|
|
||
| """ | ||
| AI Function with kwargs Example | ||
|
|
||
| This example demonstrates how to inject custom keyword arguments (kwargs) into an AI function | ||
| from the agent's run method, without exposing them to the AI model. | ||
|
|
||
| This is useful for passing runtime information like access tokens, user IDs, or | ||
| request-specific context that the tool needs but the model shouldn't know about | ||
| or provide. | ||
| """ | ||
|
|
||
|
|
||
| # Define the function tool with **kwargs to accept injected arguments | ||
| @ai_function | ||
| def get_weather( | ||
| location: Annotated[str, Field(description="The location to get the weather for.")], | ||
| **kwargs: Any, | ||
| ) -> str: | ||
| """Get the weather for a given location.""" | ||
| # Extract the injected argument from kwargs | ||
| user_id = kwargs.get("user_id", "unknown") | ||
|
|
||
| # Simulate using the user_id for logging or personalization | ||
| print(f"Getting weather for user: {user_id}") | ||
|
|
||
| return f"The weather in {location} is cloudy with a high of 15°C." | ||
|
|
||
|
|
||
| async def main() -> None: | ||
| agent = OpenAIResponsesClient().create_agent( | ||
| name="WeatherAgent", | ||
| instructions="You are a helpful weather assistant.", | ||
| tools=[get_weather], | ||
| ) | ||
|
|
||
| # Pass the injected argument when running the agent | ||
| # The 'user_id' kwarg will be passed down to the tool execution via **kwargs | ||
| response = await agent.run("What is the weather like in Amsterdam?", user_id="user_123") | ||
|
|
||
| print(f"Agent: {response.text}") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| asyncio.run(main()) |
52 changes: 52 additions & 0 deletions
52
python/samples/getting_started/tools/ai_function_with_thread_injection.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| # Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| import asyncio | ||
| from typing import Annotated, Any | ||
|
|
||
| from agent_framework import AgentThread, ai_function | ||
| from agent_framework.openai import OpenAIChatClient | ||
| from pydantic import Field | ||
|
|
||
| """ | ||
| AI Function with Thread Injection Example | ||
|
|
||
| This example demonstrates the behavior when passing 'thread' to agent.run() | ||
| and accessing that thread in AI function. | ||
| """ | ||
|
|
||
|
|
||
| # Define the function tool with **kwargs | ||
| @ai_function | ||
| async def get_weather( | ||
| location: Annotated[str, Field(description="The location to get the weather for.")], | ||
| **kwargs: Any, | ||
| ) -> str: | ||
| """Get the weather for a given location.""" | ||
| # Get thread object from kwargs | ||
| thread = kwargs.get("thread") | ||
| if thread and isinstance(thread, AgentThread): | ||
| if thread.message_store: | ||
| messages = await thread.message_store.list_messages() | ||
| print(f"Thread contains {len(messages)} messages.") | ||
| elif thread.service_thread_id: | ||
| print(f"Thread ID: {thread.service_thread_id}.") | ||
|
|
||
| return f"The weather in {location} is cloudy." | ||
|
|
||
|
|
||
| async def main() -> None: | ||
| agent = OpenAIChatClient().create_agent( | ||
| name="WeatherAgent", instructions="You are a helpful weather assistant.", tools=[get_weather] | ||
| ) | ||
|
|
||
| # Create a thread | ||
| thread = agent.get_new_thread() | ||
|
|
||
| # Run the agent with the thread | ||
| print(f"Agent: {await agent.run('What is the weather in London?', thread=thread)}") | ||
| print(f"Agent: {await agent.run('What is the weather in Amsterdam?', thread=thread)}") | ||
| print(f"Agent: {await agent.run('What cities did I ask about?', thread=thread)}") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| asyncio.run(main()) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.