-
Notifications
You must be signed in to change notification settings - Fork 791
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
Enable AIFunctionFactory.Create functions to get DI services, Alternate 1 #6144
Closed
Closed
Changes from all commits
Commits
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 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 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
82 changes: 82 additions & 0 deletions
82
src/Libraries/Microsoft.Extensions.AI/Functions/AIFunctionArguments.cs
This file contains 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,82 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System; | ||
using System.Collections; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
using Microsoft.Shared.Collections; | ||
|
||
#pragma warning disable SA1111 // Closing parenthesis should be on line of last parameter | ||
#pragma warning disable SA1112 // Closing parenthesis should be on line of opening parenthesis | ||
#pragma warning disable SA1114 // Parameter list should follow declaration | ||
#pragma warning disable CA1710 // Identifiers should have correct suffix | ||
|
||
namespace Microsoft.Extensions.AI; | ||
|
||
/// <summary>Represents arguments to be used with <see cref="AIFunction.InvokeAsync"/>.</summary> | ||
/// <remarks> | ||
/// <see cref="AIFunction.InvokeAsync"/> may be invoked with arbitary <see cref="IEnumerable{T}"/> | ||
/// implementations. However, some <see cref="AIFunction"/> implementations may dynamically check | ||
/// the type of the arguments and use the concrete type to perform more specific operations. By | ||
/// checking for <see cref="AIFunctionArguments"/>, and implementation may optionally access | ||
/// additional context provided, such as any <see cref="IServiceProvider"/> that may be associated | ||
/// with the operation. | ||
/// </remarks> | ||
public class AIFunctionArguments : IReadOnlyDictionary<string, object?> | ||
{ | ||
private readonly IReadOnlyDictionary<string, object?> _arguments; | ||
|
||
/// <summary>Initializes a new instance of the <see cref="AIFunctionArguments"/> class.</summary> | ||
/// <param name="arguments">The arguments represented by this instance.</param> | ||
public AIFunctionArguments(IEnumerable<KeyValuePair<string, object?>>? arguments) | ||
{ | ||
if (arguments is IReadOnlyDictionary<string, object?> irod) | ||
{ | ||
_arguments = irod; | ||
} | ||
else if (arguments is null | ||
#if NET | ||
|| (Enumerable.TryGetNonEnumeratedCount(arguments, out int count) && count == 0) | ||
#endif | ||
) | ||
{ | ||
_arguments = EmptyReadOnlyDictionary<string, object?>.Instance; | ||
} | ||
else | ||
{ | ||
_arguments = arguments.ToDictionary( | ||
#if !NET | ||
x => x.Key, x => x.Value | ||
#endif | ||
); | ||
} | ||
} | ||
|
||
/// <summary>Gets any services associated with these arguments.</summary> | ||
public IServiceProvider? Services { get; init; } | ||
|
||
/// <inheritdoc /> | ||
public object? this[string key] => _arguments[key]; | ||
|
||
/// <inheritdoc /> | ||
public IEnumerable<string> Keys => _arguments.Keys; | ||
|
||
/// <inheritdoc /> | ||
public IEnumerable<object?> Values => _arguments.Values; | ||
|
||
/// <inheritdoc /> | ||
public int Count => _arguments.Count; | ||
|
||
/// <inheritdoc /> | ||
public bool ContainsKey(string key) => _arguments.ContainsKey(key); | ||
|
||
/// <inheritdoc /> | ||
public IEnumerator<KeyValuePair<string, object?>> GetEnumerator() => _arguments.GetEnumerator(); | ||
|
||
/// <inheritdoc /> | ||
public bool TryGetValue(string key, out object? value) => _arguments.TryGetValue(key, out value); | ||
|
||
/// <inheritdoc /> | ||
IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable)_arguments).GetEnumerator(); | ||
} |
This file contains 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 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
81 changes: 81 additions & 0 deletions
81
test/Libraries/Microsoft.Extensions.AI.Tests/Functions/AIFunctionArgumentsTests.cs
This file contains 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,81 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
using Microsoft.Extensions.DependencyInjection; | ||
using Xunit; | ||
|
||
namespace Microsoft.Extensions.AI; | ||
|
||
public class AIFunctionArgumentsTests | ||
{ | ||
[Fact] | ||
public void NullArg_RoundtripsAsEmpty() | ||
{ | ||
var args = new AIFunctionArguments(null); | ||
Assert.Null(args.Services); | ||
} | ||
|
||
[Fact] | ||
public void EmptyArg_RoundtripsAsEmpty() | ||
{ | ||
var args = new AIFunctionArguments([]); | ||
Assert.Null(args.Services); | ||
} | ||
|
||
[Fact] | ||
public void Services_Roundtrips() | ||
{ | ||
ServiceCollection sc = new(); | ||
IServiceProvider sp = sc.BuildServiceProvider(); | ||
|
||
var args = new AIFunctionArguments([]) | ||
{ | ||
Services = sp | ||
}; | ||
|
||
Assert.Same(sp, args.Services); | ||
} | ||
|
||
[Fact] | ||
public void IReadOnlyDictionary_ImplementsInterface() | ||
{ | ||
ServiceCollection sc = new(); | ||
IServiceProvider sp = sc.BuildServiceProvider(); | ||
|
||
var args = new AIFunctionArguments( | ||
[ | ||
new KeyValuePair<string, object?>("key1", "value1"), | ||
new KeyValuePair<string, object?>("key2", "value2"), | ||
]) | ||
{ | ||
Services = sp | ||
}; | ||
|
||
Assert.Same(sp, args.Services); | ||
|
||
Assert.Equal(2, args.Count); | ||
|
||
Assert.True(args.ContainsKey("key1")); | ||
Assert.True(args.ContainsKey("key2")); | ||
Assert.False(args.ContainsKey("KEY1")); | ||
|
||
Assert.Equal("value1", args["key1"]); | ||
Assert.Equal("value2", args["key2"]); | ||
|
||
Assert.Equal(new[] { "key1", "key2" }, args.Keys); | ||
Assert.Equal(new[] { "value1", "value2" }, args.Values); | ||
|
||
Assert.True(args.TryGetValue("key1", out var value)); | ||
Assert.Equal("value1", value); | ||
Assert.False(args.TryGetValue("key3", out value)); | ||
Assert.Null(value); | ||
|
||
Assert.Equal([ | ||
new KeyValuePair<string, object?>("key1", "value1"), | ||
new KeyValuePair<string, object?>("key2", "value2"), | ||
], args.ToArray()); | ||
} | ||
} |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think it would be more conventional to retrieve an
ILoggerFactory
and use that to construct anILogger<FunctionInvokingChatClient>
. Developers won't normally register anILogger<FunctionInvokingChatClient>
explicitly.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Doesn't DI do that automatically?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
One problem/benefit of taking an
ILogger
is that whoever constructs theFunctionInvokingChatClient
controls the category name of logs emitted by it. That's kind of cool, but very unusual. I now once again lean towards sticking with convention and taking anILoggerFactory
even though I said it was okay to leave as-is before.You could take an
ILogger<FunctionInvokingChatClient>
to essentially force the caller to user the right category name, but then there's no real benefit over just taking anILoggerFactory
. It would prevent us from ever logging in a subcategory or something like that in the future.And while on the topic of sticking with conventions, I don't think we should fall back to the
IServiceProvider
to get the logger when anull
logger is passed in. We talked about this before here. I said it was okay to leave it as-is then, but it still leaves a bad taste in my mouth.I can't think of any other place where a constructor takes an
IServiceProvider
and another service in the same signature and uses theIServiceProvider
as a fallback when the other service is missing. UserManager doesn't have this type of fallback.I'd feel better about the fallback behavior if
FunctionInvokingChatClient(IChatClient innerClient, IServiceProvider services)
was a separate constructor.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The point of taking an ILogger was that someone could use this if they already have one.
If we're not going to do that, what's the benefit of taking an ILoggerFactory at all? If you can pass in an IServiceProvider, the implementation could fish the ILoggerFactory or ILogger out of there.
Are there scenarios where you have an ILoggerFactory that doesn't come from DI?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
AFAIK, logging to someone else's
ILogger
isn't supported by any classes we ship. It's always anILoggerFactory
orILogger<ServiceType>
, because it's the type controls the logging category, not whoever constructed an instance of that type. That way you get consistent logging categories and IDs when looking at logs for a random application.We don't have too many types that straddle the world between being a DI service and being easily constructable on their own, but
MemoryCache
follows this pattern and takes anILoggerFactory
rather than anILogger
.I do think that controlling the log category on a per-instance basis might be an interesting feature. I've even thought controlling the log category might be useful for
MemoryCache
, since it can be used for so many different purposes in the same application, but I don't think it's so important for this API that we should break our standard conventions. We could always add anILogger
overload later if we really need this functionality.You could use
LoggerFactory.Create()
. I've noticed the mcpdotnet tests use it.https://learn.microsoft.com/dotnet/core/extensions/logging
We could, but we'd basically be following the "service locator pattern" at that point. It wouldn't be nearly as discoverable that
FunctionInvokingChatClient
will do its own logging if you provide it a logger.I like the clean break where the
IServiceProvider
is for providing arbitrary services to theAIFunction
, and any service types we know get used internally by theFunctionInvokingChatClient
are provided as separate constructor parameters in the longest overload.I'm fine with also introducing a shorter overload that takes just the inner
IChatClient
and anIServiceProvider
, and that having that resolve the logger from DI. We could go even further and use theIServiceProvider
from the innerIChatClient
as I suggest here. But in either case, I still think there should be a longer overload that takes anILoggerFactory
. At least that would make it clear to callers thatFunctionInvokingChatClient
can emit its own logs.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
OK, so you're viewing the IServiceProvider not as something thee FICC uses itself but that is just an opaque object that's passed through. That's reasonable, though then having other overloads that do query the service provider muddies the waters, no? There are lots of APIs and delegates that pass around an IServiceProvider for resolution purposes... how is a consumer supposed to know when it'll be used in that capacity or not? My assumption is giving something a service provider is giving it access to everything, and it may access everything. Whether it does so explicitly via GetService or instantiaies objects that take a logger and have that populated using ActivatorUtilities, I don't see the difference. Both do logging. Both resolve a logger from the service provider. One just explicitly calls the method and the other does so by calling a method that calls it.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I admit allowing the overload to query the service provider muddies the waters a bit, but that's still where I draw the line. It leaves the door open for us to add new dependencies like
IMeterFactory
toFunctionInvokingChatClient
post 1.0 and use it without being forced to update old code to call the new constructor.However, in that case, I think we should still add a new constructor that takes
IMeterFactory
and doesn't fall back to the service provider. If a null meter factory is passed in, there should be no metrics same as with logging. And unlike with logging, I don't think there's aNullMeterFactory.Instance
to make it easy to disable metrics otherwise.I think that if you're calling an overload that takes an optional dependency in the parameter list and you omit it, it should not be used. The fact that you happened to need the
IServiceProvider
for other reasons doesn't make it a good idea to use the service locator pattern for every other dependency.I realize that it's a matter of taste, and there's no objectively right answer here though. If I had to rank my preference from most preferred to least, I'd go with:
IServiceProvider
as a fallback for dependencies that couldn't be provided directly with the given overload.IServiceProvider
as a fallback for any dependencies.IServiceProvider
anywhere an optional dependency hasn't been provided.But I think any of these are fine as long as we're consistent.