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

.Net: Find Associated Tool(s) Called #10654

Open
aherrick opened this issue Feb 24, 2025 · 1 comment
Open

.Net: Find Associated Tool(s) Called #10654

aherrick opened this issue Feb 24, 2025 · 1 comment
Assignees
Labels
.NET Issue or Pull requests regarding .NET code

Comments

@aherrick
Copy link

I'm trying to figure out the cleanest way to figure out what tools were called in a call. Here is what I've come up with but there has to be a better way?

using System.ComponentModel;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;

var kernel = Kernel
    .CreateBuilder()
    .AddAzureOpenAIChatCompletion(
        deploymentName: "gpt-4o",
        endpoint: "",
        apiKey: ""
    )
    .Build();

kernel.Plugins.AddFromType<WeatherPlugin>();

var chatHistory = new ChatHistory();

chatHistory.AddUserMessage("whats the weather");

var promptExecutionSettings = new PromptExecutionSettings
{
    FunctionChoiceBehavior = FunctionChoiceBehavior.Auto(),
};

var chatService = kernel.GetRequiredService<IChatCompletionService>();
var result = await chatService.GetChatMessageContentAsync(
    chatHistory,
    promptExecutionSettings,
    kernel
);

Console.WriteLine(result.Content);

var plugins = GetPluginsUsed(chatHistory);
foreach (var plugin in plugins)
{
    Console.WriteLine(plugin);
}

Console.ReadLine();

static List<string> GetPluginsUsed(ChatHistory chatHistory)
{
    // Find the index of the most recent user message
    int lastUserMessageIndex = -1;
    for (int i = chatHistory.Count - 1; i >= 0; i--)
    {
        if (chatHistory[i].Role == AuthorRole.User)
        {
            lastUserMessageIndex = i;
            break;
        }
    }

    // Extract only tool messages that appear AFTER the last user message
    var toolMessages = chatHistory
        .Skip(lastUserMessageIndex + 1) // Start from the message after the user's last input
        .Where(msg => msg.Role == AuthorRole.Tool)
        .SelectMany(toolMsg =>
            toolMsg
                .Items.OfType<FunctionResultContent>()
                .Select(x => $"({x.PluginName}: {x.FunctionName})")
        )
        .ToList();

    return toolMessages;
}

public class WeatherPlugin
{
    // Hard coded weather data
    private readonly string[] weatherData =
    [
        "Sunny, 15°C",
        "Cloudy, 12°C",
        "Rainy, 10°C",
        "Snowy, -2°C",
    ];

    private readonly Random random = new();

    [KernelFunction, Description("Get weather information")]
    public string GetWeather()
    {
        // Get random weather data
        int index = random.Next(weatherData.Length);
        return weatherData[index];
    }
}
@moonbox3 moonbox3 changed the title Find Associated Tool(s) Called .Net: Find Associated Tool(s) Called Feb 25, 2025
@moonbox3 moonbox3 added the .NET Issue or Pull requests regarding .NET code label Feb 25, 2025
@moonbox3
Copy link
Contributor

Adding @SergeyMenshykh to help.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
.NET Issue or Pull requests regarding .NET code
Projects
Status: No status
Development

No branches or pull requests

3 participants