Skip to content

Add OpenAI decision client adapter - #7957

Open
luisquintanilla wants to merge 11 commits into
luisquintanilla-decision-foundation-apifrom
luisquintanilla-decision-model-abstraction
Open

luisquintanilla wants to merge 11 commits into
luisquintanilla-decision-foundation-apifrom
luisquintanilla-decision-model-abstraction

Conversation

@luisquintanilla

@luisquintanilla luisquintanilla commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #7795. Related to #7764.

Summary

This PR adds AsIDecisionClient(), an experimental (MEAI001) extension that wraps OpenAI.Decisions.DecisionsClient as an IDecisionClient. It is the first concrete implementation of the provider-neutral decision abstraction from #7795, so the abstraction's shape is checked against a real service.

The adapter only translates. It maps the request to the OpenAI Decisions wire format and maps the native answers back. It also enforces the abstraction's response contract. It does not post-process probabilities.

OpenAIClient openAI = new(
    new BearerTokenPolicy(new DefaultAzureCredential(), "https://ai.azure.com/.default"),
    new OpenAIClientOptions { Endpoint = new Uri("https://<resource>.cognitiveservices.azure.com/openai/v1") });

using IDecisionClient client = openAI.GetDecisionsClient().AsIDecisionClient("gpt-6-luna");

byte[] photoBytes = await File.ReadAllBytesAsync("package.png");

DecisionResponse response = await client.GetDecisionAsync(
    new Order("delivered", 6),
    [
        new BinaryDecisionQuestion("is_late", "Was the order delivered late?"),
        new ChoiceDecisionQuestion("action",
            [new("refund", "Issue a refund."), new("apology", "Send an apology.")],
            "Which action should support take?"),
    ],
    contents: [new DataContent(photoBytes, "image/png")]);

record Order(string Status, int DaysLate);

The state is serialized with AIJsonUtilities.DefaultOptions, as IChatClient.GetResponseAsync<T> does. For Native AOT, pass a source-generated context's options. For full control, construct a DecisionRequest with a JsonElement State: new DecisionRequest(questions) { State = ..., Contents = ... }.

With an OpenAI API key, it is new DecisionsClient(apiKey).AsIDecisionClient("gpt-6-luna").

What this PR adds

Area Design
OpenAIClientExtensions.AsIDecisionClient(DecisionsClient, string? defaultModelId) The only new public API. It is [Experimental] and recorded in Microsoft.Extensions.AI.OpenAI.json.
OpenAIDecisionClient (internal) Request and response mapping, contract enforcement, and error translation
GetService Returns DecisionClientMetadata (provider openai, endpoint, default model, all three kinds) and the underlying DecisionsClient
README A "Decisions (experimental)" section in the Microsoft.Extensions.AI.OpenAI README

How the PRs fit together

PR Package Responsibility
#7795 Microsoft.Extensions.AI.Abstractions Provider contract and exchange types
#7796 Microsoft.Extensions.AI Typed definitions, binding and AsAIFunction
This PR (draft) Microsoft.Extensions.AI.OpenAI OpenAI implementation
luisquintanilla/typesafe-meai#5 sample End-to-end console app that uses packages built from #7796 and this PR

This PR is a draft because it depends on #7795 settling, and because the OpenAI .NET SDK's Decisions surface (OpenAI 2.15.0) is itself experimental.

Mapping

Abstraction OpenAI Decisions API
DecisionRequest.State input_json content part for a JSON object. A JSON string is sent as input_text. Other non-object values, including an explicit JSON null, are sent as input_text with their raw JSON text. A null State (no state) sends nothing.
TextContent input_text
Image DataContent or UriContent, with an optional "detail" additional property input_image
AIContent.RawRepresentation that is already a native part Passed through as-is
BinaryDecisionQuestion predicate. True and false descriptions are appended to the instructions, because predicates have no outcome descriptions.
ChoiceDecisionQuestion / DecisionCandidate choice / choices[].value
ScoreDecisionQuestion / DecisionScoreLevel score / levels[].label
DecisionOptions.ModelId, RawRepresentationFactory model, and a pre-populated DecisionCreationOptions
refusal answer UnansweredDecisionAnswer with DecisionUnansweredReason.Refusal
Choice and score confidence DecisionAnswer.AdditionalProperties["confidence"]
usage, including cached and reasoning tokens UsageDetails
Native answer and decision resource RawRepresentation on each answer and on the response

Contract enforcement, errors and ownership

  • Correlation. Native answers are matched to questions by name, and the adapter returns one answer per question in request order. A question the service didn't answer becomes an UnansweredDecisionAnswer with no reason. Answers to questions that weren't asked are ignored, and if a name repeats, the last answer wins. An answer of the wrong kind throws InvalidOperationException, because it can't be represented.
  • Distributions. Probabilities are passed through as the service reported them, in its order and without filling in omitted options. If an ID repeats, the last value wins. Checking IDs against the question's candidates or levels is left to the consumer, such as typed binding in Add Layer 2 decision interoperability #7796.
  • Scores. Score probabilities are keyed by level label. The reported score is clamped to the level scale to absorb rounding in the value the service computes.
  • Numbers. Single-precision values from the service are converted without widening artifacts, so 0.1f maps to 0.1. Non-finite values throw InvalidOperationException, as do values the answer types reject, such as probabilities outside [0, 1].
  • Inputs. A request with no state (State is null) and no contents throws ArgumentException (request) before any service call. Explicit JSON-null state counts as state, as Add experimental provider-neutral decision abstractions (Layer 1) #7795 documents.
  • Content. Unsupported content throws NotSupportedException and is never dropped. Candidate and level descriptions must be text, because OpenAI supports only text there.
  • Service errors. SDK exceptions such as ClientResultException propagate unchanged, as with the OpenAI chat adapters. The adapter does no wrapping or transient classification.
  • Ownership. The caller owns the DecisionsClient. Disposing the adapter does nothing.

Changes since the previous revision

Feedback on #7795 Change
DecisionResponse.Validate and UnansweredDecisionAnswer.Message were removed Rebased onto #7795. The adapter no longer calls Validate; its own name-based correlation already enforces the contract. Added a test for an extra answer to a question that wasn't asked.
#7795 replaced the JsonTypeInfo<TState> state overloads with default and JsonSerializerOptions overloads, mirroring IChatClient.GetResponseAsync<T>; DecisionRequest with a JsonElement remains the escape hatch Rebased onto #7795. The README sample uses the simple overload with a record. Added live integration tests for record state, string state, and record state with image contents.
Live validation of string state returned HTTP 400, because the service accepts only objects in input_json Non-object state is now sent as text (see Mapping). Added a unit test for each JSON kind.
#7795 removed DecisionClientException (77484f3867) Merged the new base (no rebase). Removed the ClientResultException wrapping and transient classification; service errors now propagate as SDK exceptions. The service-error test now asserts ClientResultException with the original status.
#7795 review updates (bc36be3e4e): DecisionRequest(questions) { State, Contents }, Choice/Score constructors take candidates or levels before instructions, IList<AIContent> content snapshots, DecisionResponse.ResponseId removed, and each implementation must validate that a request has state, contents, or both Merged the new base (no rebase). The content helpers take IList<AIContent>; tests, integration tests, and README use the new shapes. GetDecisionAsync throws ArgumentException for a request with neither state nor contents, before building options or calling the service. Explicit JSON-null state was previously dropped, which would have sent an empty input; it is now sent as input_text null, and the unreachable Undefined case was removed. The adapter never mapped ResponseId. Added tests for no input (null and empty contents), state only, JSON-null state only, and contents only.
#7795 renamed IDecisionClient.GetResponseAsync to GetDecisionAsync Renamed the adapter's implementation. The name now lines up with the DecisionsClient.CreateDecisionAsync call it wraps.
#7795 removed DecisionProtocolException and stopped requiring complete, request-ordered distributions Mapping failures throw InvalidOperationException. Mapping is lenient where the response is still usable: missing answers become unanswered, extra answers are ignored, repeated names and IDs keep the last value, and distributions pass through as reported. The adapter still throws for a kind mismatch, a choice that isn't a string, and non-finite or out-of-range values.

Suggested review focus

  1. Binary outcome descriptions. Is appending them to the predicate instructions acceptable, or should they be rejected?
  2. Score clamping. Should the adapter clamp a slightly out-of-range score, or throw?
  3. Confidence. Native confidence is exposed only through AdditionalProperties["confidence"]. Does it warrant a first-class property later?
  4. Image detail. Is a "detail" additional property on the content the right way to choose the detail level, consistent with the chat adapters?

Review map

Path What to look at
src/Libraries/Microsoft.Extensions.AI.OpenAI/OpenAIDecisionClient.cs Mapping and contract enforcement
src/Libraries/Microsoft.Extensions.AI.OpenAI/OpenAIClientExtensions.cs Public entry point
src/Libraries/Microsoft.Extensions.AI.OpenAI/Microsoft.Extensions.AI.OpenAI.json API baseline
src/Libraries/Microsoft.Extensions.AI.OpenAI/README.md Usage
test/Libraries/Microsoft.Extensions.AI.OpenAI.Tests/OpenAIDecisionClientTests.cs Wire-level unit tests
test/Libraries/Microsoft.Extensions.AI.OpenAI.Tests/OpenAIDecisionClientIntegrationTests.cs Live tests, skipped unless configured

