Skip to content

Instantly share code, notes, and snippets.

@goyaweb
Created October 2, 2024 15:40
Show Gist options
  • Select an option

  • Save goyaweb/1c2c06c3cf1ef016e85cca680f1ef1da to your computer and use it in GitHub Desktop.

Select an option

Save goyaweb/1c2c06c3cf1ef016e85cca680f1ef1da to your computer and use it in GitHub Desktop.
Share context between agents using functions
using Microsoft.SemanticKernel;
using System.ComponentModel;
namespace SynergyOS.WebApi.Infrastructure
{
public class ConversationContextManager
{ private readonly ConversationContext conversationContext;
public ConversationContextManager(
ConversationContext context)
{
conversationContext = context;
}
/// <summary>
/// Store a variable in the conversation context.
/// </summary>
/// <param name="variableName">The name of the variable to store.</param>
/// <param name="value">The value to store in the variable.</param>
/// <param name="cancellationToken">Cancellation token for async task.</param>
/// <returns>Message confirming the storage action.</returns>
[KernelFunction, Description("Store a variable in the conversation context.")]
public async Task<string> StoreVariableAsync(
string variableName,
string value,
CancellationToken cancellationToken = default)
{
// Store the value in conversationContext dynamically
if (conversationContext.Variables.ContainsKey(variableName))
{
conversationContext.Variables[variableName] = value;
}
else
{
conversationContext.Variables.Add(variableName, value);
}
return $"Stored variable '{variableName}' with value: '{value}'.";
}
/// <summary>
/// Retrieve a variable from the conversation context.
/// </summary>
/// <param name="variableName">The name of the variable to retrieve.</param>
/// <param name="cancellationToken">Cancellation token for async task.</param>
/// <returns>The value of the variable, or a message if not found.</returns>
[KernelFunction, Description("Retrieve a variable from the conversation context.")]
public async Task<string> RetrieveVariableAsync(
string variableName,
CancellationToken cancellationToken = default)
{
// Check if the variable exists and return its value
if (conversationContext.Variables.TryGetValue(variableName, out var value))
{
return $"The value of '{variableName}' is: {value}.";
}
return $"Variable '{variableName}' not found in the conversation context.";
}
}
public class ConversationContext
{
// Dictionary to hold the conversation variables
public Dictionary<string, object> Variables { get; private set; }
public ConversationContext()
{
// Initialize the dictionary
Variables = new Dictionary<string, object>();
}
// Method to clear context if needed
public void Clear()
{
Variables.Clear();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment