Skip to content

Allow caching AIFunction #6121

@raffaeler

Description

@raffaeler

Description

The default concrete implementation of AIFunction is ReflectionAIFunction.
This object captures the reference of the object containing the function to be executed on-demand by the LLM.
This reference is held as private, therefore each AIFunction instance points to a unique instance of the "agent".

I would like to cache this ReflectionAIFunction for all the instances of my agents. This means that ReflectionAIFunction should get rid of (or allow to override/replace) the field called object? _target which is used to invoke the method.

Reproduction Steps

In the "agent" default constructor I create the AIFunction

var function = AIFunctionFactory.Create(MyMethod);

later on, I can invoke the function using:

function.InvokeAsync(arguments, cancellationToken);

But InvokeAsync does not allow to specify the target instance.
Using UnderlyingMethod would not help as I could not reuse the internal marshalling transforms.

Expected behavior

I need to be able to manage the lifecycle of my "agents" without recreating the AIFunction for each instance.

If an LLM needs to invoke an agents multiple times and this agent is stateful, reusing the same agent instance would be wrong.
There are many examples of stateful agents like caching data or dbcontext, text to augment prompts, correlation ids, etc.

Actual behavior

Currently, I need to re-create the AIFunction for each instance of my agent.

Regression?

No

Known Workarounds

I am not aware of any workarounds

Configuration

  • ASP.NET Core 9
  • Microsoft.Extensions.AI version: 9.3.0-preview.1.25161.3

Other information

Nothing relevant

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-aiMicrosoft.Extensions.AI librariesbugThis issue describes a behavior which is not expected - a bug.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions