// Copyright (c) Microsoft. All rights reserved.
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging;
using Microsoft.Shared.Diagnostics;
namespace OpenAI.Chat;
///
/// Provides extension methods for
/// to simplify the creation of AI agents that work with OpenAI services.
///
///
/// These extensions bridge the gap between OpenAI SDK client objects and the Microsoft Agent Framework,
/// allowing developers to easily create AI agents that leverage OpenAI's chat completion and response services.
/// The methods handle the conversion from OpenAI clients to instances and then wrap them
/// in objects that implement the interface.
///
public static class OpenAIChatClientExtensions
{
///
/// Creates an AI agent from an using the OpenAI Chat Completion API.
///
/// The OpenAI to use for the agent.
/// Optional system instructions that define the agent's behavior and personality.
/// Optional name for the agent for identification purposes.
/// Optional description of the agent's capabilities and purpose.
/// Optional collection of AI tools that the agent can use during conversations.
/// Provides a way to customize the creation of the underlying used by the agent.
/// Optional logger factory for enabling logging within the agent.
/// An optional to use for resolving services required by the instances being invoked.
/// An instance backed by the OpenAI Chat Completion service.
/// Thrown when is .
public static ChatClientAgent AsAIAgent(
this ChatClient client,
string? instructions = null,
string? name = null,
string? description = null,
IList? tools = null,
Func? clientFactory = null,
ILoggerFactory? loggerFactory = null,
IServiceProvider? services = null) =>
client.AsAIAgent(
new ChatClientAgentOptions()
{
Name = name,
Description = description,
ChatOptions = tools is null && string.IsNullOrWhiteSpace(instructions) ? null : new ChatOptions()
{
Instructions = instructions,
Tools = tools,
}
},
clientFactory,
loggerFactory,
services);
///
/// Creates an AI agent from an using the OpenAI Chat Completion API.
///
/// The OpenAI to use for the agent.
/// Full set of options to configure the agent.
/// Provides a way to customize the creation of the underlying used by the agent.
/// Optional logger factory for enabling logging within the agent.
/// An optional to use for resolving services required by the instances being invoked.
/// An instance backed by the OpenAI Chat Completion service.
/// Thrown when or is .
public static ChatClientAgent AsAIAgent(
this ChatClient client,
ChatClientAgentOptions options,
Func? clientFactory = null,
ILoggerFactory? loggerFactory = null,
IServiceProvider? services = null)
{
Throw.IfNull(client);
Throw.IfNull(options);
var chatClient = client.AsIChatClient();
if (clientFactory is not null)
{
chatClient = clientFactory(chatClient);
}
return new ChatClientAgent(chatClient, options, loggerFactory, services);
}
}