Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions issue-spec/specs/ai-proxy-orchestration-contracts/spec.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# ai-proxy-orchestration-contracts

## Purpose

Define the long-lived behavior contract for this capability.

Proposal Issues:
- https://github.com/apache/shenyu/issues/8465

## Requirements

### Requirement: cohesive AI Proxy planning and execution contracts

The AI Proxy MUST separate request planning from reactive attempt execution, MUST keep retry and fallback policy outside Protocol, Provider, Converter, and Transport implementations, and MUST expose explicit Provider capabilities and request-scoped response adaptation while preserving built-in wire, configuration, replay-policy, streaming, cancellation, commitment, and observation behavior.

#### Scenario: prepare an exchange without transport execution

- **WHEN** a valid native or converted AI request is planned
- **THEN** the planner prepares routing, conversion, Provider request, response adapters, and replay metadata without opening an upstream connection

#### Scenario: coordinate retry and fallback with cohesive state

- **WHEN** an eligible upstream status or transport failure occurs before downstream output commitment
- **THEN** the execution pipeline applies retry, Retry-After, shared-deadline, replay-safety, and fallback decisions without moving policy into an extension implementation

#### Scenario: preserve committed streaming behavior

- **WHEN** streaming output has reached downstream or the active subscription is cancelled
- **THEN** the pipeline starts no replay, preserves backpressure, and propagates cancellation with per-subscription conversion state

#### Scenario: prepare through the explicit Provider contract

- **WHEN** the planner invokes a registered Provider
- **THEN** the Provider explicitly declares capabilities and returns the upstream request with its request-scoped response adapter through prepareRequest

#### Scenario: keep orchestration ownership focused

- **WHEN** the Engine plans and executes one logical request
- **THEN** `AiExchangePlanner` owns decoding, routing, conversion, Provider preparation and prepared metadata; `AiExecutionCoordinator` owns subscription-local execution and caching; and the attempt orchestrator, executor and response consumer own retry/fallback transitions, one upstream subscription, response commitment, backpressure and cancellation

#### Scenario: construct the Engine through one public contract

- **WHEN** a programmatic integration constructs an `AiProxyEngine`
- **THEN** it uses `AiProxyEngine.builder(protocols, providers, routeResolver, transport)` and optional policy setters while the planner, coordinator and attempt implementation types remain package-private

#### Scenario: migrate Java extension implementations explicitly

- **WHEN** an implementation migrates from the previous experimental Java API
- **THEN** it replaces Provider `buildRequest` with explicit `capabilities` and `prepareRequest`, replaces Engine constructor overloads with the builder, and updates event and observation imports to their focused packages

#### Scenario: deny exact caching by default

- **WHEN** a custom Protocol or Provider does not explicitly declare exact-response-cache compatibility for the target protocol
- **THEN** the prepared exchange is not eligible for exact response caching

#### Scenario: keep built-in compatibility during Java API consolidation

- **WHEN** the orchestration and Java extension contracts are consolidated
- **THEN** existing Admin and selector configuration, byte-preserving native paths, built-in routing, replay eligibility, response metadata, and forwarded error paths retain established behavior

#### Scenario: isolate attempt observation from request results

- **WHEN** an attempt listener or logical-call observer throws while receiving bounded lifecycle facts
- **THEN** the request result remains unchanged and the event contains no prompt, response, credential, or endpoint data

