Commit Graph

42 Commits

Author SHA1 Message Date
Eric Zhu 7615c7b83b
Rename to use BaseChatMessage and BaseAgentEvent. Bring back union types. (#6144)
Rename the `ChatMessage` and `AgentEvent` base classes to `BaseChatMessage` and `BaseAgentEvent`. 

Bring back the `ChatMessage` and `AgentEvent` as union of built-in concrete types to avoid breaking existing applications that depends on Pydantic serialization. 

Why?

Many existing code uses containers like this:

```python
class AppMessage(BaseModel):
   name: str
   message: ChatMessage 

# Serialization is this:
m = AppMessage(...)
m.model_dump_json()

# Fields like HandoffMessage.target will be lost because it is now treated as a base class without content or target fields.
```

The assumption on `ChatMessage` or `AgentEvent` to be a union of concrete types could be in many existing code bases. So this PR brings back the union types, while keep method type hints such as those on `on_messages` to use the `BaseChatMessage` and `BaseAgentEvent` base classes for flexibility.
2025-03-30 09:34:40 -07:00
Eric Zhu 025490a1bd
Use class hierarchy to organize AgentChat message types and introduce StructuredMessage type (#5998)
This PR refactored `AgentEvent` and `ChatMessage` union types to
abstract base classes. This allows for user-defined message types that
subclass one of the base classes to be used in AgentChat.

To support a unified interface for working with the messages, the base
classes added abstract methods for:
- Convert content to string
- Convert content to a `UserMessage` for model client
- Convert content for rendering in console.
- Dump into a dictionary
- Load and create a new instance from a dictionary

This way, all agents such as `AssistantAgent` and `SocietyOfMindAgent`
can utilize the unified interface to work with any built-in and
user-defined message type.

This PR also introduces a new message type, `StructuredMessage` for
AgentChat (Resolves #5131), which is a generic type that requires a
user-specified content type.

You can create a `StructuredMessage` as follow:

```python

class MessageType(BaseModel):
  data: str
  references: List[str]

message = StructuredMessage[MessageType](content=MessageType(data="data", references=["a", "b"]), source="user")

# message.content is of type `MessageType`. 
```

This PR addresses the receving side of this message type. To produce
this message type from `AssistantAgent`, the work continue in #5934.

Added unit tests to verify this message type works with agents and
teams.
2025-03-26 16:19:52 -07:00
Kurok1 2e2a314f7e
Take the output of the tool and use that to create the HandoffMessage (#6073)
Take the output of the tool and use that to create the HandoffMessage.
[discussion is
here](https://github.com/microsoft/autogen/discussions/6067#discussion-8117177)

Supports agents to carry specific instructions when performing handoff
operations

---------

Co-authored-by: Eric Zhu <ekzhu@users.noreply.github.com>
2025-03-25 21:38:07 +00:00
jspv fc2c9978fd
Add model_context property to AssistantAgent (#6072)
AssistantAgent initiation allows one to pass in a model_context, but
there isn't a "public: way to get the existing model_context created by
default.
2025-03-22 20:21:29 -07:00
Eric Zhu aba41d74d3
feat: add structured output to model clients (#5936) 2025-03-15 07:58:13 -07:00
Eric Zhu 3a1108a575
fix: make sure system message is present in reflection call (#5926)
Resolves #5919
2025-03-13 21:29:46 +00:00
Eric Zhu 7e5c1154cf
Support for external agent runtime in AgentChat (#5843)
Resolves #4075

1. Introduce custom runtime parameter for all AgentChat teams
(RoundRobinGroupChat, SelectorGroupChat, etc.). This is done by making
sure each team's topics are isolated from other teams, and decoupling
state from agent identities. Also, I removed the closure agent from the
BaseGroupChat and use the group chat manager agent to relay messages to
the output message queue.
2. Added unit tests to test scenarios with custom runtimes by using
pytest fixture
3. Refactored existing unit tests to use ReplayChatCompletionClient with
a few improvements to the client.
4. Fix a one-liner bug in AssistantAgent that caused deserialized agent
to have handoffs.

How to use it? 

```python
import asyncio
from autogen_core import SingleThreadedAgentRuntime
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_agentchat.conditions import TextMentionTermination
from autogen_ext.models.replay import ReplayChatCompletionClient

async def main() -> None:
    # Create a runtime
    runtime = SingleThreadedAgentRuntime()
    runtime.start()

    # Create a model client.
    model_client = ReplayChatCompletionClient(
        ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
    )

    # Create agents
    agent1 = AssistantAgent("assistant1", model_client=model_client, system_message="You are a helpful assistant.")
    agent2 = AssistantAgent("assistant2", model_client=model_client, system_message="You are a helpful assistant.")

    # Create a termination condition
    termination_condition = TextMentionTermination("10", sources=["assistant1", "assistant2"])

    # Create a team
    team = RoundRobinGroupChat([agent1, agent2], runtime=runtime, termination_condition=termination_condition)

    # Run the team
    stream = team.run_stream(task="Count to 10.")
    async for message in stream:
        print(message)
    
    # Save the state.
    state = await team.save_state()

    # Load the state to an existing team.
    await team.load_state(state)

    # Run the team again
    model_client.reset()
    stream = team.run_stream(task="Count to 10.")
    async for message in stream:
        print(message)

    # Create a new team, with the same agent names.
    agent3 = AssistantAgent("assistant1", model_client=model_client, system_message="You are a helpful assistant.")
    agent4 = AssistantAgent("assistant2", model_client=model_client, system_message="You are a helpful assistant.")
    new_team = RoundRobinGroupChat([agent3, agent4], runtime=runtime, termination_condition=termination_condition)

    # Load the state to the new team.
    await new_team.load_state(state)

    # Run the new team
    model_client.reset()
    new_stream = new_team.run_stream(task="Count to 10.")
    async for message in new_stream:
        print(message)
    
    # Stop the runtime
    await runtime.stop()

asyncio.run(main())
```

TODOs as future PRs:
1. Documentation.
2. How to handle errors in custom runtime when the agent has exception?

---------

Co-authored-by: Ryan Sweet <rysweet@microsoft.com>
2025-03-06 10:32:52 -08:00
Leonardo Pinheiro 906b09e451
fix: Update SKChatCompletionAdapter message conversion (#5749)
<!-- Thank you for your contribution! Please review
https://microsoft.github.io/autogen/docs/Contribute before opening a
pull request. -->

<!-- Please add a reviewer to the assignee section when you create a PR.
If you don't have the access to it, we will shortly find a reviewer and
assign them to your PR. -->

## Why are these changes needed?

<!-- Please give a short summary of the change and the problem this
solves. -->

The PR introduces two changes.

The first change is adding a name attribute to
`FunctionExecutionResult`. The motivation is that semantic kernel
requires it for their function result interface and it seemed like a
easy modification as `FunctionExecutionResult` is always created in the
context of a `FunctionCall` which will contain the name. I'm unsure if
there was a motivation to keep it out but this change makes it easier to
trace which tool the result refers to and also increases api
compatibility with SK.

The second change is an update to how messages are mapped from autogen
to semantic kernel, which includes an update/fix in the processing of
function results.

## Related issue number

<!-- For example: "Closes #1234" -->

Related to #5675 but wont fix the underlying issue of anthropic
requiring tools during AssistantAgent reflection.

## Checks

- [ ] I've included any doc changes needed for
<https://microsoft.github.io/autogen/>. See
<https://github.com/microsoft/autogen/blob/main/CONTRIBUTING.md> to
build and test documentation locally.
- [ ] I've added tests (if relevant) corresponding to the changes
introduced in this PR.
- [ ] I've made sure all auto checks have passed.

---------

Co-authored-by: Leonardo Pinheiro <lpinheiro@microsoft.com>
2025-03-03 23:05:54 +00:00
Leonardo Pinheiro a02d08a8ef
Refactor AssistantAgent on_message_stream (#5642)
<!-- Thank you for your contribution! Please review
https://microsoft.github.io/autogen/docs/Contribute before opening a
pull request. -->

<!-- Please add a reviewer to the assignee section when you create a PR.
If you don't have the access to it, we will shortly find a reviewer and
assign them to your PR. -->

## Why are these changes needed?

<!-- Please give a short summary of the change and the problem this
solves. -->

I'm unsure if everyone will agree, but I started to look into adding new
logic and found that refactoring into smaller functions would make it
more maintainable.

There is no change in functionality, only a breakdown into smaller
methods to make it more modular and improve readability. There is a lot
of logic in the method and this refactor breaks it down into context
management, llm call and result processing.

## Related issue number

<!-- For example: "Closes #1234" -->

## Checks

- [ ] I've included any doc changes needed for
<https://microsoft.github.io/autogen/>. See
<https://github.com/microsoft/autogen/blob/main/CONTRIBUTING.md> to
build and test documentation locally.
- [ ] I've added tests (if relevant) corresponding to the changes
introduced in this PR.
- [ ] I've made sure all auto checks have passed.

---------

Co-authored-by: Leonardo Pinheiro <lpinheiro@microsoft.com>
2025-02-25 19:11:35 +00:00
Eric Zhu 0360ab9715
doc: Enrich AssistantAgent API documentation with usage examples. (#5653)
Resolves #5562
2025-02-24 10:57:34 -05:00
Eric Zhu 7784f44ea6
feat: Add thought process handling in tool calls and expose ThoughtEvent through stream in AgentChat (#5500)
Resolves #5192

Test

```python
import asyncio
import os
from random import randint
from typing import List
from autogen_core.tools import BaseTool, FunctionTool
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.ui import Console

async def get_current_time(city: str) -> str:
    return f"The current time in {city} is {randint(0, 23)}:{randint(0, 59)}."

tools: List[BaseTool] = [
    FunctionTool(
        get_current_time,
        name="get_current_time",
        description="Get current time for a city.",
    ),
]

model_client = OpenAIChatCompletionClient(
    model="anthropic/claude-3.5-haiku-20241022",
    base_url="https://openrouter.ai/api/v1",
    api_key=os.environ["OPENROUTER_API_KEY"],
    model_info={
        "family": "claude-3.5-haiku",
        "function_calling": True,
        "vision": False,
        "json_output": False,
    }
)

agent = AssistantAgent(
    name="Agent",
    model_client=model_client,
    tools=tools,
    system_message= "You are an assistant with some tools that can be used to answer some questions",
)

async def main() -> None:
    await Console(agent.run_stream(task="What is current time of Paris and Toronto?"))

asyncio.run(main())
```

```
---------- user ----------
What is current time of Paris and Toronto?
---------- Agent ----------
I'll help you find the current time for Paris and Toronto by using the get_current_time function for each city.
---------- Agent ----------
[FunctionCall(id='toolu_01NwP3fNAwcYKn1x656Dq9xW', arguments='{"city": "Paris"}', name='get_current_time'), FunctionCall(id='toolu_018d4cWSy3TxXhjgmLYFrfRt', arguments='{"city": "Toronto"}', name='get_current_time')]
---------- Agent ----------
[FunctionExecutionResult(content='The current time in Paris is 1:10.', call_id='toolu_01NwP3fNAwcYKn1x656Dq9xW', is_error=False), FunctionExecutionResult(content='The current time in Toronto is 7:28.', call_id='toolu_018d4cWSy3TxXhjgmLYFrfRt', is_error=False)]
---------- Agent ----------
The current time in Paris is 1:10.
The current time in Toronto is 7:28.
```

---------

Co-authored-by: Jack Gerrits <jackgerrits@users.noreply.github.com>
2025-02-21 13:58:32 -08:00
Eric Zhu e7a3c78594
fix: Address tool call execution scenario when model produces empty tool call ids (#5509)
Resolves #5508
2025-02-13 23:11:44 -08:00
wistuba 7a772a2fcd
feat: add indictor for tool failure to FunctionExecutionResult (#5428)
Some LLMs recieve an explicit signal about tool use failures. 

Closes #5273

Co-authored-by: Eric Zhu <ekzhu@users.noreply.github.com>
2025-02-09 21:57:50 -08:00
Eitan Yarmush 172a16a615
Memory component base (#5380)
<!-- Thank you for your contribution! Please review
https://microsoft.github.io/autogen/docs/Contribute before opening a
pull request. -->

<!-- Please add a reviewer to the assignee section when you create a PR.
If you don't have the access to it, we will shortly find a reviewer and
assign them to your PR. -->

## Why are these changes needed?

Currently the way to accomplish RAG behavior with agent chat,
specifically assistant agents is with the memory interface, however
there is no way to configure it via the declarative API.

<!-- Please give a short summary of the change and the problem this
solves. -->

## Related issue number

<!-- For example: "Closes #1234" -->

## Checks

- [ ] I've included any doc changes needed for
https://microsoft.github.io/autogen/. See
https://microsoft.github.io/autogen/docs/Contribute#documentation to
build and test documentation locally.
- [ ] I've added tests (if relevant) corresponding to the changes
introduced in this PR.
- [ ] I've made sure all auto checks have passed.

---------

Co-authored-by: Victor Dibia <chuvidi2003@gmail.com>
2025-02-05 16:07:27 -08:00
afourney 517e3f000e
Assistant agent drop images when not provided with a vision-capable model. (#5351)
Allow AssistantAgent to drop images when not equipped with a multi-modal model.

Adds a corresponding utility function, which can be used in autogen-ext and teams, to accomplish the same.
2025-02-04 14:55:04 +00:00
Eric Zhu 225eb9d0b2
feat: introduce ModelClientStreamingChunkEvent for streaming model output and update handling in agents and console (#5208)
Resolves #3983

* introduce `model_client_stream` parameter in `AssistantAgent` to
enable token-level streaming output.
* introduce `ModelClientStreamingChunkEvent` as a type of `AgentEvent`
to pass the streaming chunks to the application via `run_stream` and
`on_messages_stream`. Although this will not affect the inner messages
list in the final `Response` or `TaskResult`.
* handle this new message type in `Console`.
2025-01-29 02:49:02 +00:00
Victor Dibia 67029853ec
make AssistantAgent and Handoff use BaseTool (#5193)
<!-- Thank you for your contribution! Please review
https://microsoft.github.io/autogen/docs/Contribute before opening a
pull request. -->

<!-- Please add a reviewer to the assignee section when you create a PR.
If you don't have the access to it, we will shortly find a reviewer and
assign them to your PR. -->

## Why are these changes needed?

Make AssistantAgent and Handoff use BaseTool.  
This ensures that they can be made declarative/serialized

<!-- Please give a short summary of the change and the problem this
solves. -->

## Related issue number

<!-- For example: "Closes #1234" -->

## Checks

- [ ] I've included any doc changes needed for
https://microsoft.github.io/autogen/. See
https://microsoft.github.io/autogen/docs/Contribute#documentation to
build and test documentation locally.
- [ ] I've added tests (if relevant) corresponding to the changes
introduced in this PR.
- [ ] I've made sure all auto checks have passed.
2025-01-25 12:04:05 -08:00
Eric Zhu 8643ff6e40
Pass context between AssistantAgent for handoffs (#5084)
* Pass context between AssistantAgent for handoffs

* Add parallel tool call test

---------

Co-authored-by: Jack Gerrits <jackgerrits@users.noreply.github.com>
2025-01-17 23:39:57 +00:00
Victor Dibia c2a43e84a2
Declarative BaseChat Agents (#5055)
* v1, make assistant agent declarative

* make head tail context declarative

* update and formatting

* update assistant, format updates

* make websurfer declarative

* update formatting

* move declarative docs to advanced section

* remove tools until implemented

* minor updates to termination conditions

* update docs
2025-01-16 22:29:40 -08:00
Victor Dibia abbdbb2f87
Memory Interface in AgentChat (#4438)
* initial base memroy impl

* update, add example with chromadb

* include mimetype consideration

* add transform method

* update to address feedback, will update after 4681 is merged

* update memory impl,

* remove chroma db, typing fixes

* format, add test

* update uv lock

* update docs

* format updates

* update notebook

* add memoryqueryevent message, yield message for observability.

* minor fixes, make score optional/none

* Update python/packages/autogen-agentchat/src/autogen_agentchat/agents/_assistant_agent.py

Co-authored-by: Eric Zhu <ekzhu@users.noreply.github.com>

* update tests to improve cov

* refactor, move memory to core.

* format fixxes

* format updates

* format updates

* fix azure notebook import, other fixes

* update notebook, support str query in Memory protocol

* update test

* update cells

* add specific extensible return types to memory query and update_context

---------

Co-authored-by: Eric Zhu <ekzhu@users.noreply.github.com>
2025-01-14 07:06:13 +00:00
Jack Gerrits cb1633b501
feat!: Add support for model family specification (#4856)
* Add support for model family specification

* spelling mistake

* lint, etc

* fixes
2024-12-30 15:09:21 -05:00
Leon De Andrade 23dbb6a632
Add missing model context attribute (#4848)
* Add missing model context attribute

* fix type

* Add test

* imports

---------

Co-authored-by: Eric Zhu <ekzhu@users.noreply.github.com>
2024-12-28 22:50:54 -08:00
jspv a271708a97
Tool call result summary message (#4755)
* Adding ToolCallResultSummaryMessage

* Support for ToolCallResultSummaryMessage

* Added ToolCallSummaryMessage

* ruff format

* Add ToolCallSummaryMessage to ChatMessage

* typing and tests for ToolCallSummaryMessage

* PR Feedback

---------

Co-authored-by: Eric Zhu <ekzhu@users.noreply.github.com>
Co-authored-by: Hussein Mozannar <hmozannar@microsoft.com>
2024-12-19 21:23:18 -08:00
Eric Zhu e902e94b14
Define AgentEvent, rename tool call messages to events. (#4750)
* Define AgentEvent, rename tool call messages to events.

* update doc

* Use AgentEvent | ChatMessage to replace AgentMessage

* Update docs

* update deprecation notice

* remove unused

* fix doc

* format
2024-12-18 14:09:19 -08:00
Arun Brahma 7c0bbf674f
feat: add support for list of messages as team task input and update Society of Mind Agent (#4500)
* feat: add support for list of messages as team task input
* Update society of mind agent to use the list input task
---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Ryan Sweet <rysweet@microsoft.com>
Co-authored-by: Eric Zhu <ekzhu@users.noreply.github.com>
2024-12-14 21:48:17 -08:00
Leonardo Pinheiro 253fe216fd
Add models.openai and tools.langchain namespaces (#4601)
* add models.openai namespace

* refactor tools namespace

* update lock file

* revert pyproject changes

* update docs and add cast

* update ext models doc ref

* increase underline

* add reply models namespace

* update imports

* fix test

* linting

* fix missing conflicts

* revert pydantic changes

* rename to replay

* replay

* fix reply

* Fix test

* formatting

* example

---------

Co-authored-by: Leonardo Pinheiro <lpinheiro@microsoft.com>
Co-authored-by: Jack Gerrits <jack@jackgerrits.com>
Co-authored-by: Jack Gerrits <jackgerrits@users.noreply.github.com>
2024-12-09 19:18:09 -08:00
Hussein Mozannar 871a83fcc5
Fix AssistantAgent Tool Call Behavior (#4602)
* 1 tool call iteration default

* handoff first

* return_only_response

* add and remove tools

* print out tool calls

* pass checks

* fix issues

* add test

* add unit tests

* remove extra print

* Update python/packages/autogen-agentchat/src/autogen_agentchat/agents/_assistant_agent.py

Co-authored-by: Eric Zhu <ekzhu@users.noreply.github.com>

* documentation and none max_tools_calls

* Always limit # tool call to 1

* Update notebooks for the changing behavior of assistant agent.

* Merge branch 'main' into assistant_Agent_tools

* add reflect_on_tool_use parameter to format the tool call result

* wip

* wip

* fix pyright

* Add unit tests

* Merge remote-tracking branch 'origin/main' into assistant_Agent_tools

* Update with custom formatting of tool call summary

* format

* Merge branch 'main' into assistant_Agent_tools
2024-12-09 19:03:31 -08:00
Jack Gerrits 218e84fd8e
Migrate remaining components (#4626) 2024-12-09 18:39:07 -08:00
Victor Dibia 777f2abbd7
Load and Save state in AgentChat (#4436)
1. convert dataclass types to pydantic basemodel 
2. add save_state and load_state for ChatAgent
3. state types for AgentChat
---------

Co-authored-by: Eric Zhu <ekzhu@users.noreply.github.com>
2024-12-04 16:14:41 -08:00
Jack Gerrits 3022369eeb
Flatten core base and components (#4513)
* Flatten core base and components

* remove extra files

* dont export from deprecated locations

* format

* fmt
2024-12-03 17:00:44 -08:00
Eric Zhu b62f8f63dc
Remove logging from autogen agentchat (#4510) 2024-12-03 14:45:10 -08:00
Eric Zhu 50e84b945e
Move handoff to base in agentchat (#4509) 2024-12-03 14:34:55 -08:00
Eric Zhu 52790a8de7
o1 support for agent chat, and validate model capabilities (#4397) 2024-11-27 10:45:51 -08:00
Eric Zhu 5fa38b0166
Add task type that are messages to enable multi-modal tasks. (#4091)
* Add task type that are messages to enable multi-modal tasks.

* fix test
2024-11-07 21:38:41 -08:00
Eric Zhu 2e3155be2a
AgentChat pause, resume, and reset (#4088)
* AgentChat pause and resume a task
Resolves #3859

* Add

* Update usage

* Update usage

* WIP to address stateful group chat

* Refactor group chat to add reset and flags for running

* documentation
2024-11-07 16:00:35 -08:00
Eric Zhu 16e64c4c10
Rename `model_usage` to `models_usage`. (#4053) 2024-11-04 09:25:53 -08:00
Eric Zhu ca7caa779d
Add token usage to messages (#4028)
* Add token usage to messages

* small test edit
2024-11-01 13:20:25 -07:00
Eric Zhu cff7d842a6
AgentChat streaming API (#4015) 2024-11-01 04:12:43 -07:00
Eric Zhu 3d51ab76ae
Formalize `ChatAgent` response as a dataclass with inner messages (#3990) 2024-10-30 10:27:57 -07:00
Eric Zhu 4a49844996
`ChatAgent` declares the types of messages it produces (#3991)
* `ChatAgent` declares the types of messages it produces
2024-10-30 05:32:11 -07:00
Eric Zhu eb4b1f856e
Ability to generate handoff message from AssistantAgent (#3968)
* Ability to generate handoff message from AssistantAgent

* Fix mypy

* Validation

---------

Co-authored-by: Victor Dibia <victordibia@microsoft.com>
2024-10-29 08:04:14 -07:00
Eric Zhu 3fe0f9e97d
Add AssistantAgent, deprecate CodingAssistantAgent and ToolUseAssistantAgent (#3960)
* Add AssistantAgent, deprecate CodingAssistantAgent and ToolUseAssistantAgent

* Rename

* Add note

* Update uv

* uf lock

* Merge branch 'main' into assistant-agent

* Update uv
2024-10-25 23:17:06 -07:00