Skip to content
Merged
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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2053,6 +2053,10 @@ To use a completely custom HTTP client:

## Undocumented API functionality

For endpoints without a generated service method, use the handwritten
[`CustomRequests`](docs/custom-requests.md) helper to send a relative-path request through
your existing client configuration and receive a raw response.

The SDK is typed for convenient usage of the documented API. However, it also supports working with undocumented or not yet supported parts of the API.

### Parameters
Expand Down
75 changes: 75 additions & 0 deletions docs/custom-requests.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# Custom requests

Use `CustomRequests` for a path that does not yet have a generated service method.
It snapshots an existing `OpenAIClient` configuration through `withOptions`, preserving
its transport, credentials, provider authentication hook, headers, query defaults,
retry policy, and timeouts. Creating the helper does not send a request or close the client.

```java
CustomRequests custom = CustomRequests.from(client);
CustomRequests.Request request = CustomRequests.Request.builder()
.method(HttpMethod.POST)
.path("/experimental/widgets") // Illustrative endpoint.
.putQueryParam("mode", "preview")
.putHeader("X-Preview", "enabled")
.body(JsonValue.from(Map.of("name", "example")))
.build();

try (HttpResponse response = custom.execute(request)) {
// Read response.body() using your chosen binary or JSON decoder.
}
```

These types are `com.openai.helpers.CustomRequests`, `com.openai.core.JsonValue`,
`com.openai.core.http.HttpMethod`, and `com.openai.core.http.HttpResponse`.
The helper is blocking. It supports JSON request bodies and raw response streams;
asynchronous dispatch, multipart uploads, and typed response decoding are outside this
helper's scope. Prefer generated services when available.

## Paths and configuration

Paths are unencoded resource paths relative to the configured base URL. A single leading
slash is optional and does not remove the base URL's path prefix. `/` targets that base
URL. Each segment is encoded by the normal SDK transport. Supply literal characters,
not percent-encoded strings: `%2F` represents the literal text `%2F`, not a slash.
Empty or dot segments, trailing slashes, absolute URLs, scheme-relative URLs, queries,
fragments, backslashes, and control characters are rejected. Use `putQueryParam` for
query values. Configure a different destination on the client, not in a request path.

Supported methods are GET, HEAD, POST, PUT, PATCH, DELETE, and OPTIONS. GET and HEAD
cannot have a body. Omit `body` for no body or use `JsonValue.from(null)` for JSON null.
There is no body-size limit added by this helper.

Request headers and query values replace client defaults of the same name; repeated
values within a request are retained. Credentials are resolved through the SDK's normal
request preparation and per-attempt authentication. Requests default to ordinary bearer
authentication. For an admin endpoint, explicitly select the configured admin key:

```java
.securityOptions(SecurityOptions.builder().adminApiKeyAuth(true).build())
```

`SecurityOptions` is in `com.openai.core`. The helper does not infer authentication from
the resource path or silently use an admin key for ordinary requests. `execute(request, requestOptions)`
accepts per-request timeouts. The configured client owns all transport resources.

Azure routing follows existing client configuration. On legacy Azure endpoints the SDK
adds `openai`; supply `deployments/<deployment>/...` in the resource path for a deployment
endpoint. The helper does not infer a deployment from an arbitrary JSON `model` field.
On Azure v1 endpoints, use paths relative to the configured `/openai/v1` base URL.

## Responses and errors

Successful responses are returned without reading or buffering the body. Always close
them, including when decoding fails. Streaming and binary responses use the same raw
`body()` stream; the helper does not parse SSE events or validate a response schema.
Non-2xx responses use standard SDK exceptions and are closed by the error handler.
The client's existing retry policy applies, including to retryable POST failures;
use the endpoint's idempotency contract when making requests with side effects.

The helper uses the configured client transport and options; overrides of individual
generated service methods are not involved. Request/response data and authentication
headers may be sensitive: retain normal SDK logging defaults.

See the [Java example](../openai-java-example/src/main/java/com/openai/example/CustomRequestsExample.java),
which demonstrates raw access to the existing `/models` endpoint.
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
package com.openai.helpers

import com.openai.client.OpenAIClient
import com.openai.core.ClientOptions
import com.openai.core.JsonValue
import com.openai.core.Params
import com.openai.core.RequestOptions
import com.openai.core.SecurityOptions
import com.openai.core.getPackageVersion
import com.openai.core.handlers.errorBodyHandler
import com.openai.core.handlers.errorHandler
import com.openai.core.http.Headers
import com.openai.core.http.HttpMethod
import com.openai.core.http.HttpRequest
import com.openai.core.http.HttpResponse
import com.openai.core.http.QueryParams
import com.openai.core.http.json
import com.openai.core.prepare
import java.util.Collections