Source SPEC comments:
- https://github.com/apache/shenyu/issues/8465#issuecomment-6816631104
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,15 @@ void cancelSealsActiveAttemptBeforeLogicalEventAndIgnoresLateFacts() {
final AiRequestObservation observation = new AiRequestObservation(sink, base);
final AiRequestObservation.Attempt attempt = observation.startAttempt(base, AiAttemptEvent.Kind.PRIMARY, "openai", "openai-chat", true);
attempt.status(200);
attempt.streamEvidence(AiStreamCompletion.Evidence.PENDING);
observation.finish(SignalType.CANCEL, 200);
attempt.usage(new AiUsage(1L, 1L, 2L, AiUsage.Status.REPORTED));
attempt.finish(SignalType.ON_COMPLETE, null);
observation.updateContext(base.withIdentity("late", "late"));
assertEquals(List.of("attempt", "terminal"), sink.order);
assertEquals(AiCallOutcome.CANCELLED, sink.attempts.get(0).outcome());
assertEquals(AiStreamCompletion.Evidence.SOURCE_CANCELLED, sink.attempts.get(0).completion().evidence());
assertEquals(AiStreamCompletion.Framing.NOT_INSPECTED, sink.attempts.get(0).completion().framing());
assertEquals(AiCallOutcome.CANCELLED, sink.events.get(0).outcome());
assertSame(AiUsage.UNKNOWN, sink.events.get(0).usage());
assertNull(observation.getContext().getTenant());
Expand Down
192 changes: 161 additions & 31 deletions shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,156 @@ See the License for the specific language governing permissions and
limitations under the License.
-->

# AI Proxy protocol conversion with Connect
# AI Proxy

AI Proxy decodes a client AI request, selects a provider-native protocol, prepares
the upstream request, and returns the response in the client protocol. The engine
owns HTTP execution, retries, fallback, caching and observation. Protocol and
provider implementations describe their own formats and service behavior.

## Developer entry points

The built-in implementations are the extension references:

| Task | Start here | What to learn |
| --- | --- | --- |
| Understand the public execution entry point | [AiProxyEngine](src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngine.java) | Request and response stages, execution ownership |
| Follow request planning | [AiExchangePlanner](src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiExchangePlanner.java) | Decode, route, prepare, and bind response adaptation |
| Add a native protocol | [OpenAiResponses](src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/protocol/OpenAiResponses.java) | Envelope validation, decoded request fields, outgoing options, native response passthrough |
| Add protocol stream framing or inspection | [OpenAiChat](src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/protocol/OpenAiChat.java) | SSE encoding, usage and completion inspection |
| Implement provider request construction | [OpenAi](src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/provider/OpenAi.java) | Defaults, model mapping, provider transformation, endpoint and authentication |
| Reuse request construction for a compatible service | [OpenAiCompatible](src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/provider/OpenAiCompatible.java) and [OpenAiProviderOptions](src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/provider/OpenAiProviderOptions.java) | Named profiles, native bindings and the built-in DeepSeek profile |
| Add a directional protocol conversion | [ConnectResponsesToChatConverter](src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/conversion/ConnectResponsesToChatConverter.java) | Request conversion and the matching reverse response adapter |
| Register implementations | [AiProxyPluginConfiguration](../../../shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy/src/main/java/org/apache/shenyu/springboot/starter/plugin/ai/proxy/AiProxyPluginConfiguration.java) | Protocol and provider beans collected by their factories |

## Request and response flow

```mermaid
flowchart TD
A[Client protocol decoding] --> B[Native protocol routing or conversion]
B --> C[Target protocol request preparation]
C --> D[Provider request adaptation]
D --> E[Transport execution]
E --> F[Raw target protocol response inspection]
F --> G[Provider response adaptation]
G --> H[Optional reverse protocol conversion]
H --> I[Client protocol response encoding]
I --> J[Downstream response consumption]
```

The client protocol and target protocol can differ in one exchange. For example,
a Responses request uses the OpenAI provider's native Responses binding, while a
Responses request to the Chat-only DeepSeek profile uses a Responses-to-Chat
converter. Both paths use the same engine and transport.

The internal execution pipeline coordinates observation and caching, attempt
orchestration owns primary/retry/fallback transitions, and the attempt executor
owns one upstream subscription. Protocol and provider extensions can start from
the interfaces and built-in implementations above without following these
execution internals.

Programmatic integrations should construct the public execution facade through
`AiProxyEngine.builder(protocols, providers, routeResolver, transport)` and add
only the optional policies they need. Planning, coordination and attempt classes
are package-private implementation details; protocol, provider, converter and
transport contracts remain the supported extension surface. The builder is the
single Engine construction contract and owns defaults for optional policies.

## Extending a native protocol

Use [AiProxyProtocol](src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/protocol/AiProxyProtocol.java)
and `OpenAiResponses` as the starting point:

1. Choose a unique `name()` and implement `matches()` to recognize the envelope.
Matching also runs when a selector explicitly names the protocol.
2. In `decodeRequest()`, validate the envelope and populate the protocol,
operation, raw body and a request-owned payload. Decode model, stream and token
settings when present. Preserve an absent stream value so configuration can
supply its default; keep the raw body and payload consistent.
3. Implement `prepareOutgoingRequest()` to map gateway options to native fields,
such as Responses `max_output_tokens`. The engine calls this on the target
protocol after routing/conversion and before provider preparation.
4. Choose response hooks according to the protocol. Native Responses currently
uses default byte passthrough. `OpenAiChat.encodeResponse()` demonstrates
protocol framing, while its `responseInspector()` attaches passive usage and
completion inspection. Inspectors run on the raw target-protocol response;
encoders run after provider adaptation and reverse conversion.
5. Register a protocol bean and declare a matching native binding in the provider
capabilities. Set the selector's `protocol` and `provider` identifiers.

`detectionOrder()` resolves overlapping envelope detection. Exact response caching
is an explicit opt-in; its existing native text Chat eligibility rules still apply.
Implement a converter only when clients need this protocol against an upstream
that speaks another protocol. Register its directional route and return the
request-scoped reverse response adapter together with the converted request.

## Extending a provider

Use [AiProxyProvider](src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/provider/AiProxyProvider.java)
to choose the appropriate implementation path:

- For an OpenAI-compatible service, follow the existing DeepSeek registration:
`new OpenAiCompatible("DeepSeek", OpenAiProviderOptions.deepSeek())`. A profile
declares native protocol bindings, endpoint paths, authentication, model aliases,
defaults and provider transformations. The built-in profile shows where vendor
token and dialect differences belong.
- For independent request construction, implement `name()`, `capabilities()` and
`prepareRequest()`. Return the upstream HTTP request together with its
request-scoped response adapter; do not open the connection in this method.
- When no Provider response adaptation is needed, use
`PreparedAiRequest.identity(upstreamRequest)`. When response adaptation needs
request state, allocate that state during preparation and return the matching
adapter in the same `PreparedAiRequest`.

`OpenAi.prepareRequest()` is the complete built-in reference: validate the
configuration and capabilities, prepare the provider payload, validate the final
stream setting and features, then construct the HTTP request. Its payload stage
applies defaults, model mappings and the selected native binding in that order.
Endpoint and authentication handling stay in the provider. Response adapters
transform the body lazily so the engine retains subscription and cancellation
ownership.

Register the provider as a bean with a unique provider identifier. The existing
factory collects provider beans and rejects duplicate normalized identifiers.
Native bindings declare accepted protocols; converters supply any supported
cross-protocol routes. Ordinary protocol and provider additions use the existing
engine, transport and synchronized selector configuration.

## Java API migration

This release intentionally consolidates the experimental AI Proxy Java extension
API. External integrations must migrate source code together with the gateway
artifact:

| Previous API | Replacement |
| --- | --- |
| `AiProxyProvider.buildRequest(request, config)` | Implement `capabilities()` and `prepareRequest(request, config)`; return `PreparedAiRequest.identity(upstreamRequest)` when no response adaptation is required |
| Public `AiProxyEngine` constructor overloads | `AiProxyEngine.builder(protocols, providers, routeResolver, transport)`, optional policy setters, then `build()` |
| `service.AiProxyAttemptEvent` | `service.event.AiProxyAttemptEvent` |
| `service.AiProxyAttemptListener` | `service.event.AiProxyAttemptListener` |
| `service.AiObservationSupport` | `service.observation.AiObservationSupport` |
| `service.AiUpstreamUsageTap` | Public `service.observation.AiUpstreamUsageTap` |

The `OpenAi(ProviderProfile)` constructor remains available. This does not retain
source or binary compatibility for implementations of the old Provider interface
or callers of the removed Engine constructors.

Exact response caching is also an explicit extension opt-in. A custom Provider
must override `isExactResponseCacheCompatible(targetProtocol)` for every native
target protocol it approves; the default is `false`. Protocol compatibility,
route eligibility, request shape and cache authorization are still checked
independently, so this hook alone never authorizes reuse.

Use the built-in tests as verification references:
[OpenAiResponsesTest](src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/protocol/OpenAiResponsesTest.java),
[OpenAiTest](src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/provider/OpenAiTest.java),
[AiProxyProviderHttpTest](src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/provider/AiProxyProviderHttpTest.java)
and [AiProxyEngineOrchestrationTest](src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngineOrchestrationTest.java).
Check envelope validation, optional/default values, prepared requests, response
adaptation and source-data isolation. Streaming extensions also exercise framing,
error, cancellation and backpressure through the existing engine and transport.

## Protocol conversion with Connect

The AI Proxy uses `io.github.agentic-ai-java:connect:0.1.0` for JSON protocol
conversion and explicitly selected provider dialects. ShenYu remains the
Expand Down Expand Up @@ -127,7 +276,9 @@ An opt-in, tenant/subject-isolated local cache is available for explicitly appro
bounded nonstreaming text Chat routes. It is disabled by default and requires an
application-owned cache authorization adapter; diagnostic identity and client
headers do not authorize reuse. Streams, tools, sessions, fallback and unsupported
payloads bypass. See [configuration, isolation and lifecycle limits](../../../docs/ai-exact-response-cache.md).
payloads bypass. Custom Providers default to ineligible and must override
`isExactResponseCacheCompatible(targetProtocol)` to opt in for an approved native
protocol. See [configuration, isolation and lifecycle limits](../../../docs/ai-exact-response-cache.md).

## Configuration and use

Expand Down Expand Up @@ -270,34 +421,12 @@ names and prefixes (including Bearer); query credentials and unauthenticated loc
services are also available. Generated content-type, accept and credential headers
replace conflicting profile headers case-insensitively.

Register another Chat-compatible service as a Spring bean without changing Engine,
Protocol or Transport. For example:

```java
@Bean
public AiProxyProvider tenantProvider() {
ObjectNode defaults = JsonNodeFactory.instance.objectNode();
defaults.put("temperature", 0.7);
OpenAiProviderOptions options = new OpenAiProviderOptions(
"/generate", OpenAiProviderOptions.Authentication.HEADER, "api-key", "",
Map.of("X-Tenant", "tenant-a"), Map.of("api-version", "2026-01"),
Map.of("client-alias", "upstream-model"), defaults,
AiProviderCapabilities.chat(), null)
.withRequestTransformer(OpenAiChat.NAME, (payload, context) -> {
JsonNode tokens = payload.remove("max_completion_tokens");
if (Objects.nonNull(tokens)) {
payload.set("max_tokens", tokens);
}
return payload;
});
return new OpenAiCompatible("tenant-provider", options);
}
```

Set the selector's `provider` to `tenant-provider`, its `baseUrl` to the service base
URL and its `apiKey` to the credential. The profile also works with a collection-based
`AiProxyProviderFactory` without Spring. Existing custom implementations keep their
interface contract and the `OpenAi(ProviderProfile)` constructor remains available.
Register another Chat-compatible service as a Spring bean using the built-in
DeepSeek profile and registration as the reference described above. Set the
selector's `provider` to the registered identifier, its `baseUrl` to the service
base URL and its `apiKey` to the credential. The profile also works with a collection-based
`AiProxyProviderFactory` without Spring. The `OpenAi(ProviderProfile)` constructor
remains available; custom Provider implementations follow the migration contract above.

Model precedence is configured routed model, then client model, then profile default.
Alias mapping applies to the selected model. Defaults fill only absent fields; explicit
Expand All @@ -309,7 +438,8 @@ are copied and per-request changes do not mutate the registered profile. Profile
representations omit headers, query values and body defaults.

Provider response differences remain in the request-bound Connect response adapter or
the existing `AiProxyProvider.adaptResponse` hook. DeepSeek Chat response fields, including
the `PreparedAiRequest.responseAdapter()` returned by `AiProxyProvider.prepareRequest`.
DeepSeek Chat response fields, including
`reasoning_content` and vendor usage fields, remain passthrough for Chat clients; Connect
converts reasoning and usage for Responses clients. Providers do not open connections,
configure pools/timeouts, write client responses, or implement retry/fallback policy.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@
import org.apache.shenyu.plugin.ai.proxy.enhanced.cache.AiResponseCacheScopeResolver;
import org.apache.shenyu.plugin.ai.proxy.enhanced.handler.AiProxyPluginHandler;
import org.apache.shenyu.plugin.ai.proxy.enhanced.model.AiUpstreamResponse;
import org.apache.shenyu.plugin.ai.proxy.enhanced.service.AiObservationSupport;
import org.apache.shenyu.plugin.ai.proxy.enhanced.service.AiProxyConfigService;
import org.apache.shenyu.plugin.ai.proxy.enhanced.service.config.AiProxyConfigService;
import org.apache.shenyu.plugin.ai.proxy.enhanced.service.observation.AiObservationSupport;
import org.apache.shenyu.plugin.ai.proxy.enhanced.service.AiProxyEngine;
import org.apache.shenyu.plugin.api.ShenyuPluginChain;
import org.apache.shenyu.plugin.base.AbstractShenyuPlugin;
Expand Down
Loading
Loading