Validation and review

Validated locally at head 3bbb83549b (merge 5f2c51479a of base 77484f3867, plus the adapter change).

Suite TFMs Result
Microsoft.Extensions.AI.OpenAI build netstandard2.0, net462, net8.0, net9.0, net10.0, net11.0 0 warnings, 0 errors
OpenAIDecisionClientTests + OpenAIDecisionClientIntegrationTests (filtered) net11.0 32 passed, 5 skipped (live tests), 0 failed
Full Microsoft.Extensions.AI.OpenAI.Tests net11.0, net10.0, net9.0, net8.0 430 passed, 168 skipped, 0 failed on each
Full Microsoft.Extensions.AI.OpenAI.Tests net472 430 passed, 166 skipped, 0 failed

With the input check and JSON-null mapping reverted, the four affected unit-test cases fail (no state with null contents, no state with empty contents, JSON-null state only, and the JSON-null case of the per-kind mapping test).

Live tests were not run on this revision. No OpenAI:* integration configuration was available, so the five OpenAIDecisionClientIntegrationTests were skipped. In particular, whether the service accepts input_text null as the only input is not yet validated live. The earlier live results (5/5 against Azure OpenAI gpt-6-luna on net10.0 at 6c43336080, plus probes for data-URI and detail=low images, images in predicate instructions, zero-probability options, and score probabilities with value and label) predate this change. Three bugs found during those runs were fixed: a null image detail went through an implicit SDK conversion, a float-to-double conversion differed on net11.0, and non-object state was sent as input_json.

The integration tests are enabled through OpenAI:Mode/OpenAI:Endpoint plus OpenAI:DecisionModel. They are skipped otherwise.

Service behavior. The deployment used for earlier validation reported zero output tokens, so OutputTokenCount was 0 in those runs. The adapter reports what the service returns.

Hosted CI for this stacked draft is not claimed here. This does not constitute API review approval.

@luisquintanilla

Copy link
Copy Markdown
Contributor Author

cc: @achandmsft

@luisquintanilla
luisquintanilla force-pushed the luisquintanilla-decision-model-abstraction branch 2 times, most recently from dac27e4 to fa041dc Compare November 18, 2026 20:11
luisquintanilla and others added 4 commits November 18, 2026 15:54
Adds an experimental AsIDecisionClient extension over OpenAI.Decisions.DecisionsClient.
Maps JSON state, text, and image contents (data and URI, with optional detail) and
binary, choice, and score questions to the Decisions API, and maps predicate, choice,
score, and refusal answers back to the provider-neutral abstractions with validation.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
FromOpenAIDecision already correlates answers by name in request order, checks kinds, and maps distributions into request order, so the DecisionResponse.Validate call is removed. Adds a test for an answer to a question that was not asked.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Follow the IDecisionClient rename in the abstractions. Update the OpenAI
adapter, the decisions README sample, and the unit and integration
tests. Chat client members are unchanged.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
The service accepts only JSON objects as JSON input, so string state is now sent as text, null state is omitted, and other JSON values are sent as their JSON text. Add integration tests for record state, string state, and record state with image contents using the GetDecisionAsync state overload, and update the README sample to use it.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@luisquintanilla
luisquintanilla force-pushed the luisquintanilla-decision-model-abstraction branch from fa041dc to b91535f Compare November 18, 2026 21:08
luisquintanilla and others added 6 commits November 18, 2026 21:51
- Questions the service did not answer become UnansweredDecisionAnswer.
- Answers for questions that were not asked are ignored, and when a question
  is answered more than once the last answer wins.
- Distributions are passed through as reported instead of being zero-filled
  and reordered to the request.
- Kind mismatches and invalid values still throw InvalidOperationException.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…apter

Adopt the updated DecisionRequest shape and Choice/Score constructor order from the base API, and take IList<AIContent> in the content helpers. Reject requests that provide neither state nor contents before any service call, and send explicit JSON-null state as raw JSON text instead of silently dropping it. Add focused tests and update the README.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
DecisionClientException was removed from the abstractions. Stop wrapping ClientResultException and drop the transient classification so SDK exceptions propagate unchanged, as the OpenAI chat adapters do. Argument validation and malformed-response checks are unchanged.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…I choice and score questions

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-ai Microsoft.Extensions.AI libraries

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants