Commit Graph

92 Commits

Author SHA1 Message Date
Eric Zhu e686342f53
Fix token limited model context (#6137)
Token limited model context is currently broken because it is importing
from extensions.

This fix removed the imports and updated the model context
implementation to use model client directly.

In the future, the model client's token counting should cache results
from model API to provide accurate counting.
2025-03-28 17:24:41 +00:00
Griffin Bassman 7487687cdc
[feat] token-limited message context (#6087) 2025-03-27 13:59:27 -07:00
Eric Zhu aba41d74d3
feat: add structured output to model clients (#5936) 2025-03-15 07:58:13 -07:00
Eric Zhu 740afe5b61
Add ToolCallEvent and log it from all builtin tools (#5859)
Resolves #5745

Also made sure to log LLMCallEvent from all builtin model clients, and
added unit test for coverage.

---------

Co-authored-by: Ryan Sweet <rysweet@microsoft.com>
Co-authored-by: Victor Dibia <victordibia@microsoft.com>
2025-03-07 16:04:45 -08:00
afourney 8f737de0e1
Add client close (#5871)
Fixes #4821 by adding a `close()` method to all clients.

Additionally:
* The m1 CLI is updated to close the client before exiting.
* The playwrightcontroller is updated to suppress some other unrelated
chatty warnings (e.g,, produced by markitdown when encountering
conversions that require external utilities)
2025-03-07 14:10:06 -08:00
Muhammad Junaid 0b9a622b56
Fix: Auto-Convert Pydantic and Dataclass Arguments in AutoGen Tool Calls (#5737)
AutoGen was passing raw dictionaries to functions instead of
constructing Pydantic model or dataclass instances. If a tool function’s
parameter was a Pydantic BaseModel or a dataclass, the function would
receive a dict and likely throw an error or behave incorrectly (since it
expected an object of that type).

This PR addresses problem in AutoGen where tool functions expecting
structured inputs (Pydantic models or dataclasses) were receiving raw
dictionaries. It ensures that structured inputs are automatically
validated and instantiated before function calls. Complete details are
in Issue #5736

[Reproducible Example Code - Failing
Case](https://colab.research.google.com/drive/1hgoP-cGdSZ1-OqQLpwYmlmcExgftDqlO?usp=sharing)
 
<!-- Please give a short summary of the change and the problem this
solves. -->
## Changes Made:
- Inspect function signatures for Pydantic BaseModel and dataclass
annotations.
- Convert input dictionaries into properly instantiated objects using
BaseModel.model_validate() for Pydantic models or standard instantiation
for dataclasses.
  - Raise descriptive errors when validation or instantiation fails.
  - Unit tests have been added to cover all scenarios

Now structured inputs are automatically validated and instantiated
before function calls.

- **Updated Conversion Logic:**  
In the `run()` method, we now inspect the function’s signature and
convert input dictionaries to structured objects. For parameters
annotated with a Pydantic model, we use `model_validate()` to create an
instance; for those annotated with a dataclass, we instantiate the
object using the dataclass constructor. For example:

  ```python
  # Get the function signature.
  sig = inspect.signature(self._func)
  raw_kwargs = args.model_dump()
  kwargs = {}

  # Iterate over the parameters expected by the function.
  for name, param in sig.parameters.items():
      if name in raw_kwargs:
          expected_type = param.annotation
          value = raw_kwargs[name]
# If expected type is a subclass of BaseModel, perform conversion.
if inspect.isclass(expected_type) and issubclass(expected_type,
BaseModel):
              try:
                  kwargs[name] = expected_type.model_validate(value)
              except ValidationError as e:
                  raise ValueError(
f"Error validating parameter '{name}' for function
'{self._func.__name__}': {e}"
                  ) from e
          # If it's a dataclass, instantiate it.
          elif is_dataclass(expected_type):
              try:
cls = expected_type if isinstance(expected_type, type) else
type(expected_type)
                  kwargs[name] = cls(**value)
              except Exception as e:
                  raise ValueError(
f"Error instantiating dataclass parameter '{name}' for function
'{self._func.__name__}': {e}"
                  ) from e
          else:
              kwargs[name] = value
  ```

- **Error Handling Improvements:**  
Conversion steps are wrapped in try/except blocks to raise descriptive
errors when instantiation fails, aiding in debugging invalid inputs.

- **Testing:**  
Unit tests have been added to simulate tool calls (e.g., an `add` tool)
to ensure that with input like:
  ```json
  {"input": {"x": 2, "y": 3}}
  ```
The tool function receives an instance of the expected type and returns
the correct result.


## Related issue number
Closes #5736
 
## Checks
- [x] 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.
- [x] I've added tests (if relevant) corresponding to the changes
introduced in this PR.
- [x] I've made sure all auto checks have passed.
2025-03-03 16:35:27 -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
Jack Gerrits 6b68719939
Allow background exceptions to be fatal (#5716)
Closes #4904 

Does not change default behavior in core.

In agentchat, this change will mean that exceptions that used to be
ignored and result in bugs like the group chat stopping are now reported
out to the user application.

---------

Co-authored-by: Ben Constable <benconstable@microsoft.com>
Co-authored-by: Ryan Sweet <rysweet@microsoft.com>
2025-02-26 18:34:53 +00:00
Eric Zhu 80891b4841
doc & fix: Enhance AgentInstantiationContext with detailed documentation and examples for agent instantiation; Fix a but that caused value error when the expected class is not provided in register_factory (#5555)
Resolves #5519

Also spotted and fixed a bug that caused value error from `register_factory`, when the `expected_class` was not provided.
2025-02-14 18:19:32 -08:00
Eric Zhu 69c0b2b5ef
fix: Add model info validation and improve error messaging (#5556)
Introduce validation for the ModelInfo dictionary to ensure required
fields are present.

Resolves #5501
2025-02-14 18:09:33 -08:00
Eric Zhu ec314c586c
feat: Add strict mode support to BaseTool, ToolSchema and FunctionTool (#5507)
Resolves #4447

For `openai` client's structured output support is through its beta
client, which requires the function JSON schema to be strict when in
structured output mode.

Reference:
https://platform.openai.com/docs/guides/function-calling#strict-mode
2025-02-13 19:44:55 +00: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
Jack Gerrits 40d74a32a1
Use proto descriptor for typename (#5346)
Closes #5302
2025-02-04 19:18:16 +00:00
Nour Bouzid 02e968a531
FunctionTool partial support (#5183)
<!-- 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?

FunctionTool supports passing in a partial

## Related issue number

Closes #5151 

## Checks

- [x] 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.
- [x] I've added tests (if relevant) corresponding to the changes
introduced in this PR.
- [x] I've made sure all auto checks have passed.
2025-01-29 18:02:18 +00:00
Mohammad Mazraeh 2f1684b698
update dependencies to work with protobuf 5 (#5195)
Closes #5074

Signed-off-by: Mohammad Mazraeh <mazraeh.mohammad@gmail.com>
2025-01-28 22:11:54 -08:00
Victor Dibia 6359b6a7be
improve component config, add description support in dump_component (#5203)
<!-- 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?

It is currently hard to add a description to a component (defaults to
None also) .. you have to call super.dump() modify and return. This PR
makes the experience better.

- allows you specify `component_description` and `component_label` as an
optional class var. label is an optional human readable name for the the
component.
- will use component_description if provided int he description field
when dumped if there is no description, will use the first line of class
docstring. Takes advantage of all the good practices we have in writing
good docstrings. label defaults to component type.
 

For example 

```python
model_client=OpenAIChatCompletionClient( model="gpt-4o-2024-08-06" )
config = model_client.dump_component()
print(config.model_dump_json())
```
Note the description field below is no longer None and there is a label
```python
{
  "provider": "autogen_ext.models.openai.OpenAIChatCompletionClient",
  "component_type": "model",
  "version": 1,
  "component_version": 1,
  "description": "Chat completion client for OpenAI hosted models.",
  "label": "OpenAIChatCompletionClient",
  "config": { "model": "gpt-4o-2024-08-06" }
}


```

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

## Related issue number

<!-- For example: "Closes #1234" -->
None, felt faster to fix.

## Checks

- [x] 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.
- [x] I've added tests (if relevant) corresponding to the changes
introduced in this PR.
- [x] I've made sure all auto checks have passed.
2025-01-27 21:41:23 +00:00
Victor Dibia 979d8ab4f1
Make AgentChat Team Config Serializable (#5071)
* initial pass on making group chats declarative

* update group chat tests

* update impl to include participant serialization for all teams

* v1 making soc declarative

* update memory test

* update chatagent and team base classes

* update serialization doc notebook

* fomating updates
2025-01-24 07:08:22 +00:00
Victor Dibia 58d789a249
Make FunctionTools Serializable (Declarative) (#5052)
* vi1 for declarative tools

* make functtools declarative

* add tests

* update imports

* update formatting

* move tests, format fixes

* format updates

* update test

* add user warning to _from_config

* add warning on load_component to docs

---------

Co-authored-by: Ryan Sweet <rysweet@microsoft.com>
2025-01-24 03:49:43 +00:00
Victor Dibia 5e9b24c3d9
Make Memory and Team an ABC (#5149)
* make memory and team an ABC

* update memory test

* update tests
2025-01-22 15:51:34 -08:00
Sachin Joglekar 8bd65c672f
Add ChatCompletionCache along with AbstractStore for caching completions (#4924)
* Add ChatCompletionCache along with AbstractStore for caching completions

* Addressing comments

* Improve interface for cachestore

* Improve documentation & revert protocol

* Make cache store typed, and improve docs

* remove unnecessary casts
2025-01-16 15:47:38 -08:00
Eric Zhu 6954e516b6
Update autogen_core.memory: adding docs, removing some fields. (#5053)
* Update autogen_core.memory: adding docs, removing some fields.

* Remove timestamp

* Remove name from base; fix example code

* fix test

* lint

* fix doc
2025-01-15 02:33:46 +00: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 404522bd6b
Split apart component infra to allow for abstract class integration (#5017)
* Split apart component infra to allow for abstract class integration

* fix is_component_class check

* make is_ functions type guards

* Simplify component creation

* undo changes

* Format
2025-01-13 15:58:38 -05:00
peterychang 71a3b238e7
Activate deactivate agents (#4800)
* Instantiate and call activate/deactivate on agents

* autoformatting

* remove activate. Rename deactivate to close

* remove unneeded import

* create close fn in runtime

* change runtime close behavior

* uv.lock

---------

Co-authored-by: Jack Gerrits <jackgerrits@users.noreply.github.com>
2025-01-07 21:37:02 +00:00
Jack Gerrits 5b9be79fba
feat!: Add message context to signature of intervention handler, add more to docs (#4882)
* Add message context to signature of intervention handler, add more to docs

* example

* Add to test

* Fix pyright

* mypy
2025-01-07 12:51:35 -05:00
Griffin Bassman bdfdc6ab5e
fix: poe check errors to pass (#4917)
Co-authored-by: Jack Gerrits <jackgerrits@users.noreply.github.com>
2025-01-07 10:48:37 -05:00
Jack Gerrits e6ac2f37fa
Update logged events, add message id to send message (#4868)
* Update logged events

* add message_id

* serialize payload for log

* fix pytest warning

* serialization

* fix test

* lock

* fix warning and test
2024-12-31 15:11:48 -05:00
Jack Gerrits c58eb9d120
Move intervention objects to root module (#4859)
* Move intervention to root

* usage
2024-12-30 16:09:37 -05: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
Jack Gerrits 190fcd15ed
fix!: Fix SingleThreadedAgentRuntime busy loop (#4855)
* Fix high cpu usage

* Use queue for shutdown

* mypy fixes

* formatting

* missing import
2024-12-30 15:04:20 -05:00
Leonardo Pinheiro 9a2dbb4fba
Add * before keyword args for ChatCompletionClient (#4822)
add * before keyword args

Co-authored-by: Leonardo Pinheiro <lpinheiro@microsoft.com>
Co-authored-by: Jack Gerrits <jackgerrits@users.noreply.github.com>
2024-12-27 08:41:16 -05:00
Jack Gerrits 0040016bec
Remove usage of internal pydantic functionality for forward ref eval (#4816)
* Remove usage of internal pydantic func

* Update python/packages/autogen-core/tests/test_tools.py

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update python/packages/autogen-core/tests/test_tools.py

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Remove unused import NoneType from test_tools.py

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2024-12-26 12:15:54 -08:00
Jack Gerrits 90d6723685
Usability improvements to component config (#4794)
* Usability improvements to component config

* Implement model upgrade
2024-12-23 14:03:58 -05:00
Jack Gerrits dda208f9b4
Add component config support (#4757)
* Add wip component impl

* finishing touches

* remove test file

* fix json usage

* Format

---------

Co-authored-by: Victor Dibia <victordibia@microsoft.com>
2024-12-20 13:14:24 -05:00
Aditya Kurniawan c989181da2
use model context for assistant agent, refactor model context (#4681)
* Decouple model_context from AssistantAgent

* add UnboundedBufferedChatCompletionContext to mimic pervious model_context behaviour on AssistantAgent

* moving unbounded buffered chat to a different file

* fix model_context assertions in test_group_chat

* Refactor model context, introduce states

* fixes

* update

---------

Co-authored-by: aditya.kurniawan <aditya.kurniawan@core42.ai>
Co-authored-by: Eric Zhu <ekzhu@users.noreply.github.com>
Co-authored-by: Victor Dibia <victordibia@microsoft.com>
2024-12-19 22:27:41 -08:00
kiyoung 2cd91f66d8
make "Alias", "ImportFromModule" classes hashable (#4734)
make hashable to Alias, ImportFromModule

Co-authored-by: Jack Gerrits <jackgerrits@users.noreply.github.com>
2024-12-17 11:11:36 -08:00
Jack Gerrits 218e84fd8e
Migrate remaining components (#4626) 2024-12-09 18:39:07 -08:00
Jack Gerrits 87011ae01b
Migrate model context and models modules out of components (#4613)
* Move model context out of components

* move models out of components

* rename docs file
2024-12-09 10:00:08 -08:00
Jack Gerrits 9af450a59f
Move local code exec to ext, uplevel components (#4557) 2024-12-04 20:21:46 -08:00
Jack Gerrits e615059345
Remove extract_markdown_code_blocks from core API (#4554) 2024-12-04 17:13:43 -08:00
Jack Gerrits 2b878763f8
Move grpc runtimes to ext, flatten application (#4553)
* Move grpc runtimes to ext, flatten application

* rename to grpc

* fmt
2024-12-04 16:23:20 -08:00
Jack Gerrits d85a607da9
Move LLMUsageTracker to a cookbook (#4549)
* Move LLMUsageTracker to a cookbook

* rename, add to index

* fmt and remove test

* Update python/packages/autogen-core/docs/src/user-guide/core-user-guide/cookbook/llm-usage-logger.ipynb

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Fix missing quotation marks in notebook

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2024-12-04 14:49:39 -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
Jack Gerrits 954ba84fe7
Change base agent to use on message impl (#4485)
* Change base agent to use on message impl

* update doc

* Update

* Merge branch 'main' into on_msg_impl
2024-12-03 10:04:12 -08:00
Jack Gerrits a4067f6c0a
Migrate Python distributed runtime to use cloud events for event (#4407)
* Cloud event publishing

* Implement cloud event receiving

* impl host servicer and
2024-11-27 08:32:03 -08:00
Jack Gerrits bd77ccbd7b
Serialize to Proto.Any for python serializer (#4404) 2024-11-27 07:32:01 -08:00
Jack Gerrits 0d3bc948a1
Replatform closure agent on base agent (#4389)
* Replatform closure agent on base agent

* Fix mypy

* update agentcaht

---------
2024-11-26 16:33:37 -08:00
Jack Gerrits 45f16f534b
Fix deprecated usages (#4374) 2024-11-26 16:31:23 -08:00
Jack Gerrits df183be35a
Add special topic for agent direct messaging (#4385)
* Add special topic for agent direct messaging

* move to base

* update sub counts

* Fix tests
2024-11-26 17:01:25 -05:00