/**
* Blocking requests to paths not yet exposed by generated services. Uses a snapshot of the supplied
* client's configuration and its existing transport. The caller owns the client and must close
* successful responses. Non-2xx responses use the SDK's normal exception mapping and are closed.
*
* Paths are unencoded resource paths relative to the configured base URL. Query values belong in
* [Request.Builder.putQueryParam], not the path. There is no per-request destination override.
*/
class CustomRequests private constructor(private val options: ClientOptions) {
private val errors = errorHandler(errorBodyHandler(options.jsonMapper))

companion object {
/** Capture configuration through the public client configuration hook. */
@JvmStatic
fun from(client: OpenAIClient): CustomRequests {
var options: ClientOptions? = null
client.withOptions { builder -> options = builder.build() }
val captured = checkNotNull(options) { "Client did not provide its configuration" }
val configured =
if (captured.headers.names().any { it.equals("User-Agent", ignoreCase = true) })
captured
else
captured
.toBuilder()
.defaultUserAgent(
"${client.javaClass.simpleName}/Java ${getPackageVersion()}"
)
.build()
return CustomRequests(configured)
}
}

/**
* Sends a request using normal authentication, retry and timeout policy. Returns an unparsed
* response whose body may be binary or streamed. Response schema validation does not apply.
*/
@JvmOverloads
fun execute(
request: Request,
requestOptions: RequestOptions = RequestOptions.none(),
): HttpResponse {
val httpRequest =
HttpRequest.builder()
.method(request.method)
.baseUrl(options.baseUrl())
.pathSegments(request.pathSegments)
.apply { request.body?.let { body(json(options.jsonMapper, it)) } }
.build()
.prepare(options, request, request.securityOptions)
return errors.handle(
options.httpClient.execute(
httpRequest,
requestOptions.applyDefaults(RequestOptions.from(options)),
)
)
}

/** Immutable custom request; JSON bodies use [JsonValue] to retain arbitrary API fields. */
class Request private constructor(builder: Builder) : Params {
internal val method = checkNotNull(builder.method) { "method is required" }
internal val pathSegments =
Collections.unmodifiableList(
ArrayList(checkNotNull(builder.pathSegments) { "path is required" })
)
internal val body = builder.body
internal val securityOptions = builder.securityOptions
private val headers = builder.headers.build()
private val queryParams = builder.queryParams.build()

override fun _headers(): Headers = headers

override fun _queryParams(): QueryParams = queryParams

companion object {
@JvmStatic fun builder() = Builder()
}

class Builder internal constructor() {
internal var method: HttpMethod? = null
internal var pathSegments: List<String>? = null
internal var body: JsonValue? = null
internal var securityOptions = SecurityOptions.builder().bearerAuth(true).build()
internal val headers = Headers.builder()
internal val queryParams = QueryParams.builder()

fun method(method: HttpMethod) = apply {
require(method != HttpMethod.CONNECT && method != HttpMethod.TRACE) {
"CONNECT and TRACE are not supported"
}
this.method = method
}

/** An unencoded path, optionally starting with one slash; '/' targets the base URL. */
fun path(path: String) = apply {
require(
path.isNotEmpty() &&
!path.startsWith("//") &&
!path.contains(Regex("^[a-zA-Z][a-zA-Z0-9+.-]*:"))
) {
"Path must be relative to the configured base URL"
}
require(path.none { it == '?' || it == '#' || it == '\\' || it.isISOControl() }) {
"Path must not contain a query, fragment, backslash or control character"
}
val relative = path.removePrefix("/")
val segments = if (relative.isEmpty()) emptyList() else relative.split('/')
require(segments.none { it.isEmpty() || it == "." || it == ".." }) {
"Path must not contain empty or dot segments"
}
pathSegments = segments
}

/** A JSON value, including JsonValue.from(null) for an explicit JSON null body. */
fun body(body: JsonValue) = apply { this.body = body }

/** Authentication schemes for this endpoint. Defaults to ordinary bearer auth. */
fun securityOptions(securityOptions: SecurityOptions) = apply {
this.securityOptions = securityOptions
}

fun putHeader(name: String, value: String) = apply { headers.put(name, value) }

fun putQueryParam(name: String, value: String) = apply { queryParams.put(name, value) }

fun build(): Request {
require(body == null || (method != HttpMethod.GET && method != HttpMethod.HEAD)) {
"GET and HEAD requests must not have a body"
}
return Request(this)
}
}
}
}
Loading
Loading