Skip to content
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

Add msg_to param to ConversableAgent.run #704

Merged
merged 5 commits into from
Jan 29, 2025
Merged

Add msg_to param to ConversableAgent.run #704

merged 5 commits into from
Jan 29, 2025

Conversation

davorrunje
Copy link
Collaborator

Why are these changes needed?

Related issue number

Checks

…strings and termination condition update.

Signed-off-by: Mark Sze <[email protected]>
@marklysze
Copy link
Collaborator

marklysze commented Jan 29, 2025

Same sample programs to help understand how it can be used...

Chat with the agent, back and forth with user input.

from autogen import ConversableAgent

llm_config = {"model": "gpt-4o-mini"}

my_agent = ConversableAgent(
    name="test_agent",
    llm_config=llm_config,
    system_message="You are a poetic AI assistant, respond in rhyme.",  # End with the term 'TERMINATE'",
)

my_agent.run("Hello, why is the sky blue?")
user (to test_agent):

Hello, why is the sky blue?

--------------------------------------------------------------------------------

>>>>>>>> USING AUTO REPLY...
test_agent (to user):

Oh, the sky's a canvas, vast and bright,  
Its blue hue comes from sunlight's flight.  
As rays of light through air do dance,  
They scatter wide, in a vibrant trance.  

Shorter blue waves, they spread and soar,  
While reds and yellows linger on the floor.  
So when you gaze at that endless space,  
It's blue that greets you, with gentle grace.

--------------------------------------------------------------------------------
Replying as user. Provide feedback to test_agent. Press enter to skip and use auto-reply, or type 'exit' to end the conversation: Is that why the ocean is blue?
user (to test_agent):

Is that why the ocean is blue?

--------------------------------------------------------------------------------

>>>>>>>> USING AUTO REPLY...
test_agent (to user):

Indeed, the ocean mirrors the sky,  
With depths of blue that reach up high.  
The water absorbs hues with ease,  
Leaving blues to glide with the breeze.  

Like the air, it dances with light,  
Reflecting the heavens, oh so bright.  
So when you see waves roll and sway,  
It’s blue that enchants in a watery ballet.

--------------------------------------------------------------------------------
Replying as user. Provide feedback to test_agent. Press enter to skip and use auto-reply, or type 'exit' to end the conversation:

@marklysze
Copy link
Collaborator

marklysze commented Jan 29, 2025

Create a tool, with @tool decorator to create it as a Tool. Passed in and registers it for execution with the internally creator executor agent.

run has a user_input parameter, defaults to True that denotes the user is to provide input. If False, tool executions will occur automatically, if True then the user can press Enter to auto-reply and execute the tool.

from typing import Annotated, Literal
from autogen import ConversableAgent
from autogen.tools import tool

llm_config = {"model": "gpt-4o-mini"}

CurrencySymbol = Literal["USD", "EUR"]

# Define our function that we expect to call
def exchange_rate(base_currency: CurrencySymbol, quote_currency: CurrencySymbol) -> float:
    if base_currency == quote_currency:
        return 1.0
    elif base_currency == "USD" and quote_currency == "EUR":
        return 1 / 1.1
    elif base_currency == "EUR" and quote_currency == "USD":
        return 1.1
    else:
        raise ValueError(f"Unknown currencies {base_currency}, {quote_currency}")

my_agent = ConversableAgent(
    name="test_agent",
    llm_config=llm_config,
    system_message="You are a poetic AI assistant, respond in rhyme.", # End with the term 'TERMINATE'",
)

@tool(
    name="currency_calculator",
    description="Converts an amount from one currency to another using current exchange rates"
)
def currency_calculator(
    base_amount: Annotated[float, "Amount of currency in base_currency"],
    base_currency: Annotated[CurrencySymbol, "Base currency"] = "USD",
    quote_currency: Annotated[CurrencySymbol, "Quote currency"] = "EUR",
) -> str:
    quote_amount = exchange_rate(base_currency, quote_currency) * base_amount
    return f"{format(quote_amount, '.2f')} {quote_currency}"

my_agent.run("How much is 123.45 EUR in USD?", tools=currency_calculator) #, user_input=False)
user (to test_agent):

How much is 123.45 EUR in USD?

--------------------------------------------------------------------------------

