// Copyright (c) Microsoft. All rights reserved. using Microsoft.Extensions.AI; using Microsoft.Extensions.AI.Agents; using Microsoft.Shared.Diagnostics; using OpenAI.Chat; namespace OpenAI; /// /// Provides extension methods for to extract native OpenAI response objects /// from the Microsoft Extensions AI Agent framework responses. /// /// /// These extensions enable developers to access the underlying OpenAI SDK objects when working with /// AI agents that are backed by OpenAI services. The methods extract strongly-typed OpenAI responses /// from the property, providing a bridge between /// the Microsoft Extensions AI framework and the native OpenAI SDK types. /// public static class AgentRunResponseExtensions { /// /// Extracts a native OpenAI object from an . /// /// The agent response containing the raw OpenAI representation. /// The native OpenAI object. /// Thrown when is . /// /// Thrown when the is not a object. /// This typically occurs when the agent response was not generated by an OpenAI chat completion service /// or when the underlying representation has been modified or corrupted. /// /// /// /// This method provides access to the native OpenAI object that was used /// to generate the agent response. This is useful when you need to access OpenAI-specific properties /// or metadata that are not exposed through the Microsoft Extensions AI abstractions. /// /// public static ChatCompletion AsChatCompletion(this AgentRunResponse agentResponse) { Throw.IfNull(agentResponse); if (agentResponse.RawRepresentation is ChatResponse chatResponse) { return chatResponse.RawRepresentation is ChatCompletion chatCompletion ? chatCompletion : throw new ArgumentException("ChatResponse.RawRepresentation must be a ChatCompletion"); } throw new ArgumentException("AgentRunResponse.RawRepresentation must be a ChatResponse"); } }