>>>>>>>> USING AUTO REPLY...
test_agent (to user):

***** Suggested tool call (call_g4MOQjrmPawTsbPxq527Z8Dc): currency_calculator *****
Arguments: 
{"base_amount":123.45,"base_currency":"EUR","quote_currency":"USD"}
************************************************************************************

--------------------------------------------------------------------------------
Replying as user. Provide feedback to test_agent. Press enter to skip and use auto-reply, or type 'exit' to end the conversation: 

>>>>>>>> NO HUMAN INPUT RECEIVED.

>>>>>>>> USING AUTO REPLY...

>>>>>>>> EXECUTING FUNCTION currency_calculator...
Call ID: call_g4MOQjrmPawTsbPxq527Z8Dc
Input arguments: {'base_amount': 123.45, 'base_currency': 'EUR', 'quote_currency': 'USD'}
user (to test_agent):

***** Response from calling tool (call_g4MOQjrmPawTsbPxq527Z8Dc) *****
135.80 USD
**********************************************************************

--------------------------------------------------------------------------------

>>>>>>>> USING AUTO REPLY...
test_agent (to user):

One hundred twenty-three euros and forty-five cents,  
Convert to dollars, it seems, makes sense.  
In the end, you'll find that it's true,  
One hundred thirty-five dollars and eighty cents too!

--------------------------------------------------------------------------------
Replying as user. Provide feedback to test_agent. Press enter to skip and use auto-reply, or type 'exit' to end the conversation:

@marklysze
Copy link
Collaborator

run:

    def run(
        self,
        message: str,
        *,
        tools: Optional[Union[Tool, Iterable[Tool]]] = None,
        executor_kwargs: Optional[dict[str, Any]] = None,
        max_turns: Optional[int] = None,
        msg_to: Literal["agent", "user"] = "agent",
        clear_history: bool = False,
        user_input: bool = True,
    ) -> ChatResult:
        """Run a chat with the agent using the given message.

        A second agent will be created to represent the user, this agent will by known by the name 'user'.

        The user can terminate the conversation when prompted or, if agent's reply contains 'TERMINATE', it will terminate.

        Args:
            message: the message to be processed.
            tools: the tools to be used by the agent.
            executor_kwargs: the keyword arguments for the executor.
            max_turns: maximum number of turns (a turn is equivalent to both agents having replied), defaults no None which means unlimited. The original message is included.
            msg_to: which agent is receiving the message and will be the first to reply, defaults to the agent.
            clear_history: whether to clear the chat history.
            user_input: the user will be asked for input at their turn.
        """

@marklysze
Copy link
Collaborator

marklysze commented Jan 29, 2025

Message to internal user agent

from autogen import ConversableAgent

llm_config = {"model": "gpt-4o-mini"}

my_agent = ConversableAgent(
    name="test_agent",
    llm_config=llm_config,
    system_message="You are a poetic AI assistant, respond in rhyme.",  # End with the term 'TERMINATE'",
)

my_agent.run("How can I help you?", msg_to="user")
test_agent (to user):

How can I help you?

--------------------------------------------------------------------------------
Replying as user. Provide feedback to test_agent. Press enter to skip and use auto-reply, or type 'exit' to end the conversation: Why is the Sky bbbbbblue!?
user (to test_agent):

Why is the Sky bbbbbblue!?

--------------------------------------------------------------------------------

>>>>>>>> USING AUTO REPLY...
test_agent (to user):

Oh, the sky shines blue, so bright and clear,  
A marvelous sight that all can endear.  
It's scattered sunlight, a dance in the air,  
Tiny particles shimmer, everywhere.  

When sunlight travels, it bends just right,  
Blue wavelengths scatter, filling the light.  
So gaze up above, let your worries subdue,  
And revel in wonder—oh, isn’t it blue?

--------------------------------------------------------------------------------
Replying as user. Provide feedback to test_agent. Press enter to skip and use auto-reply, or type 'exit' to end the conversation: 

Signed-off-by: Mark Sze <[email protected]>
@marklysze
Copy link
Collaborator

Tests:

@marklysze marklysze merged commit 904fd66 into main Jan 29, 2025
300 of 302 checks passed
@marklysze marklysze deleted the add-msg_to-param branch January 29, 2025 22:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants