@effect/ai-openai-compat (#1208)

This commit is contained in:
Tim
2026-02-12 00:31:54 +00:00
committed by GitHub
parent bceef83735
commit 33f368f3c3
33 changed files with 5752 additions and 128 deletions
+1
View File
@@ -1,5 +1,6 @@
# Generated by Direnv
.direnv/
.env
# Generated by TypeScript
dist/
+1
View File
@@ -14,3 +14,4 @@ This directory contains specifications for all major features and enhancements i
- [atom-solid-bindings.md](atom-solid-bindings.md) - Add `@effect/atom-solid` bindings for Effect Atom modules in SolidJS.
- [devtools-v3-port.md](devtools-v3-port.md) - Port Effect v3 DevTools modules into `effect/unstable/devtools`.
- [cli-completions-refactor.md](cli-completions-refactor.md) - Replace dynamic CLI completions with static shell script generation for Bash, Zsh, and Fish.
- [ai-openai-compat.md](ai-openai-compat.md) - Add a minimal-schema OpenAI compat package for LanguageModel + embeddings.
+180
View File
@@ -0,0 +1,180 @@
# OpenAI Compat Package for Minimal Schemas
## Overview
Add a new package `@effect/ai-openai-compat` that provides OpenAI LanguageModel + embeddings with minimal schemas and no full codegen client. It should be a lighter alternative to `@effect/ai-openai` while keeping the same runtime behavior for LanguageModel.
## Goals
- Ship `@effect/ai-openai-compat` under `packages/ai/openai-compat`.
- Implement LanguageModel + embeddings support.
- Keep OpenAiLanguageModel feature surface aligned with `@effect/ai-openai` (tools, structured output, streaming, telemetry, provider metadata).
- Replace full generated schemas with minimal, permissive schemas covering Responses + Embeddings endpoints only.
- Keep error mapping, config, and telemetry consistent with existing OpenAI package.
## Non-goals
- Full OpenAI API coverage beyond Responses + Embeddings.
- Strict model id literal unions (without a fallback to string).
- OpenAPI codegen in the compat package.
- Changes to existing `@effect/ai-openai` behavior.
## Assumptions
- Scope includes LanguageModel + embeddings (user choice).
- LanguageModel behavior should match `@effect/ai-openai`, but schema validation is minimal and permissive.
- Any additional endpoint coverage can be layered later without codegen.
## Current State
- `@effect/ai-openai` uses `Generated.ts` with full OpenAI OpenAPI codegen.
- `OpenAiClient` depends on generated client and schemas for responses, streaming, and embeddings.
- `OpenAiLanguageModel` relies on `Generated.*` types for request/response/tool structures.
- Provider-defined tools (`OpenAiTool`) use generated schema fields for parameters and results.
## Proposed Design
### Package Layout
`packages/ai/openai-compat/`
- `src/OpenAiSchema.ts` (minimal schemas only)
- `src/OpenAiClient.ts`
- `src/OpenAiLanguageModel.ts`
- `src/OpenAiTool.ts`
- `src/OpenAiStructuredOutput.ts`
- `src/OpenAiTelemetry.ts`
- `src/OpenAiError.ts`
- `src/OpenAiConfig.ts`
- `src/internal/errors.ts`
- `src/internal/utilities.ts` (if needed by LanguageModel)
- `src/index.ts` (generated via `pnpm codegen`)
- `test/...`
- `docgen.json`, `tsconfig.json`, `vitest.config.ts`, `package.json`
### Public API Surface
Exports should mirror `@effect/ai-openai` naming so users can switch packages:
- `OpenAiSchema` (minimal schema types only; no full codegen client)
- `OpenAiClient`
- `OpenAiConfig`
- `OpenAiError`
- `OpenAiLanguageModel`
- `OpenAiStructuredOutput`
- `OpenAiTelemetry`
- `OpenAiTool`
### Compatibility Notes
- Runtime behavior and error semantics should match `@effect/ai-openai` for LanguageModel.
- Type compatibility is best-effort: schemas are intentionally permissive, and model id literals are augmented with a string fallback.
- Schema decoding should accept unknown fields from the API; unknown stream events should be ignored, not treated as errors.
### Minimal Schema Strategy
- Create `OpenAiSchema.ts` manually (no codegen) with only:
- `CreateResponse` request schema (fields used by LanguageModel).
- `Response`, `ResponseUsage`, `ResponseStreamEvent` schemas (fields used for LM output conversion).
- `Tool` and tool call item schemas needed by LM and `OpenAiTool`.
- `Annotation` schema for citations.
- `CreateEmbeddingRequest` and `CreateEmbeddingResponse` schemas.
- Use permissive schemas to avoid breakage:
- Keep the known model literal list but allow any string as a fallback (e.g. `Schema.Union([Schema.Literals([...]), Schema.String])`).
- Allow unknown keys via `Schema.Record(Schema.String, Schema.Json)` or non-strict annotations where supported.
- For tool-specific payloads, use `Schema.Json` for nested structures not required by LM logic.
- Provide type exports matching names used in `OpenAiLanguageModel` so the code ports with minimal changes.
### Schema Field Matrix (Minimum)
- `CreateResponse`:
- `model`, `input`, `include`, `text.format`, `text.verbosity`, `tools`, `tool_choice`, `stream`, `store`, `conversation`.
- Optional passthrough fields used by config: `metadata`, `user`, `temperature`, `top_p`, `top_logprobs`, `max_output_tokens`, `reasoning`, `truncation`, `seed`, `service_tier`, `parallel_tool_calls`, `modalities`.
- `InputItem` and `InputContent`:
- `role` + `content` for user/system/developer.
- Content parts: `input_text`, `input_image` (file_id or image_url, detail), `input_file` (file_id, file_url, file_data, filename).
- `Tool`:
- Function tools with `name`, `description`, and JSON Schema parameters.
- Provider-defined tool names used by LM (`apply_patch`, `shell`, `local_shell`, `web_search`, `web_search_preview`, `code_interpreter`, `file_search`, `image_generation`, `mcp`, `computer_use`) with opaque args.
- `Response`:
- `id`, `model`, `created_at`, `output`, `usage`, `incomplete_details`, `service_tier`.
- Output item types handled by LM: `message`, `reasoning`, `function_call`, `apply_patch_call`, `shell_call`, `local_shell_call`, `code_interpreter_call`, `file_search_call`, `web_search_call`, `image_generation_call`, `mcp_call`, `mcp_approval_request`, `mcp_list_tools`, `computer_call` (if referenced).
- `Annotation`:
- `type`, `file_id`, `container_id`, `filename`, `index`, `url`, `title`, `start_index`, `end_index`.
- `ResponseUsage`:
- `input_tokens`, `output_tokens`, `total_tokens`, optional token details (as `Schema.Json`).
- `ResponseStreamEvent`:
- `type` plus event-specific payload for the event types referenced by streaming logic.
- Unknown event fallback: `{ type: string; [key: string]: Json }`.
- `CreateEmbeddingRequest`:
- `model`, `input`, `dimensions`, `encoding_format`, `user`.
- `CreateEmbeddingResponse`:
- `data[]` with `embedding: number[]`, `index`, `object`, plus `model` and `usage` when present.
### OpenAiClient (compat)
- Implement HTTP calls directly using `HttpClient`:
- `createResponse`: POST `/responses`.
- `createResponseStream`: POST `/responses` with `stream: true`, decode SSE via `Sse.decodeSchema` using minimal `ResponseStreamEvent` schema.
- `createEmbedding`: POST `/embeddings`.
- Reuse `OpenAiConfig` for optional client transform.
- Reuse error mapping from `packages/ai/openai/src/internal/errors.ts`, swapping schema references to minimal ones.
- Keep headers, API key, org/project handling identical to existing client.
### OpenAiLanguageModel (compat)
- Port `OpenAiLanguageModel.ts` with minimal changes:
- Use compat `Generated` types and schemas.
- `Model` type should be a union of known literals plus `string & {}` (allow any string).
- Keep tool mapping, structured output, streaming, reasoning, and metadata behavior consistent.
- Ensure request construction uses minimal `CreateResponse` schema with permissive extra fields.
- Continue to use `OpenAiStructuredOutput` for JSON schema conversion.
- Continue to add OpenAI telemetry attributes via `OpenAiTelemetry`.
### Streaming Semantics
- Decode SSE events with `Sse.decodeSchema` using minimal `ResponseStreamEvent`.
- Handle the same event types as `@effect/ai-openai`; unknown events should be ignored.
- Treat `response.completed`, `response.incomplete`, and `response.failed` as terminal events that emit a finish part.
### OpenAiTool (compat)
- Keep provider-defined tools but relax schemas:
- Parameters and outputs for complex tools use `Schema.Json` or minimal structs.
- Avoid importing full generated field schemas.
- If tool definitions are too heavy, defer any extra options to follow-up work, but base LM tool calling stays intact.
### Docs and Exports
- `docgen.json` should exclude `src/OpenAiSchema.ts` and `src/internal/**`.
- `index.ts` must be generated via `pnpm codegen` (no manual edits).
### Workspace Updates
- Add new path mappings in `tsconfig.json` and `tsconfig.packages.json`:
- `@effect/ai-openai-compat` and `@effect/ai-openai-compat/*`.
- Ensure `pnpm-lock.yaml` updates after workspace install.
## Testing Plan
- Add tests under `packages/ai/openai-compat/test`:
- `OpenAiCompatClient.test.ts`: headers, request paths, error mapping, embedding request/response decode.
- `OpenAiCompatLanguageModel.test.ts`: port key LM tests (generateText, streamText, tool calls, structured output).
- Add a focused test for permissive schema handling (unknown fields in response or stream event).
- Use `@effect/vitest` and `it.effect` pattern, matching existing tests.
## Validation
- Run `pnpm lint-fix`.
- Run `pnpm test <new test file>` for each new test file.
- Run `pnpm check` (if failing, `pnpm clean` then re-run).
- Run `pnpm build`.
- Run `pnpm docgen`.
## Implementation Plan
1. Scaffold `packages/ai/openai-compat` with `package.json`, `tsconfig.json`, `vitest.config.ts`, `docgen.json`, base `src` folder, and workspace path mappings. Include minimal, valid module stubs required by exports so `pnpm check/build/docgen` can pass once codegen runs.
2. Implement minimal `src/OpenAiSchema.ts`, `OpenAiClient.ts`, `OpenAiConfig.ts`, `OpenAiError.ts`, and `src/internal/errors.ts` together, with direct HTTP calls and permissive schemas for Responses + Embeddings.
3. Implement `OpenAiLanguageModel`, `OpenAiTelemetry`, `OpenAiStructuredOutput`, `OpenAiTool`, and any shared utilities in one step to keep feature parity and avoid validation gaps.
4. Add compat test suite (client, LM, structured output/tool smoke, permissive schema handling) using `@effect/vitest` patterns.
5. Run `pnpm codegen` to generate `src/index.ts` exports and then run validations: `pnpm lint-fix`, `pnpm test <new tests>`, `pnpm check` (and `pnpm clean` if needed), `pnpm build`, `pnpm docgen`.
+14 -27
View File
@@ -58,7 +58,7 @@ export interface Service {
Type extends {
readonly id?: string | undefined
readonly event: string
readonly data: unknown
readonly data: string
},
DecodingServices
>(
@@ -247,7 +247,7 @@ export const make = Effect.fnUntraced(
Type extends {
readonly id?: string | undefined
readonly event: string
readonly data: unknown
readonly data: string
},
DecodingServices
>(schema: Schema.Decoder<Type, DecodingServices>) =>
@@ -260,12 +260,7 @@ export const make = Effect.fnUntraced(
Effect.map((response) => response.stream),
Stream.unwrap,
Stream.decodeText(),
Stream.pipeThroughChannel(Sse.decodeSchema<
Type,
DecodingServices,
HttpClientError.HttpClientError,
unknown
>(schema))
Stream.pipeThroughChannel(Sse.decodeSchema(schema))
)
const createMessage = (options: {
@@ -287,31 +282,23 @@ export const make = Effect.fnUntraced(
type: Schema.Literal("ping")
})
const SseEvent = Schema.Struct({
...Sse.EventEncoded.fields,
data: Schema.Union([
PingEvent,
Generated.BetaMessageStartEvent,
Generated.BetaMessageDeltaEvent,
Generated.BetaMessageStopEvent,
Generated.BetaContentBlockStartEvent,
Generated.BetaContentBlockDeltaEvent,
Generated.BetaContentBlockStopEvent,
Generated.BetaErrorResponse
])
})
const MessageEvent = Schema.Union([
PingEvent,
Generated.BetaMessageStartEvent,
Generated.BetaMessageDeltaEvent,
Generated.BetaMessageStopEvent,
Generated.BetaContentBlockStartEvent,
Generated.BetaContentBlockDeltaEvent,
Generated.BetaContentBlockStopEvent,
Generated.BetaErrorResponse
])
const buildMessageStream = (
response: HttpClientResponse.HttpClientResponse
): [HttpClientResponse.HttpClientResponse, Stream.Stream<MessageStreamEvent, AiError.AiError>] => {
const stream = response.stream.pipe(
Stream.decodeText(),
Stream.pipeThroughChannel(Sse.decodeSchema<
typeof SseEvent.Type,
typeof SseEvent.DecodingServices,
HttpClientError.HttpClientError,
unknown
>(SseEvent)),
Stream.pipeThroughChannel(Sse.decodeDataSchema(MessageEvent)),
Stream.takeUntil((event) => event.data.type === "message_stop"),
Stream.map((event) => event.data),
Stream.filter((event): event is MessageStreamEvent => event.type !== "ping"),
+20
View File
@@ -0,0 +1,20 @@
{
"$schema": "../../node_modules/@effect/docgen/schema.json",
"srcLink": "https://github.com/Effect-TS/effect/tree/main/packages/ai/openai-compat/src/",
"exclude": ["src/internal/**"],
"examplesCompilerOptions": {
"noEmit": true,
"strict": true,
"skipLibCheck": true,
"moduleResolution": "Bundler",
"module": "ES2022",
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"rewriteRelativeImportExtensions": true,
"allowImportingTsExtensions": true,
"paths": {
"effect": ["../../../effect/src/index.js"],
"effect/*": ["../../../effect/src/*.js"]
}
}
}
+68
View File
@@ -0,0 +1,68 @@
{
"name": "@effect/ai-openai-compat",
"version": "3.0.0",
"type": "module",
"license": "MIT",
"description": "An OpenAI compat integration for Effect",
"homepage": "https://effect.website",
"repository": {
"type": "git",
"url": "https://github.com/Effect-TS/effect-smol.git",
"directory": "packages/ai/openai-compat"
},
"bugs": {
"url": "https://github.com/Effect-TS/effect-smol/issues"
},
"tags": [
"typescript",
"ai",
"openai",
"compat"
],
"keywords": [
"typescript",
"ai",
"openai",
"compat"
],
"sideEffects": [],
"exports": {
"./package.json": "./package.json",
".": "./src/index.ts",
"./*": "./src/*.ts",
"./internal/*": null,
"./*/index": null
},
"files": [
"src/**/*.ts",
"dist/**/*.js",
"dist/**/*.js.map",
"dist/**/*.d.ts",
"dist/**/*.d.ts.map"
],
"publishConfig": {
"provenance": true,
"exports": {
"./package.json": "./package.json",
".": "./dist/index.js",
"./*": "./dist/*.js",
"./internal/*": null,
"./*/index": null
}
},
"scripts": {
"codegen": "effect-utils codegen",
"build": "tsc -b tsconfig.json && pnpm babel",
"build:tsgo": "tsgo -b tsconfig.json && pnpm babel",
"babel": "babel dist --plugins annotate-pure-calls --out-dir dist --source-maps",
"check": "tsc -b tsconfig.json",
"test": "vitest",
"coverage": "vitest --coverage"
},
"devDependencies": {
"effect": "workspace:^"
},
"peerDependencies": {
"effect": "workspace:^"
}
}
@@ -0,0 +1,998 @@
/**
* @since 1.0.0
*/
import * as Array from "effect/Array"
import type * as Config from "effect/Config"
import * as Effect from "effect/Effect"
import { identity, pipe } from "effect/Function"
import * as Layer from "effect/Layer"
import * as Redacted from "effect/Redacted"
import * as Schema from "effect/Schema"
import * as ServiceMap from "effect/ServiceMap"
import * as Stream from "effect/Stream"
import type * as AiError from "effect/unstable/ai/AiError"
import * as Sse from "effect/unstable/encoding/Sse"
import * as Headers from "effect/unstable/http/Headers"
import * as HttpClient from "effect/unstable/http/HttpClient"
import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest"
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse"
import * as Errors from "./internal/errors.ts"
import { OpenAiConfig } from "./OpenAiConfig.ts"
/**
* @since 1.0.0
* @category models
*/
export interface Service {
readonly client: HttpClient.HttpClient
readonly createResponse: (
options: CreateResponseRequestJson
) => Effect.Effect<
[body: CreateResponse200, response: HttpClientResponse.HttpClientResponse],
AiError.AiError
>
readonly createResponseStream: (
options: Omit<CreateResponseRequestJson, "stream" | "stream_options">
) => Effect.Effect<
[
response: HttpClientResponse.HttpClientResponse,
stream: Stream.Stream<CreateResponse200Sse, AiError.AiError>
],
AiError.AiError
>
readonly createEmbedding: (
options: CreateEmbeddingRequestJson
) => Effect.Effect<CreateEmbedding200, AiError.AiError>
}
/**
* @since 1.0.0
* @category service
*/
export class OpenAiClient extends ServiceMap.Service<OpenAiClient, Service>()(
"@effect/ai-openai-compat/OpenAiClient"
) {}
/**
* @since 1.0.0
* @category models
*/
export type Options = {
readonly apiKey?: Redacted.Redacted<string> | undefined
readonly apiUrl?: string | undefined
readonly organizationId?: Redacted.Redacted<string> | undefined
readonly projectId?: Redacted.Redacted<string> | undefined
readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined
}
const RedactedOpenAiHeaders = {
OpenAiOrganization: "OpenAI-Organization",
OpenAiProject: "OpenAI-Project"
}
/**
* @since 1.0.0
* @category constructors
*/
export const make = Effect.fnUntraced(
function*(options: Options): Effect.fn.Return<Service, never, HttpClient.HttpClient> {
const baseClient = yield* HttpClient.HttpClient
const httpClient = baseClient.pipe(
HttpClient.mapRequest((request) =>
request.pipe(
HttpClientRequest.prependUrl(options.apiUrl ?? "https://api.openai.com/v1"),
options.apiKey !== undefined
? HttpClientRequest.bearerToken(Redacted.value(options.apiKey))
: identity,
options.organizationId !== undefined
? HttpClientRequest.setHeader(
RedactedOpenAiHeaders.OpenAiOrganization,
Redacted.value(options.organizationId)
)
: identity,
options.projectId !== undefined
? HttpClientRequest.setHeader(
RedactedOpenAiHeaders.OpenAiProject,
Redacted.value(options.projectId)
)
: identity,
HttpClientRequest.acceptJson
)
),
options.transformClient !== undefined
? options.transformClient
: identity
)
const resolveHttpClient = Effect.map(
OpenAiConfig.getOrUndefined,
(config) =>
config?.transformClient !== undefined
? config.transformClient(httpClient)
: httpClient
)
const decodeResponse = HttpClientResponse.schemaBodyJson(ChatCompletionResponse)
const createResponse = (
payload: CreateResponseRequestJson
): Effect.Effect<
[body: CreateResponse200, response: HttpClientResponse.HttpClientResponse],
AiError.AiError
> =>
Effect.flatMap(resolveHttpClient, (client) =>
pipe(
HttpClientRequest.post("/chat/completions"),
HttpClientRequest.bodyJsonUnsafe(payload),
HttpClient.filterStatusOk(client).execute,
Effect.flatMap((response) =>
Effect.map(decodeResponse(response), (
body
): [CreateResponse200, HttpClientResponse.HttpClientResponse] => [
body,
response
])
),
Effect.catchTags({
HttpClientError: (error) => Errors.mapHttpClientError(error, "createResponse"),
SchemaError: (error) => Effect.fail(Errors.mapSchemaError(error, "createResponse"))
})
))
const buildResponseStream = (
response: HttpClientResponse.HttpClientResponse
): [
HttpClientResponse.HttpClientResponse,
Stream.Stream<CreateResponse200Sse, AiError.AiError>
] => {
const stream = response.stream.pipe(
Stream.decodeText(),
Stream.pipeThroughChannel(Sse.decode()),
Stream.flatMap((event) => {
const data = decodeChatCompletionSseData(event.data)
return Stream.fromIterable(data !== undefined ? [data] : [])
}),
Stream.takeUntil((event) => event === "[DONE]"),
Stream.catchTags({
Retry: (error) => Stream.die(error),
HttpClientError: (error) => Stream.fromEffect(Errors.mapHttpClientError(error, "createResponseStream"))
})
) as any
return [response, stream]
}
const createResponseStream: Service["createResponseStream"] = (payload) =>
Effect.flatMap(resolveHttpClient, (client) =>
pipe(
HttpClientRequest.post("/chat/completions"),
HttpClientRequest.bodyJsonUnsafe({
...payload,
stream: true,
stream_options: {
include_usage: true
}
}),
HttpClient.filterStatusOk(client).execute,
Effect.map(buildResponseStream),
Effect.catchTag(
"HttpClientError",
(error) => Errors.mapHttpClientError(error, "createResponseStream")
)
))
const decodeEmbedding = HttpClientResponse.schemaBodyJson(CreateEmbeddingResponseSchema)
const createEmbedding = (
payload: CreateEmbeddingRequestJson
): Effect.Effect<CreateEmbedding200, AiError.AiError> =>
Effect.flatMap(resolveHttpClient, (client) =>
pipe(
HttpClientRequest.post("/embeddings"),
HttpClientRequest.bodyJsonUnsafe(payload),
HttpClient.filterStatusOk(client).execute,
Effect.flatMap(decodeEmbedding),
Effect.catchTags({
HttpClientError: (error) => Errors.mapHttpClientError(error, "createEmbedding"),
SchemaError: (error) => Effect.fail(Errors.mapSchemaError(error, "createEmbedding"))
})
))
return OpenAiClient.of({
client: httpClient,
createResponse,
createResponseStream,
createEmbedding
})
},
Effect.updateService(
Headers.CurrentRedactedNames,
Array.appendAll(Object.values(RedactedOpenAiHeaders))
)
)
/**
* @since 1.0.0
* @category layers
*/
export const layer = (options: Options): Layer.Layer<OpenAiClient, never, HttpClient.HttpClient> =>
Layer.effect(OpenAiClient, make(options))
/**
* @since 1.0.0
* @category layers
*/
export const layerConfig = (options?: {
readonly apiKey?: Config.Config<Redacted.Redacted<string>> | undefined
readonly apiUrl?: Config.Config<string> | undefined
readonly organizationId?: Config.Config<Redacted.Redacted<string>> | undefined
readonly projectId?: Config.Config<Redacted.Redacted<string>> | undefined
readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined
}): Layer.Layer<OpenAiClient, Config.ConfigError, HttpClient.HttpClient> =>
Layer.effect(
OpenAiClient,
Effect.gen(function*() {
const apiKey = options?.apiKey !== undefined
? yield* options.apiKey :
undefined
const apiUrl = options?.apiUrl !== undefined
? yield* options.apiUrl :
undefined
const organizationId = options?.organizationId !== undefined
? yield* options.organizationId
: undefined
const projectId = options?.projectId !== undefined
? yield* options.projectId :
undefined
return yield* make({
apiKey,
apiUrl,
organizationId,
projectId,
transformClient: options?.transformClient
})
})
)
type JsonObject = { readonly [x: string]: Schema.Json }
/**
* @since 1.0.0
*/
export type IncludeEnum =
| "message.input_image.image_url"
| "reasoning.encrypted_content"
| "message.output_text.logprobs"
/**
* @since 1.0.0
*/
export type MessageStatus = "in_progress" | "completed" | "incomplete"
type InputTextContent = {
readonly type: "input_text"
readonly text: string
}
type InputImageContent = {
readonly type: "input_image"
readonly image_url?: string | null | undefined
readonly file_id?: string | null | undefined
readonly detail?: "low" | "high" | "auto" | null | undefined
}
type InputFileContent = {
readonly type: "input_file"
readonly file_id?: string | null | undefined
readonly filename?: string | undefined
readonly file_url?: string | undefined
readonly file_data?: string | undefined
}
/**
* @since 1.0.0
*/
export type InputContent = InputTextContent | InputImageContent | InputFileContent
/**
* @since 1.0.0
*/
export type SummaryTextContent = {
readonly type: "summary_text"
readonly text: string
}
type ReasoningTextContent = {
readonly type: "reasoning_text"
readonly text: string
}
type RefusalContent = {
readonly type: "refusal"
readonly refusal: string
}
type TextContent = {
readonly type: "text"
readonly text: string
}
type ComputerScreenshotContent = {
readonly type: "computer_screenshot"
readonly image_url: string | null
readonly file_id: string | null
}
type FileCitationAnnotation = {
readonly type: "file_citation"
readonly file_id: string
readonly index: number
readonly filename: string
}
type UrlCitationAnnotation = {
readonly type: "url_citation"
readonly url: string
readonly start_index: number
readonly end_index: number
readonly title: string
}
type ContainerFileCitationAnnotation = {
readonly type: "container_file_citation"
readonly container_id: string
readonly file_id: string
readonly start_index: number
readonly end_index: number
readonly filename: string
}
type FilePathAnnotation = {
readonly type: "file_path"
readonly file_id: string
readonly index: number
}
/**
* @since 1.0.0
*/
export type Annotation =
| FileCitationAnnotation
| UrlCitationAnnotation
| ContainerFileCitationAnnotation
| FilePathAnnotation
type OutputTextContent = {
readonly type: "output_text"
readonly text: string
readonly annotations?: ReadonlyArray<Annotation> | undefined
readonly logprobs?: ReadonlyArray<unknown> | undefined
}
type OutputMessageContent =
| InputTextContent
| OutputTextContent
| TextContent
| SummaryTextContent
| ReasoningTextContent
| RefusalContent
| InputImageContent
| ComputerScreenshotContent
| InputFileContent
type OutputMessage = {
readonly id: string
readonly type: "message"
readonly role: "assistant"
readonly content: ReadonlyArray<OutputMessageContent>
readonly status: MessageStatus
}
/**
* @since 1.0.0
*/
export type ReasoningItem = {
readonly type: "reasoning"
readonly id: string
readonly encrypted_content?: string | null | undefined
readonly summary: ReadonlyArray<SummaryTextContent>
readonly content?: ReadonlyArray<ReasoningTextContent> | undefined
readonly status?: MessageStatus | undefined
}
type FunctionCall = {
readonly id?: string | undefined
readonly type: "function_call"
readonly call_id: string
readonly name: string
readonly arguments: string
readonly status?: MessageStatus | undefined
}
type FunctionCallOutput = {
readonly id?: string | null | undefined
readonly call_id: string
readonly type: "function_call_output"
readonly output: string | ReadonlyArray<InputTextContent | InputImageContent | InputFileContent>
readonly status?: MessageStatus | null | undefined
}
type CustomToolCall = {
readonly type: "custom_tool_call"
readonly id?: string | undefined
readonly call_id: string
readonly name: string
readonly input: string
}
type CustomToolCallOutput = {
readonly type: "custom_tool_call_output"
readonly id?: string | undefined
readonly call_id: string
readonly output: string | ReadonlyArray<InputTextContent | InputImageContent | InputFileContent>
}
type ItemReference = {
readonly type?: "item_reference" | null | undefined
readonly id: string
}
/**
* @since 1.0.0
*/
export type InputItem =
| {
readonly role: "user" | "assistant" | "system" | "developer"
readonly content: string | ReadonlyArray<InputContent>
readonly type?: "message" | undefined
}
| {
readonly type?: "message" | undefined
readonly role: "user" | "system" | "developer"
readonly status?: MessageStatus | undefined
readonly content: ReadonlyArray<InputContent>
}
| OutputMessage
| FunctionCall
| FunctionCallOutput
| ReasoningItem
| CustomToolCallOutput
| CustomToolCall
| ItemReference
type FunctionTool = {
readonly type: "function"
readonly name: string
readonly description?: string | null | undefined
readonly parameters?: JsonObject | null | undefined
readonly strict?: boolean | null | undefined
}
type CustomToolParam = {
readonly type: "custom"
readonly name: string
readonly description?: string | undefined
readonly format?: unknown
}
/**
* @since 1.0.0
*/
export type Tool =
| FunctionTool
| CustomToolParam
type ToolChoice =
| "none"
| "auto"
| "required"
| {
readonly type: "allowed_tools"
readonly mode: "auto" | "required"
readonly tools: ReadonlyArray<JsonObject>
}
| {
readonly type: "function"
readonly name: string
}
| {
readonly type: "custom"
readonly name: string
}
/**
* @since 1.0.0
*/
export type TextResponseFormatConfiguration =
| {
readonly type: "text"
}
| {
readonly type: "json_schema"
readonly description?: string | undefined
readonly name: string
readonly schema: JsonObject
readonly strict?: boolean | null | undefined
}
| {
readonly type: "json_object"
}
/**
* @since 1.0.0
*/
export type CreateResponse = {
readonly metadata?: Readonly<Record<string, string>> | null | undefined
readonly top_logprobs?: number | undefined
readonly temperature?: number | null | undefined
readonly top_p?: number | null | undefined
readonly user?: string | null | undefined
readonly safety_identifier?: string | null | undefined
readonly prompt_cache_key?: string | null | undefined
readonly service_tier?: string | undefined
readonly prompt_cache_retention?: "in-memory" | "24h" | null | undefined
readonly previous_response_id?: string | null | undefined
readonly model?: string | undefined
readonly reasoning?: unknown
readonly background?: boolean | null | undefined
readonly max_output_tokens?: number | null | undefined
readonly max_tool_calls?: number | null | undefined
readonly text?: {
readonly format?: TextResponseFormatConfiguration | undefined
readonly verbosity?: "low" | "medium" | "high" | null | undefined
} | undefined
readonly tools?: ReadonlyArray<Tool> | undefined
readonly tool_choice?: ToolChoice | undefined
readonly truncation?: "auto" | "disabled" | null | undefined
readonly input?: string | ReadonlyArray<InputItem> | undefined
readonly include?: ReadonlyArray<IncludeEnum> | null | undefined
readonly parallel_tool_calls?: boolean | null | undefined
readonly store?: boolean | null | undefined
readonly instructions?: string | null | undefined
readonly stream?: boolean | null | undefined
readonly conversation?: string | null | undefined
readonly modalities?: ReadonlyArray<"text" | "audio"> | undefined
readonly seed?: number | undefined
}
/**
* @since 1.0.0
*/
export type ResponseUsage = {
readonly input_tokens: number
readonly output_tokens: number
readonly total_tokens: number
readonly input_tokens_details?: unknown
readonly output_tokens_details?: unknown
}
type OutputItem =
| OutputMessage
| FunctionCall
| ReasoningItem
| CustomToolCall
/**
* @since 1.0.0
*/
export type Response = {
readonly id: string
readonly object?: "response" | undefined
readonly model: string
readonly status?: "completed" | "failed" | "in_progress" | "cancelled" | "queued" | "incomplete" | undefined
readonly created_at: number
readonly output: ReadonlyArray<OutputItem>
readonly usage?: ResponseUsage | null | undefined
readonly incomplete_details?:
| {
readonly reason?: "max_output_tokens" | "content_filter" | undefined
}
| null
| undefined
readonly service_tier?: string | undefined
}
type ResponseCreatedEvent = {
readonly type: "response.created"
readonly response: Response
readonly sequence_number: number
}
type ResponseCompletedEvent = {
readonly type: "response.completed"
readonly response: Response
readonly sequence_number: number
}
type ResponseIncompleteEvent = {
readonly type: "response.incomplete"
readonly response: Response
readonly sequence_number: number
}
type ResponseFailedEvent = {
readonly type: "response.failed"
readonly response: Response
readonly sequence_number: number
}
type ResponseOutputItemAddedEvent = {
readonly type: "response.output_item.added"
readonly output_index: number
readonly sequence_number: number
readonly item: OutputItem
}
type ResponseOutputItemDoneEvent = {
readonly type: "response.output_item.done"
readonly output_index: number
readonly sequence_number: number
readonly item: OutputItem
}
type ResponseTextDeltaEvent = {
readonly type: "response.output_text.delta"
readonly item_id: string
readonly output_index: number
readonly content_index: number
readonly delta: string
readonly sequence_number: number
readonly logprobs?: ReadonlyArray<unknown> | undefined
}
type ResponseOutputTextAnnotationAddedEvent = {
readonly type: "response.output_text.annotation.added"
readonly item_id: string
readonly output_index: number
readonly content_index: number
readonly annotation_index: number
readonly sequence_number: number
readonly annotation: Annotation
}
type ResponseFunctionCallArgumentsDeltaEvent = {
readonly type: "response.function_call_arguments.delta"
readonly item_id: string
readonly output_index: number
readonly sequence_number: number
readonly delta: string
}
type ResponseReasoningSummaryPartAddedEvent = {
readonly type: "response.reasoning_summary_part.added"
readonly item_id: string
readonly output_index: number
readonly summary_index: number
readonly sequence_number: number
readonly part: SummaryTextContent
}
type ResponseReasoningSummaryPartDoneEvent = {
readonly type: "response.reasoning_summary_part.done"
readonly item_id: string
readonly output_index: number
readonly summary_index: number
readonly sequence_number: number
readonly part: SummaryTextContent
}
type ResponseReasoningSummaryTextDeltaEvent = {
readonly type: "response.reasoning_summary_text.delta"
readonly item_id: string
readonly output_index: number
readonly summary_index: number
readonly delta: string
readonly sequence_number: number
}
type ResponseErrorEvent = {
readonly type: "error"
readonly code: string | null
readonly message: string
readonly param: string | null
readonly sequence_number: number
}
type UnknownResponseStreamEvent = {
readonly type: string
readonly [key: string]: unknown
}
/**
* @since 1.0.0
*/
export type ResponseStreamEvent =
| ResponseCreatedEvent
| ResponseCompletedEvent
| ResponseIncompleteEvent
| ResponseFailedEvent
| ResponseOutputItemAddedEvent
| ResponseOutputItemDoneEvent
| ResponseTextDeltaEvent
| ResponseOutputTextAnnotationAddedEvent
| ResponseFunctionCallArgumentsDeltaEvent
| ResponseReasoningSummaryPartAddedEvent
| ResponseReasoningSummaryPartDoneEvent
| ResponseReasoningSummaryTextDeltaEvent
| ResponseErrorEvent
| UnknownResponseStreamEvent
/**
* @since 1.0.0
*/
export type Embedding = {
readonly embedding: ReadonlyArray<number> | string
readonly index: number
readonly object?: string | undefined
}
/**
* @since 1.0.0
*/
export type CreateEmbeddingRequest = {
readonly input: string | ReadonlyArray<string> | ReadonlyArray<number> | ReadonlyArray<ReadonlyArray<number>>
readonly model: string
readonly encoding_format?: "float" | "base64" | undefined
readonly dimensions?: number | undefined
readonly user?: string | undefined
}
/**
* @since 1.0.0
*/
export type CreateEmbeddingResponse = {
readonly data: ReadonlyArray<Embedding>
readonly model: string
readonly object?: "list" | undefined
readonly usage?: {
readonly prompt_tokens: number
readonly total_tokens: number
} | undefined
}
/**
* @since 1.0.0
*/
export type CreateEmbeddingRequestJson = CreateEmbeddingRequest
/**
* @since 1.0.0
*/
export type CreateEmbedding200 = CreateEmbeddingResponse
/**
* @since 1.0.0
*/
export type ChatCompletionContentPart =
| {
readonly type: "text"
readonly text: string
}
| {
readonly type: "image_url"
readonly image_url: {
readonly url: string
readonly detail?: "low" | "high" | "auto" | undefined
}
}
/**
* @since 1.0.0
*/
export type ChatCompletionRequestToolCall = {
readonly id: string
readonly type: "function"
readonly function: {
readonly name: string
readonly arguments: string
}
}
/**
* @since 1.0.0
*/
export type ChatCompletionRequestMessage =
| {
readonly role: "system" | "developer" | "user" | "assistant"
readonly content: string | ReadonlyArray<ChatCompletionContentPart> | null
readonly tool_calls?: ReadonlyArray<ChatCompletionRequestToolCall> | undefined
}
| {
readonly role: "tool"
readonly tool_call_id: string
readonly content: string
}
/**
* @since 1.0.0
*/
export type ChatCompletionTool = {
readonly type: "function"
readonly function: {
readonly name: string
readonly description?: string | null | undefined
readonly parameters?: JsonObject | undefined
readonly strict?: boolean | undefined
}
}
/**
* @since 1.0.0
*/
export type ChatCompletionToolChoice =
| "none"
| "auto"
| "required"
| {
readonly type: "function"
readonly function: {
readonly name: string
}
}
/**
* @since 1.0.0
*/
export type ChatCompletionResponseFormat =
| {
readonly type: "json_object"
}
| {
readonly type: "json_schema"
readonly json_schema: {
readonly name: string
readonly schema: JsonObject
readonly description?: string | undefined
readonly strict?: boolean | undefined
}
}
/**
* @since 1.0.0
*/
export type ChatCompletionRequest = {
readonly model: string
readonly messages: ReadonlyArray<ChatCompletionRequestMessage>
readonly temperature?: number | null | undefined
readonly top_p?: number | null | undefined
readonly max_tokens?: number | null | undefined
readonly user?: string | null | undefined
readonly seed?: number | undefined
readonly parallel_tool_calls?: boolean | null | undefined
readonly response_format?: ChatCompletionResponseFormat | undefined
readonly tools?: ReadonlyArray<ChatCompletionTool> | undefined
readonly tool_choice?: ChatCompletionToolChoice | undefined
readonly service_tier?: string | undefined
readonly stream?: boolean | undefined
readonly stream_options?: {
readonly include_usage?: boolean | undefined
} | undefined
}
/**
* @since 1.0.0
*/
export type CreateResponseRequestJson = ChatCompletionRequest
/**
* @since 1.0.0
*/
export type CreateResponse200 = ChatCompletionResponse
/**
* @since 1.0.0
*/
export type CreateResponse200Sse = ChatCompletionStreamEvent
const EmbeddingSchema = Schema.Struct({
embedding: Schema.Union([Schema.Array(Schema.Number), Schema.String]),
index: Schema.Number,
object: Schema.optionalKey(Schema.String)
})
const CreateEmbeddingResponseSchema = Schema.Struct({
data: Schema.Array(EmbeddingSchema),
model: Schema.String,
object: Schema.optionalKey(Schema.Literal("list")),
usage: Schema.optionalKey(Schema.Struct({
prompt_tokens: Schema.Number,
total_tokens: Schema.Number
}))
})
const ChatCompletionToolFunction = Schema.Struct({
name: Schema.String,
arguments: Schema.optionalKey(Schema.String)
})
const ChatCompletionToolCall = Schema.Struct({
id: Schema.optionalKey(Schema.String),
index: Schema.optionalKey(Schema.Number),
type: Schema.optionalKey(Schema.String),
function: Schema.optionalKey(ChatCompletionToolFunction)
})
const ChatCompletionMessage = Schema.Struct({
role: Schema.optionalKey(Schema.String),
content: Schema.optionalKey(Schema.NullOr(Schema.String)),
tool_calls: Schema.optionalKey(Schema.Array(ChatCompletionToolCall))
})
const ChatCompletionDelta = Schema.Struct({
role: Schema.optionalKey(Schema.String),
content: Schema.optionalKey(Schema.NullOr(Schema.String)),
tool_calls: Schema.optionalKey(Schema.Array(ChatCompletionToolCall))
})
const ChatCompletionChoice = Schema.Struct({
index: Schema.Number,
finish_reason: Schema.optionalKey(Schema.NullOr(Schema.String)),
message: Schema.optionalKey(ChatCompletionMessage),
delta: Schema.optionalKey(ChatCompletionDelta)
})
const ChatCompletionUsage = Schema.Struct({
prompt_tokens: Schema.Number,
completion_tokens: Schema.Number,
total_tokens: Schema.Number,
prompt_tokens_details: Schema.optionalKey(Schema.Any),
completion_tokens_details: Schema.optionalKey(Schema.Any)
})
const ChatCompletionResponse = Schema.Struct({
id: Schema.String,
model: Schema.String,
created: Schema.Number,
choices: Schema.Array(ChatCompletionChoice),
usage: Schema.optionalKey(Schema.NullOr(ChatCompletionUsage)),
service_tier: Schema.optionalKey(Schema.String)
})
const ChatCompletionChunk = Schema.Struct({
id: Schema.String,
model: Schema.String,
created: Schema.Number,
choices: Schema.Array(ChatCompletionChoice),
usage: Schema.optionalKey(Schema.NullOr(ChatCompletionUsage)),
service_tier: Schema.optionalKey(Schema.String)
})
/**
* @since 1.0.0
*/
export type ChatCompletionToolCall = typeof ChatCompletionToolCall.Type
/**
* @since 1.0.0
*/
export type ChatCompletionMessage = typeof ChatCompletionMessage.Type
/**
* @since 1.0.0
*/
export type ChatCompletionChoice = typeof ChatCompletionChoice.Type
/**
* @since 1.0.0
*/
export type ChatCompletionUsage = typeof ChatCompletionUsage.Type
/**
* @since 1.0.0
*/
export type ChatCompletionResponse = typeof ChatCompletionResponse.Type
/**
* @since 1.0.0
*/
export type ChatCompletionChunk = typeof ChatCompletionChunk.Type
/**
* @since 1.0.0
*/
export type ChatCompletionStreamEvent = ChatCompletionChunk | "[DONE]"
const parseJson = (value: string): unknown => {
try {
return JSON.parse(value)
} catch {
return undefined
}
}
const isChatCompletionChunk = Schema.is(ChatCompletionChunk)
const decodeChatCompletionSseData = (
data: string
): ChatCompletionStreamEvent | undefined => {
if (data === "[DONE]") {
return data
}
const parsed = parseJson(data)
return isChatCompletionChunk(parsed)
? parsed
: undefined
}
@@ -0,0 +1,53 @@
/**
* @since 1.0.0
*/
import * as Effect from "effect/Effect"
import { dual } from "effect/Function"
import * as ServiceMap from "effect/ServiceMap"
import type { HttpClient } from "effect/unstable/http/HttpClient"
/**
* @since 1.0.0
* @category services
*/
export class OpenAiConfig extends ServiceMap.Service<
OpenAiConfig,
OpenAiConfig.Service
>()("@effect/ai-openai-compat/OpenAiConfig") {
/**
* @since 1.0.0
*/
static readonly getOrUndefined: Effect.Effect<typeof OpenAiConfig.Service | undefined> = Effect.map(
Effect.services<never>(),
(context) => context.mapUnsafe.get(OpenAiConfig.key)
)
}
/**
* @since 1.0.0
*/
export declare namespace OpenAiConfig {
/**
* @since 1.0.
* @category models
*/
export interface Service {
readonly transformClient?: ((client: HttpClient) => HttpClient) | undefined
}
}
/**
* @since 1.0.0
* @category configuration
*/
export const withClientTransform: {
(transform: (client: HttpClient) => HttpClient): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>
<A, E, R>(self: Effect.Effect<A, E, R>, transform: (client: HttpClient) => HttpClient): Effect.Effect<A, E, R>
} = dual(2, <A, E, R>(
self: Effect.Effect<A, E, R>,
transformClient: (client: HttpClient) => HttpClient
) =>
Effect.flatMap(
OpenAiConfig.getOrUndefined,
(config) => Effect.provideService(self, OpenAiConfig, { ...config, transformClient })
))
@@ -0,0 +1,102 @@
/**
* @since 1.0.0
*/
/**
* OpenAI-specific error metadata fields.
*
* @since 1.0.0
* @category models
*/
export type OpenAiErrorMetadata = {
/**
* The OpenAI error code returned by the API.
*/
readonly errorCode: string | null
/**
* The OpenAI error type returned by the API.
*/
readonly errorType: string | null
/**
* The unique request ID for debugging with OpenAI support.
*/
readonly requestId: string | null
}
/**
* OpenAI-specific rate limit metadata fields.
*
* Extends base error metadata with rate limit specific information from
* OpenAI's rate limit headers.
*
* @since 1.0.0
* @category models
*/
export type OpenAiRateLimitMetadata = OpenAiErrorMetadata & {
/**
* The rate limit type (e.g. "requests", "tokens").
*/
readonly limit: string | null
/**
* Number of remaining requests in the current window.
*/
readonly remaining: number | null
/**
* Time until the request rate limit resets.
*/
readonly resetRequests: string | null
/**
* Time until the token rate limit resets.
*/
readonly resetTokens: string | null
}
declare module "effect/unstable/ai/AiError" {
export interface RateLimitError {
readonly metadata: {
readonly openai?: OpenAiRateLimitMetadata | null
}
}
export interface QuotaExhaustedError {
readonly metadata: {
readonly openai?: OpenAiErrorMetadata | null
}
}
export interface AuthenticationError {
readonly metadata: {
readonly openai?: OpenAiErrorMetadata | null
}
}
export interface ContentPolicyError {
readonly metadata: {
readonly openai?: OpenAiErrorMetadata | null
}
}
export interface InvalidRequestError {
readonly metadata: {
readonly openai?: OpenAiErrorMetadata | null
}
}
export interface InternalProviderError {
readonly metadata: {
readonly openai?: OpenAiErrorMetadata | null
}
}
export interface InvalidOutputError {
readonly metadata: {
readonly openai?: OpenAiErrorMetadata | null
}
}
export interface UnknownError {
readonly metadata: {
readonly openai?: OpenAiErrorMetadata | null
}
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,463 @@
/**
* Provides a codec transformation for OpenAI structured output.
*
* OpenAI's API has specific constraints on JSON schema support that differ
* from the full JSON Schema specification. This module transforms Effect
* `Schema.Codec` types into a form compatible with OpenAI's structured
* output requirements by:
*
* - Converting tuples to objects with string keys (tuples are unsupported)
* - Converting optional properties to nullable unions (`T | null`)
* - Converting index signatures (records) to arrays of key-value pairs
* - Converting `oneOf` unions to `anyOf` unions
* - Merging multiple regex patterns into a single `pattern` (since OpenAI
* does not support `allOf`)
* - Preserving only OpenAI-compatible formats and descriptions
*
* @since 1.0.0
*/
import * as Arr from "effect/Array"
import type * as JsonSchema from "effect/JsonSchema"
import * as Option from "effect/Option"
import * as Predicate from "effect/Predicate"
import * as Rec from "effect/Record"
import * as Schema from "effect/Schema"
import * as AST from "effect/SchemaAST"
import * as Transformation from "effect/SchemaTransformation"
/**
* Transforms a `Schema.Codec` into a form compatible with OpenAI's
* structured output constraints.
*
* The transformation walks the schema AST and rewrites constructs that
* OpenAI does not support natively:
*
* - **Tuples** are converted to objects with numeric string keys (e.g.
* `"0"`, `"1"`) since OpenAI does not support tuple schemas. Rest
* elements are placed under a `"__rest__"` key.
* - **Optional properties** are replaced with `T | null` unions, because
* OpenAI requires all properties to be present.
* - **Records** (index signatures) are converted to arrays of `[key, value]`
* pairs.
* - **`oneOf` unions** are rewritten as `anyOf` unions.
* - **Regex patterns** from multiple filters are merged into a single
* `pattern` using lookaheads, since OpenAI does not support `allOf`.
* - **Filters and annotations** are preserved where compatible (e.g.
* `description`, supported `format` values like `"date-time"`, `"email"`,
* `"uuid"`, etc.), and stripped otherwise.
*
* If the schema is already compatible, the original codec is returned
* unchanged.
*
* @since 1.0.0
* @category Codec Transformation
*/
export function toCodecOpenAI<T, E, RD, RE>(
schema: Schema.Codec<T, E, RD, RE>
): {
codec: Schema.Codec<T, unknown, RD, RE>
jsonSchema: JsonSchema.JsonSchema
} {
const to = schema.ast
const from = recur(AST.toEncoded(to))
const codec = from === to ? schema : Schema.make<typeof schema>(AST.decodeTo(from, to, Transformation.passthrough()))
const document = Schema.toJsonSchemaDocument(codec)
const jsonSchema = rewrite(document.schema)
if (Object.keys(document.definitions).length > 0) {
jsonSchema.$defs = Rec.map(document.definitions, rewrite)
}
return { codec, jsonSchema }
}
/**
* Post-processes the JSON schema produced by `Schema.toJsonSchemaDocument`,
* recursively flattening `allOf` arrays by merging each member's keys into
* the parent object. This is necessary because OpenAI structured output does
* not support `allOf`.
*/
function rewrite(schema: JsonSchema.JsonSchema): JsonSchema.JsonSchema {
const out: JsonSchema.JsonSchema = {}
for (const [k, v] of Object.entries(schema)) {
if (k === "allOf" && Array.isArray(v)) {
for (const member of v) {
Object.assign(out, rewrite(member as JsonSchema.JsonSchema))
}
} else if (Array.isArray(v)) {
out[k] = v.map((item) =>
typeof item === "object" && item !== null && !Array.isArray(item)
? rewrite(item as JsonSchema.JsonSchema)
: item
)
} else if (typeof v === "object" && v !== null) {
out[k] = rewrite(v as JsonSchema.JsonSchema)
} else {
out[k] = v
}
}
return out
}
function recur(ast: AST.AST): AST.AST {
switch (ast._tag) {
case "Declaration":
case "Void":
case "Never":
case "Unknown":
case "Any":
case "BigInt":
case "Symbol":
case "UniqueSymbol":
case "ObjectKeyword":
case "Enum":
case "TemplateLiteral":
return unsupportedAst(
ast,
"OpenAI structured output does not support this schema kind; consider transforming the schema or using a different provider"
)
case "Undefined":
return unsupportedAst(
ast,
"OpenAI structured output does not support undefined; consider transforming the schema or using a different provider; if using `Schema.optional`, consider using `Schema.optionalKey` instead"
)
case "Null":
return ast
case "String": {
const { annotations, filters } = get(ast)
if (annotations !== undefined || filters !== undefined) {
return new AST.String(annotations, filters)
}
return ast
}
case "Number": {
const { annotations, filters } = get(ast)
if (annotations !== undefined || filters !== undefined) {
return new AST.Number(annotations, filters)
}
return ast
}
case "Boolean":
return ast
case "Literal": {
const literal = ast.literal
if (typeof literal === "string" || typeof literal === "number" || typeof literal === "boolean") {
const { annotations, filters } = get(ast)
if (annotations !== undefined || filters !== undefined) {
return new AST.Literal(ast.literal, annotations, filters)
}
return ast
}
throw new Error(
`${errorPrefix}: Unsupported literal type ${typeof literal} (value: ${
String(literal)
}) (supported: string | number | boolean)`
)
}
case "Union": {
if (ast.mode === "oneOf") {
return new AST.Union(ast.types, "anyOf", ast.annotations, ast.checks)
}
const types = AST.mapOrSame(ast.types, recur)
const { annotations, filters } = get(ast)
if (types !== ast.types || annotations !== undefined || filters !== undefined) {
return new AST.Union(types, "anyOf", annotations, filters)
}
return ast
}
case "Arrays": {
if (ast.rest.length > 1) {
throw new Error(
`${errorPrefix}: Post-rest elements are not supported for arrays (rest length: ${ast.rest.length})`
)
}
let { annotations, filters } = get(ast)
if (ast.elements.length > 0) {
// tuples are not supported by OpenAI, we translate them to objects with string keys
if (annotations !== undefined && typeof annotations.description === "string") {
annotations.description = `${TUPLE_DESCRIPTION}; ${annotations.description}`
} else {
annotations ??= {}
annotations.description = TUPLE_DESCRIPTION
}
const propertySignatures = ast.elements.map((e, i) => {
return new AST.PropertySignature(String(i), e)
})
if (ast.rest.length === 1) {
propertySignatures.push(new AST.PropertySignature(REST_PROPERTY_NAME, new AST.Arrays(false, [], ast.rest)))
}
return AST.decodeTo(
recur(new AST.Objects(propertySignatures, [], annotations, filters)),
ast,
Transformation.transform({
decode: (o) => {
let t: Array<unknown> = []
for (let i = 0; i < ast.elements.length; i++) {
const k = String(i)
if (o[k] !== undefined) {
t.push(o[k])
}
}
if (REST_PROPERTY_NAME in o) {
t = [...t, ...o[REST_PROPERTY_NAME]]
}
return t
},
encode: (t) => {
const o: Record<string, unknown> = {}
for (let i = 0; i < ast.elements.length; i++) {
if (t.length >= i) {
o[String(i)] = t[i]
}
}
if (ast.rest.length === 1) {
o[REST_PROPERTY_NAME] = t.length >= ast.elements.length ? t.slice(ast.elements.length) : []
}
return o
}
})
)
} else {
const rest = AST.mapOrSame(ast.rest, recur)
if (rest !== ast.rest || annotations !== undefined || filters !== undefined) {
return new AST.Arrays(false, [], rest, annotations, filters)
}
return ast
}
}
case "Objects": {
let { annotations, filters } = get(ast)
if (ast.indexSignatures.length === 0) {
const propertySignatures = AST.mapOrSame(ast.propertySignatures, (ps) => {
if (typeof ps.name !== "string") {
throw new Error(
`${errorPrefix}: Property names must be strings (got ${typeof ps.name})`
)
}
let type = recur(ps.type)
// optional properties are not supported by OpenAI, so we translate them to nullable unions
if (AST.isOptional(ps.type)) {
type = AST.decodeTo(
new AST.Union([type, AST.null], "anyOf"),
AST.optionalKey(type),
Transformation.transformOptional({
decode: Option.filter(Predicate.isNotNull),
encode: Option.orElseSome(() => null)
})
)
}
if (type === ps.type) {
return ps
}
return new AST.PropertySignature(ps.name, type)
})
if (
propertySignatures !== ast.propertySignatures || annotations !== undefined || filters !== undefined
) {
return new AST.Objects(propertySignatures, [], annotations, filters)
}
} else if (ast.indexSignatures.length === 1 && ast.propertySignatures.length === 0) {
const is = ast.indexSignatures[0]
// records are not supported by OpenAI, so we translate them to arrays of key-value pairs
if (annotations !== undefined && typeof annotations.description === "string") {
annotations.description = `${RECORD_DESCRIPTION}; ${annotations.description}`
} else {
annotations ??= {}
annotations.description = RECORD_DESCRIPTION
}
return AST.decodeTo(
recur(new AST.Arrays(false, [], [new AST.Arrays(false, [is.parameter, is.type], [])], annotations)),
ast,
Transformation.transform({
decode: Object.fromEntries,
encode: Object.entries
})
)
} else {
throw new Error(
`${errorPrefix}: unsupported object schema shape (properties: ${ast.propertySignatures.length}, indexSignatures: ${ast.indexSignatures.length}). Supported: plain objects (properties only) or records (single index signature, no properties)`
)
}
return ast
}
case "Suspend": {
const cached = cache.get(ast)
if (cached) return cached
const { annotations, filters } = get(ast)
const out = new AST.Suspend(() => recur(ast.thunk()), annotations, filters)
cache.set(ast, out)
return out
}
}
}
const cache = new Map<AST.AST, AST.AST>()
const errorPrefix = "OpenAiStructuredOutput"
function unsupportedAst(ast: AST.AST, details?: string): never {
const base = `Unsupported AST ${ast._tag}`
const full = `${errorPrefix}: ${base}`
throw new Error(details !== undefined ? `${full} (${details})` : full)
}
const REST_PROPERTY_NAME = "__rest__"
const RECORD_DESCRIPTION =
"Object encoded as array of [key, value] pairs. Apply object constraints to the decoded object"
const TUPLE_DESCRIPTION =
"Tuple encoded as an object with numeric string keys ('0', '1', ...). If present, '__rest__' contains remaining elements"
type Annotation =
| { readonly _tag: "description"; readonly description: string }
| { readonly _tag: "format"; readonly format: string }
type Filter =
| Annotation
| { readonly _tag: "filter"; readonly filter: AST.Filter<any> }
| { readonly _tag: "regex"; readonly source: string }
const get = (ast: AST.AST): {
annotations: Record<string, string> | undefined
filters: [AST.Check<any>, ...AST.Check<any>[]] | undefined
} => {
const annotations: Record<string, string> = {}
const filters: Array<AST.Filter<any>> = []
const regexSources: Array<string> = []
const checks = getChecks(ast, AST.isArrays(ast))
if (checks.length > 0) {
for (const check of checks) {
switch (check._tag) {
case "description": {
if (annotations.description !== undefined) {
annotations.description += ` and ${check.description}`
} else {
annotations.description = check.description
}
break
}
case "format": {
annotations.format = check.format
break
}
case "filter": {
filters.push(check.filter)
break
}
case "regex": {
regexSources.push(check.source)
break
}
}
}
}
// OpenAI does not support allOf, so we merge multiple regex patterns into a single isPattern filter
if (regexSources.length === 1) {
filters.push(AST.isPattern(new RegExp(regexSources[0])))
} else if (regexSources.length > 1) {
const combined = regexSources.map((s) => `(?=[\\s\\S]*?(?:${s}))`).join("")
filters.push(AST.isPattern(new RegExp(`^${combined}`)))
}
return {
annotations: Object.keys(annotations).length > 0 ? annotations : undefined,
filters: Arr.isArrayNonEmpty(filters) ? filters : undefined
}
}
const getChecks = (ast: AST.AST, isArray: boolean): Array<Filter> => [
...(ast.checks !== undefined ? getFilters(ast.checks, isArray) : []),
...getAnnotations(ast.annotations)
]
const getAnnotations = (annotations: Schema.Annotations.Filter | undefined): Array<Annotation> => {
const out: Array<Annotation> = []
if (annotations !== undefined) {
const description = annotations?.description
?? (annotations.meta?._tag === "isInt" || annotations.meta?._tag === "isFinite"
? undefined
: annotations?.expected)
if (typeof description === "string") {
out.push({ _tag: "description", description })
}
const format = annotations?.format
if (typeof format === "string") {
if (formats.includes(format)) {
out.push({ _tag: "format", format })
} else {
out.push({ _tag: "description", description: `a value with a format of ${format}` })
}
}
}
return out
}
function getFilter(filter: AST.Filter<any>, isArray: boolean): Array<Filter> {
let out: Array<Filter> = []
const annotations = getAnnotations(filter.annotations)
const meta = filter.annotations?.meta
if (meta !== undefined) {
switch (meta._tag) {
case "isMinLength":
case "isMaxLength":
case "isLength": {
out = out.concat(annotations)
if (isArray) {
out.push({ _tag: "filter", filter: resetFilter(filter) })
}
break
}
case "isInt":
case "isFinite":
case "isGreaterThan":
case "isGreaterThanOrEqualTo":
case "isLessThan":
case "isLessThanOrEqualTo":
case "isBetween":
case "isMultipleOf": {
out = out.concat(annotations)
out.push({ _tag: "filter", filter: resetFilter(filter) })
break
}
default: {
out = out.concat(annotations)
break
}
}
if ("regExp" in meta && meta.regExp instanceof RegExp) {
out.push({ _tag: "regex", source: meta.regExp.source })
}
}
return out
}
function resetFilter(filter: AST.Filter<any>): AST.Filter<any> {
return filter.annotate({
description: undefined,
expected: undefined,
title: undefined,
format: undefined
})
}
function getFilters(checks: readonly [AST.Check<any>, ...AST.Check<any>[]], isArray: boolean): Array<Filter> {
return checks.flatMap((check) => {
switch (check._tag) {
case "Filter":
return getFilter(check, isArray)
case "FilterGroup":
return getFilters(check.checks, isArray)
}
})
}
const formats = [
"date-time",
"time",
"date",
"duration",
"email",
"hostname",
"uri",
"ipv4",
"ipv6",
"uuid"
]
@@ -0,0 +1,141 @@
/**
* OpenAI telemetry attributes for OpenTelemetry integration.
*
* Provides OpenAI-specific GenAI telemetry attributes following OpenTelemetry
* semantic conventions, extending the base GenAI attributes with OpenAI-specific
* request and response metadata.
*
* @since 1.0.0
*/
import { dual } from "effect/Function"
import * as String from "effect/String"
import type { Span } from "effect/Tracer"
import type { Simplify } from "effect/Types"
import * as Telemetry from "effect/unstable/ai/Telemetry"
/**
* The attributes used to describe telemetry in the context of Generative
* Artificial Intelligence (GenAI) Models requests and responses.
*
* {@see https://opentelemetry.io/docs/specs/semconv/attributes-registry/gen-ai/}
*
* @since 1.0.0
* @category models
*/
export type OpenAiTelemetryAttributes = Simplify<
& Telemetry.GenAITelemetryAttributes
& Telemetry.AttributesWithPrefix<RequestAttributes, "gen_ai.openai.request">
& Telemetry.AttributesWithPrefix<ResponseAttributes, "gen_ai.openai.request">
>
/**
* All telemetry attributes which are part of the GenAI specification,
* including the OpenAi-specific attributes.
*
* @since 1.0.0
* @category models
*/
export type AllAttributes = Telemetry.AllAttributes & RequestAttributes & ResponseAttributes
/**
* Telemetry attributes which are part of the GenAI specification and are
* namespaced by `gen_ai.openai.request`.
*
* @since 1.0.0
* @category models
*/
export interface RequestAttributes {
/**
* The response format that is requested.
*/
readonly responseFormat?: (string & {}) | WellKnownResponseFormat | null | undefined
/**
* The service tier requested. May be a specific tier, `default`, or `auto`.
*/
readonly serviceTier?: (string & {}) | WellKnownServiceTier | null | undefined
}
/**
* Telemetry attributes which are part of the GenAI specification and are
* namespaced by `gen_ai.openai.response`.
*
* @since 1.0.0
* @category models
*/
export interface ResponseAttributes {
/**
* The service tier used for the response.
*/
readonly serviceTier?: string | null | undefined
/**
* A fingerprint to track any eventual change in the Generative AI
* environment.
*/
readonly systemFingerprint?: string | null | undefined
}
/**
* The `gen_ai.openai.request.response_format` attribute has the following
* list of well-known values.
*
* If one of them applies, then the respective value **MUST** be used;
* otherwise, a custom value **MAY** be used.
*
* @since 1.0.0
* @category models
*/
export type WellKnownResponseFormat = "json_object" | "json_schema" | "text"
/**
* The `gen_ai.openai.request.service_tier` attribute has the following
* list of well-known values.
*
* If one of them applies, then the respective value **MUST** be used;
* otherwise, a custom value **MAY** be used.
*
* @since 1.0.0
* @category models
*/
export type WellKnownServiceTier = "auto" | "default"
/**
* @since 1.0.0
* @since models
*/
export type OpenAiTelemetryAttributeOptions = Telemetry.GenAITelemetryAttributeOptions & {
openai?: {
request?: RequestAttributes | undefined
response?: ResponseAttributes | undefined
} | undefined
}
const addOpenAiRequestAttributes = Telemetry.addSpanAttributes("gen_ai.openai.request", String.camelToSnake)<
RequestAttributes
>
const addOpenAiResponseAttributes = Telemetry.addSpanAttributes("gen_ai.openai.response", String.camelToSnake)<
ResponseAttributes
>
/**
* Applies the specified OpenAi GenAI telemetry attributes to the provided
* `Span`.
*
* **NOTE**: This method will mutate the `Span` **in-place**.
*
* @since 1.0.0
* @since utilities
*/
export const addGenAIAnnotations: {
(options: OpenAiTelemetryAttributeOptions): (span: Span) => void
(span: Span, options: OpenAiTelemetryAttributeOptions): void
} = dual(2, (span: Span, options: OpenAiTelemetryAttributeOptions) => {
Telemetry.addGenAIAnnotations(span, options)
if (options.openai != null) {
if (options.openai.request != null) {
addOpenAiRequestAttributes(span, options.openai.request)
}
if (options.openai.response != null) {
addOpenAiResponseAttributes(span, options.openai.response)
}
}
})
+61
View File
@@ -0,0 +1,61 @@
/**
* @since 1.0.0
*/
// @barrel: Auto-generated exports. Do not edit manually.
/**
* @since 1.0.0
*/
export * as OpenAiClient from "./OpenAiClient.ts"
/**
* @since 1.0.0
*/
export * as OpenAiConfig from "./OpenAiConfig.ts"
/**
* @since 1.0.0
*/
export * as OpenAiError from "./OpenAiError.ts"
/**
* OpenAI Language Model implementation.
*
* Provides a LanguageModel implementation for OpenAI's responses API,
* supporting text generation, structured output, tool calling, and streaming.
*
* @since 1.0.0
*/
export * as OpenAiLanguageModel from "./OpenAiLanguageModel.ts"
/**
* Provides a codec transformation for OpenAI structured output.
*
* OpenAI's API has specific constraints on JSON schema support that differ
* from the full JSON Schema specification. This module transforms Effect
* `Schema.Codec` types into a form compatible with OpenAI's structured
* output requirements by:
*
* - Converting tuples to objects with string keys (tuples are unsupported)
* - Converting optional properties to nullable unions (`T | null`)
* - Converting index signatures (records) to arrays of key-value pairs
* - Converting `oneOf` unions to `anyOf` unions
* - Merging multiple regex patterns into a single `pattern` (since OpenAI
* does not support `allOf`)
* - Preserving only OpenAI-compatible formats and descriptions
*
* @since 1.0.0
*/
export * as OpenAiStructuredOutput from "./OpenAiStructuredOutput.ts"
/**
* OpenAI telemetry attributes for OpenTelemetry integration.
*
* Provides OpenAI-specific GenAI telemetry attributes following OpenTelemetry
* semantic conventions, extending the base GenAI attributes with OpenAI-specific
* request and response metadata.
*
* @since 1.0.0
*/
export * as OpenAiTelemetry from "./OpenAiTelemetry.ts"
@@ -0,0 +1,327 @@
import * as Arr from "effect/Array"
import * as Duration from "effect/Duration"
import * as Effect from "effect/Effect"
import { dual } from "effect/Function"
import * as Number from "effect/Number"
import * as Option from "effect/Option"
import * as Redactable from "effect/Redactable"
import * as Schema from "effect/Schema"
import * as SchemaTransformation from "effect/SchemaTransformation"
import * as String from "effect/String"
import * as AiError from "effect/unstable/ai/AiError"
import type * as Response from "effect/unstable/ai/Response"
import type * as HttpClientError from "effect/unstable/http/HttpClientError"
import type * as HttpClientRequest from "effect/unstable/http/HttpClientRequest"
import type * as HttpClientResponse from "effect/unstable/http/HttpClientResponse"
import type { OpenAiErrorMetadata } from "../OpenAiError.ts"
/** @internal */
export const OpenAiErrorBody = Schema.Struct({
error: Schema.Struct({
message: Schema.String,
type: Schema.optional(Schema.NullOr(Schema.String)),
status: Schema.optional(Schema.NullOr(Schema.String)),
param: Schema.optional(Schema.NullOr(Schema.String)),
code: Schema.optional(Schema.NullOr(Schema.Union([Schema.String, Schema.Number])))
})
})
const OpenAiErrorBodyJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Union([
OpenAiErrorBody,
Schema.NonEmptyArray(OpenAiErrorBody).pipe(
Schema.decodeTo(
Schema.toType(OpenAiErrorBody),
SchemaTransformation.transform({
decode: Arr.headNonEmpty,
encode: (item) => [item]
})
)
)
])))
/** @internal */
export const mapSchemaError = dual<
(method: string) => (error: Schema.SchemaError) => AiError.AiError,
(error: Schema.SchemaError, method: string) => AiError.AiError
>(2, (error, method) =>
AiError.make({
module: "OpenAiClient",
method,
reason: AiError.InvalidOutputError.fromSchemaError(error)
}))
/** @internal */
export const mapHttpClientError = dual<
(method: string) => (error: HttpClientError.HttpClientError) => Effect.Effect<never, AiError.AiError>,
(error: HttpClientError.HttpClientError, method: string) => Effect.Effect<never, AiError.AiError>
>(2, (error, method) => {
const reason = error.reason
switch (reason._tag) {
case "TransportError": {
return Effect.fail(AiError.make({
module: "OpenAiClient",
method,
reason: new AiError.NetworkError({
reason: "TransportError",
description: reason.description,
request: buildHttpRequestDetails(reason.request)
})
}))
}
case "EncodeError": {
return Effect.fail(AiError.make({
module: "OpenAiClient",
method,
reason: new AiError.NetworkError({
reason: "EncodeError",
description: reason.description,
request: buildHttpRequestDetails(reason.request)
})
}))
}
case "InvalidUrlError": {
return Effect.fail(AiError.make({
module: "OpenAiClient",
method,
reason: new AiError.NetworkError({
reason: "InvalidUrlError",
description: reason.description,
request: buildHttpRequestDetails(reason.request)
})
}))
}
case "StatusCodeError": {
return mapStatusCodeError(reason, method)
}
case "DecodeError": {
return Effect.fail(AiError.make({
module: "OpenAiClient",
method,
reason: new AiError.InvalidOutputError({
description: reason.description ?? "Failed to decode response"
})
}))
}
case "EmptyBodyError": {
return Effect.fail(AiError.make({
module: "OpenAiClient",
method,
reason: new AiError.InvalidOutputError({
description: reason.description ?? "Response body was empty"
})
}))
}
}
})
/** @internal */
const mapStatusCodeError = Effect.fnUntraced(function*(
error: HttpClientError.StatusCodeError,
method: string
) {
const { request, response, description } = error
const status = response.status
const headers = response.headers as Record<string, string>
const requestId = headers["x-request-id"]
let body = yield* response.text.pipe(
Effect.catchCause(() => Effect.succeed(description?.startsWith("{") ? description : undefined))
)
const decoded = OpenAiErrorBodyJson(body)
const reason = mapStatusCodeToReason({
status,
headers,
message: Option.isSome(decoded) ? decoded.value.error.message : undefined,
http: buildHttpContext({ request, response, body }),
metadata: {
errorCode: Option.isSome(decoded) ? decoded.value.error.code?.toString() ?? null : null,
errorType: decoded.pipe(
Option.flatMapNullishOr((d) => d.error.type ?? d.error.status),
Option.map(String.toLowerCase),
Option.getOrNull
),
requestId: requestId ?? null
}
})
return yield* AiError.make({ module: "OpenAiClient", method, reason })
})
/** @internal */
export const parseRateLimitHeaders = (headers: Record<string, string>) => {
const retryAfterRaw = headers["retry-after"]
let retryAfter: Duration.Duration | undefined
if (retryAfterRaw !== undefined) {
const parsed = Number.parse(retryAfterRaw)
if (parsed !== undefined) {
retryAfter = Duration.seconds(parsed)
}
}
const remainingRaw = headers["x-ratelimit-remaining-requests"]
const remaining = remainingRaw !== undefined ? Number.parse(remainingRaw) ?? null : null
return {
retryAfter,
limit: headers["x-ratelimit-limit-requests"] ?? null,
remaining,
resetRequests: headers["x-ratelimit-reset-requests"] ?? null,
resetTokens: headers["x-ratelimit-reset-tokens"] ?? null
}
}
/** @internal */
export const buildHttpRequestDetails = (
request: HttpClientRequest.HttpClientRequest
): typeof Response.HttpRequestDetails.Type => ({
method: request.method,
url: request.url,
urlParams: Array.from(request.urlParams),
hash: request.hash,
headers: Redactable.redact(request.headers) as Record<string, string>
})
/** @internal */
export const buildHttpContext = (params: {
readonly request: HttpClientRequest.HttpClientRequest
readonly response?: HttpClientResponse.HttpClientResponse
readonly body?: string | undefined
}): typeof AiError.HttpContext.Type => ({
request: buildHttpRequestDetails(params.request),
response: params.response !== undefined
? {
status: params.response.status,
headers: Redactable.redact(params.response.headers) as Record<string, string>
}
: undefined,
body: params.body
})
const buildInvalidRequestDescription = (params: {
readonly status: number
readonly message: string | undefined
readonly method: string
readonly url: string
readonly errorCode: string | null
readonly errorType: string | null
readonly requestId: string | null
readonly body: string | undefined
}): string => {
const parts: Array<string> = []
if (params.message) {
parts.push(params.message)
} else {
parts.push(`HTTP ${params.status}`)
}
parts.push(`(${params.method} ${params.url})`)
if (params.errorCode) {
parts.push(`[code: ${params.errorCode}]`)
} else if (params.errorType) {
parts.push(`[type: ${params.errorType}]`)
}
if (params.requestId) {
parts.push(`[requestId: ${params.requestId}]`)
}
if (!params.message && params.body) {
const truncated = params.body.length > 200
? params.body.slice(0, 200) + "..."
: params.body
parts.push(`Response: ${truncated}`)
}
return parts.join(" ")
}
/** @internal */
export const mapStatusCodeToReason = ({ status, headers, message, metadata, http }: {
readonly status: number
readonly headers: Record<string, string>
readonly message: string | undefined
readonly metadata: OpenAiErrorMetadata
readonly http: typeof AiError.HttpContext.Type
}): AiError.AiErrorReason => {
const invalidRequestDescription = buildInvalidRequestDescription({
status,
message,
method: http.request.method,
url: http.request.url,
errorCode: metadata.errorCode,
errorType: metadata.errorType,
requestId: metadata.requestId,
body: http.body
})
switch (status) {
case 400:
return new AiError.InvalidRequestError({
description: invalidRequestDescription,
metadata: { openai: metadata },
http
})
case 401:
return new AiError.AuthenticationError({
kind: "InvalidKey",
metadata,
http
})
case 403:
return new AiError.AuthenticationError({
kind: "InsufficientPermissions",
metadata,
http
})
case 404:
return new AiError.InvalidRequestError({
description: invalidRequestDescription,
metadata: { openai: metadata },
http
})
case 409:
case 422:
return new AiError.InvalidRequestError({
description: invalidRequestDescription,
metadata: { openai: metadata },
http
})
case 429: {
if (
metadata.errorCode === "insufficient_quota" ||
metadata.errorType === "insufficient_quota" ||
metadata.errorType?.includes("quota") ||
metadata.errorType?.includes("exhausted")
) {
return new AiError.QuotaExhaustedError({
metadata: { openai: metadata },
http
})
}
const { retryAfter, ...rateLimitMetadata } = parseRateLimitHeaders(headers)
return new AiError.RateLimitError({
retryAfter,
metadata: {
openai: {
...metadata,
...rateLimitMetadata
}
},
http
})
}
default:
if (status >= 500) {
return new AiError.InternalProviderError({
description: message ?? "Server error",
metadata,
http
})
}
return new AiError.UnknownError({
description: message,
metadata,
http
})
}
}
@@ -0,0 +1,33 @@
import type * as Response from "effect/unstable/ai/Response"
/** @internal */
export const ProviderOptionsKey = "@effect/ai-openai-compat/OpenAiLanguageModel/ProviderOptions"
/** @internal */
export const ProviderMetadataKey = "@effect/ai-openai-compat/OpenAiLanguageModel/ProviderMetadata"
const finishReasonMap: Record<string, Response.FinishReason> = {
content_filter: "content-filter",
function_call: "tool-calls",
length: "length",
stop: "stop",
tool_calls: "tool-calls"
}
/** @internal */
export const escapeJSONDelta = (delta: string): string => JSON.stringify(delta).slice(1, -1)
/** @internal */
export const resolveFinishReason = (
finishReason: string | null | undefined,
hasToolCalls: boolean
): Response.FinishReason => {
if (finishReason == null) {
return hasToolCalls ? "tool-calls" : "stop"
}
const reason = finishReasonMap[finishReason]
if (reason == null) {
return hasToolCalls ? "tool-calls" : "unknown"
}
return reason
}
@@ -0,0 +1,439 @@
import * as OpenAiClient from "@effect/ai-openai-compat/OpenAiClient"
import { assert, describe, it } from "@effect/vitest"
import { Effect, Layer, Redacted, Stream } from "effect"
import { HttpClient, type HttpClientError, type HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
describe("OpenAiClient", () => {
describe("request behavior", () => {
it.effect("sets auth and OpenAI headers on /chat/completions requests", () =>
Effect.gen(function*() {
let capturedRequest: HttpClientRequest.HttpClientRequest | undefined
const client = yield* OpenAiClient.make({
apiKey: Redacted.make("sk-test-key"),
apiUrl: "https://compat.example.test/v1",
organizationId: Redacted.make("org_123"),
projectId: Redacted.make("proj_456")
}).pipe(
Effect.provide(Layer.succeed(
HttpClient.HttpClient,
makeHttpClient((request) => {
capturedRequest = request
return Effect.succeed(jsonResponse(request, 200, makeChatCompletion()))
})
))
)
yield* client.createResponse({
model: "gpt-4o-mini",
messages: [{ role: "user", content: "hello" }]
})
assert.isDefined(capturedRequest)
if (capturedRequest === undefined) {
return
}
assert.isTrue(capturedRequest.url.endsWith("/chat/completions"))
assert.isTrue(capturedRequest.url.startsWith("https://compat.example.test/v1"))
assert.strictEqual(capturedRequest.headers["authorization"], "Bearer sk-test-key")
assert.strictEqual(capturedRequest.headers["openai-organization"], "org_123")
assert.strictEqual(capturedRequest.headers["openai-project"], "proj_456")
const body = yield* getRequestBody(capturedRequest)
assert.strictEqual(body.messages[0]?.role, "user")
assert.strictEqual(body.messages[0]?.content, "hello")
}))
it.effect("uses /embeddings path and decodes permissive embedding payloads", () =>
Effect.gen(function*() {
let capturedRequest: HttpClientRequest.HttpClientRequest | undefined
const client = yield* OpenAiClient.make({
apiKey: Redacted.make("sk-test-key"),
apiUrl: "https://compat.example.test/v1"
}).pipe(
Effect.provide(Layer.succeed(
HttpClient.HttpClient,
makeHttpClient((request) => {
capturedRequest = request
return Effect.succeed(jsonResponse(request, 200, {
data: [{
embedding: "YmFzZTY0LWRhdGE=",
index: 0,
object: "embedding",
vendor_payload: { future_field: true }
}],
model: "my-custom-embedding-model",
object: "list",
usage: {
prompt_tokens: 5,
total_tokens: 5
},
unknown_top_level: true
}))
})
))
)
const embedding = yield* client.createEmbedding({
model: "my-custom-embedding-model",
input: "embed this"
})
assert.isDefined(capturedRequest)
if (capturedRequest === undefined) {
return
}
assert.isTrue(capturedRequest.url.endsWith("/embeddings"))
assert.strictEqual(embedding.model, "my-custom-embedding-model")
assert.strictEqual(embedding.data[0]?.index, 0)
assert.strictEqual(typeof embedding.data[0]?.embedding, "string")
}))
it.effect("sets stream=true for createResponseStream and returns chat chunks", () =>
Effect.gen(function*() {
let capturedRequest: HttpClientRequest.HttpClientRequest | undefined
const client = yield* OpenAiClient.make({
apiKey: Redacted.make("sk-test-key")
}).pipe(
Effect.provide(Layer.succeed(
HttpClient.HttpClient,
makeHttpClient((request) => {
capturedRequest = request
return Effect.succeed(sseResponse(request, [
{
id: "chatcmpl_test_1",
object: "chat.completion.chunk",
model: "gpt-4o-mini",
created: 1,
future_provider_field: { accepted: true },
choices: [{
index: 0,
delta: { content: "Hello" },
finish_reason: null
}]
},
{
id: "chatcmpl_test_1",
object: "chat.completion.chunk",
model: "gpt-4o-mini",
created: 1,
usage: {
prompt_tokens: 4,
completion_tokens: 2,
total_tokens: 6,
prompt_tokens_details: { cached_tokens: 1 },
completion_tokens_details: { reasoning_tokens: 1 }
},
choices: [{
index: 0,
delta: {},
finish_reason: "stop"
}]
},
"[DONE]"
]))
})
))
)
const eventsChunk = yield* client.createResponseStream({
model: "gpt-4o-mini",
messages: [{ role: "user", content: "hello" }]
}).pipe(
Effect.flatMap(([_, stream]) => Stream.runCollect(stream))
)
assert.isDefined(capturedRequest)
if (capturedRequest === undefined) {
return
}
const body = yield* getRequestBody(capturedRequest)
assert.strictEqual(body.stream, true)
assert.strictEqual(body.stream_options.include_usage, true)
assert.isTrue(capturedRequest.url.endsWith("/chat/completions"))
const events = globalThis.Array.from(eventsChunk)
const firstEvent = events[0]
const secondEvent = events[1]
assert.isTrue(typeof firstEvent === "object")
assert.isTrue(typeof secondEvent === "object")
if (
typeof firstEvent !== "object" || firstEvent === null || typeof secondEvent !== "object" ||
secondEvent === null
) {
return
}
assert.strictEqual(firstEvent.id, "chatcmpl_test_1")
assert.strictEqual(secondEvent.id, "chatcmpl_test_1")
assert.strictEqual(events[2], "[DONE]")
}))
it.effect("passes chat-completions tool_choice payload through unchanged", () =>
Effect.gen(function*() {
let capturedRequest: HttpClientRequest.HttpClientRequest | undefined
const client = yield* OpenAiClient.make({
apiKey: Redacted.make("sk-test-key")
}).pipe(
Effect.provide(Layer.succeed(
HttpClient.HttpClient,
makeHttpClient((request) => {
capturedRequest = request
return Effect.succeed(jsonResponse(request, 200, makeChatCompletion()))
})
))
)
yield* client.createResponse({
model: "gpt-4o-mini",
messages: [{ role: "user", content: "hello" }],
tool_choice: {
type: "function",
function: {
name: "TestTool"
}
},
tools: [{
type: "function",
function: {
name: "TestTool",
parameters: {
type: "object",
additionalProperties: false,
properties: {
input: { type: "string" }
},
required: ["input"]
}
}
}]
})
assert.isDefined(capturedRequest)
if (capturedRequest === undefined) {
return
}
const body = yield* getRequestBody(capturedRequest)
assert.deepStrictEqual(body.tool_choice, { type: "function", function: { name: "TestTool" } })
}))
it.effect("accepts assistant tool-call and tool result chat history", () =>
Effect.gen(function*() {
let capturedRequest: HttpClientRequest.HttpClientRequest | undefined
const client = yield* OpenAiClient.make({
apiKey: Redacted.make("sk-test-key")
}).pipe(
Effect.provide(Layer.succeed(
HttpClient.HttpClient,
makeHttpClient((request) => {
capturedRequest = request
return Effect.succeed(jsonResponse(request, 200, makeChatCompletion()))
})
))
)
yield* client.createResponse({
model: "gpt-4o-mini",
messages: [
{
role: "assistant",
content: null,
tool_calls: [{
id: "patch_call_1",
type: "function",
function: {
name: "apply_patch",
arguments: JSON.stringify({
call_id: "patch_call_1",
operation: {
type: "delete_file",
path: "src/obsolete.ts"
}
})
}
}]
},
{
role: "tool",
tool_call_id: "patch_call_1",
content: "deleted"
}
]
})
assert.isDefined(capturedRequest)
if (capturedRequest === undefined) {
return
}
const body = yield* getRequestBody(capturedRequest)
const assistantMessages = body.messages.filter((message: any) => message.role === "assistant")
const patchMessage = assistantMessages.find((message: any) =>
message.tool_calls?.[0]?.function?.name === "apply_patch"
)
assert.isDefined(patchMessage)
assert.strictEqual(patchMessage.tool_calls[0].id, "patch_call_1")
assert.deepStrictEqual(JSON.parse(patchMessage.tool_calls[0].function.arguments), {
call_id: "patch_call_1",
operation: {
type: "delete_file",
path: "src/obsolete.ts"
}
})
const toolMessages = body.messages.filter((message: any) => message.role === "tool")
const patchOutput = toolMessages.find((message: any) => message.tool_call_id === "patch_call_1")
assert.isDefined(patchOutput)
assert.strictEqual(patchOutput.content, "deleted")
}))
})
describe("error mapping", () => {
it.effect("maps 400 responses to InvalidRequestError", () =>
Effect.gen(function*() {
const client = yield* OpenAiClient.make({
apiKey: Redacted.make("sk-test-key")
}).pipe(
Effect.provide(Layer.succeed(
HttpClient.HttpClient,
makeHttpClient((request) =>
Effect.succeed(jsonResponse(request, 400, {
error: {
message: "Bad request",
type: "invalid_request_error",
code: null
}
}))
)
))
)
const error = yield* client.createResponse({
model: "gpt-4o-mini",
messages: [{ role: "user", content: "hello" }]
}).pipe(Effect.flip)
assert.strictEqual(error._tag, "AiError")
assert.strictEqual(error.method, "createResponse")
assert.strictEqual(error.reason._tag, "InvalidRequestError")
}))
it.effect("maps insufficient quota errors to QuotaExhaustedError", () =>
Effect.gen(function*() {
const client = yield* OpenAiClient.make({
apiKey: Redacted.make("sk-test-key")
}).pipe(
Effect.provide(Layer.succeed(
HttpClient.HttpClient,
makeHttpClient((request) =>
Effect.succeed(jsonResponse(request, 429, {
error: {
message: "You exceeded your current quota",
type: "insufficient_quota",
code: "insufficient_quota"
}
}))
)
))
)
const error = yield* client.createResponse({
model: "gpt-4o-mini",
messages: [{ role: "user", content: "hello" }]
}).pipe(Effect.flip)
assert.strictEqual(error._tag, "AiError")
assert.strictEqual(error.method, "createResponse")
assert.strictEqual(error.reason._tag, "QuotaExhaustedError")
}))
})
})
const makeHttpClient = (
handler: (
request: HttpClientRequest.HttpClientRequest
) => Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError>
) =>
HttpClient.makeWith(
Effect.fnUntraced(function*(requestEffect) {
const request = yield* requestEffect
return yield* handler(request)
}),
Effect.succeed as HttpClient.HttpClient.Preprocess<HttpClientError.HttpClientError, never>
)
const makeChatCompletion = () => ({
id: "chatcmpl_test_1",
object: "chat.completion",
model: "gpt-4o-mini",
created: 1,
choices: [{
index: 0,
finish_reason: "stop",
message: {
role: "assistant",
content: "Hello"
}
}],
usage: {
prompt_tokens: 1,
completion_tokens: 1,
total_tokens: 2
}
})
const jsonResponse = (
request: HttpClientRequest.HttpClientRequest,
status: number,
body: unknown
): HttpClientResponse.HttpClientResponse =>
HttpClientResponse.fromWeb(
request,
new Response(JSON.stringify(body), {
status,
headers: {
"content-type": "application/json"
}
})
)
const sseResponse = (
request: HttpClientRequest.HttpClientRequest,
events: ReadonlyArray<unknown>
): HttpClientResponse.HttpClientResponse =>
HttpClientResponse.fromWeb(
request,
new Response(toSseBody(events), {
status: 200,
headers: {
"content-type": "text/event-stream"
}
})
)
const getRequestBody = (request: HttpClientRequest.HttpClientRequest) =>
Effect.gen(function*() {
const body = request.body
if (body._tag === "Uint8Array") {
const text = new TextDecoder().decode(body.body)
return JSON.parse(text)
}
return yield* Effect.die(new Error("Expected Uint8Array body"))
})
const toSseBody = (events: ReadonlyArray<unknown>): string =>
events.map((event) => {
if (typeof event === "string") {
return `data: ${event}\n\n`
}
return `data: ${JSON.stringify(event)}\n\n`
}).join("")
@@ -0,0 +1,580 @@
import { OpenAiClient, OpenAiLanguageModel } from "@effect/ai-openai-compat"
import { assert, describe, it } from "@effect/vitest"
import { Effect, Layer, Redacted, Schema, Stream } from "effect"
import { LanguageModel, Prompt, Tool, Toolkit } from "effect/unstable/ai"
import { HttpClient, type HttpClientError, type HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
describe("OpenAi compat LanguageModel", () => {
describe("generateText", () => {
it.effect("sends model in request and decodes text output", () =>
Effect.gen(function*() {
let capturedRequest: HttpClientRequest.HttpClientRequest | undefined
const layer = OpenAiClient.layer({ apiKey: Redacted.make("sk-test-key") }).pipe(
Layer.provide(Layer.succeed(
HttpClient.HttpClient,
makeHttpClient((request) => {
capturedRequest = request
return Effect.succeed(jsonResponse(
request,
makeChatCompletion({
choices: [{
index: 0,
finish_reason: "stop",
message: {
role: "assistant",
content: "Hello, compat!"
}
}]
})
))
})
))
)
const result = yield* LanguageModel.generateText({ prompt: "hello" }).pipe(
Effect.provide(OpenAiLanguageModel.model("gpt-4o-mini")),
Effect.provide(layer)
)
assert.strictEqual(result.text, "Hello, compat!")
assert.isDefined(capturedRequest)
if (capturedRequest === undefined) {
return
}
const requestBody = yield* getRequestBody(capturedRequest)
assert.strictEqual(requestBody.model, "gpt-4o-mini")
assert.strictEqual(requestBody.messages[0]?.content, "hello")
}))
it.effect("preserves multimodal user content order in chat payload", () =>
Effect.gen(function*() {
let capturedRequest: HttpClientRequest.HttpClientRequest | undefined
const layer = OpenAiClient.layer({ apiKey: Redacted.make("sk-test-key") }).pipe(
Layer.provide(Layer.succeed(
HttpClient.HttpClient,
makeHttpClient((request) => {
capturedRequest = request
return Effect.succeed(jsonResponse(
request,
makeChatCompletion({
choices: [{
index: 0,
finish_reason: "stop",
message: {
role: "assistant",
content: "done"
}
}]
})
))
})
))
)
yield* LanguageModel.generateText({
prompt: Prompt.make([{
role: "user",
content: [
Prompt.textPart({ text: "first text" }),
Prompt.filePart({
mediaType: "image/png",
data: new URL("https://example.com/image.png")
}),
Prompt.textPart({ text: "second text" })
]
}])
}).pipe(
Effect.provide(OpenAiLanguageModel.model("gpt-4o-mini")),
Effect.provide(layer)
)
assert.isDefined(capturedRequest)
if (capturedRequest === undefined) {
return
}
const requestBody = yield* getRequestBody(capturedRequest)
const content = requestBody.messages[0]?.content
assert.isTrue(Array.isArray(content))
assert.deepStrictEqual(content, [
{
type: "text",
text: "first text"
},
{
type: "image_url",
image_url: {
url: "https://example.com/image.png",
detail: "auto"
}
},
{
type: "text",
text: "second text"
}
])
}))
it.effect("maps function_call output to tool-call part and sends function tool schema", () =>
Effect.gen(function*() {
let capturedRequest: HttpClientRequest.HttpClientRequest | undefined
const layer = OpenAiClient.layer({ apiKey: Redacted.make("sk-test-key") }).pipe(
Layer.provide(Layer.succeed(
HttpClient.HttpClient,
makeHttpClient((request) => {
capturedRequest = request
return Effect.succeed(jsonResponse(
request,
makeChatCompletion({
choices: [{
index: 0,
finish_reason: "tool_calls",
message: {
role: "assistant",
content: null,
tool_calls: [{
id: "call_1",
type: "function",
function: {
name: "TestTool",
arguments: JSON.stringify({ input: "hello" })
}
}]
}
}]
})
))
})
))
)
const result = yield* LanguageModel.generateText({
prompt: "use the tool",
toolkit: TestToolkit,
disableToolCallResolution: true
}).pipe(
Effect.provide(OpenAiLanguageModel.model("gpt-4o-mini")),
Effect.provide(TestToolkitLayer),
Effect.provide(layer)
)
const toolCall = result.content.find((part) => part.type === "tool-call")
assert.isDefined(toolCall)
if (toolCall?.type !== "tool-call") {
return
}
assert.strictEqual(toolCall.name, "TestTool")
assert.deepStrictEqual(toolCall.params, { input: "hello" })
assert.isDefined(capturedRequest)
if (capturedRequest === undefined) {
return
}
const requestBody = yield* getRequestBody(capturedRequest)
const functionTool = requestBody.tools.find((tool: any) => tool.type === "function")
assert.isDefined(functionTool)
assert.strictEqual(functionTool.function.name, "TestTool")
assert.strictEqual(functionTool.function.strict, true)
}))
it.effect("maps provider apply_patch function call back to custom provider-defined tool", () =>
Effect.gen(function*() {
let capturedRequest: HttpClientRequest.HttpClientRequest | undefined
const layer = OpenAiClient.layer({ apiKey: Redacted.make("sk-test-key") }).pipe(
Layer.provide(Layer.succeed(
HttpClient.HttpClient,
makeHttpClient((request) => {
capturedRequest = request
return Effect.succeed(jsonResponse(
request,
makeChatCompletion({
choices: [{
index: 0,
finish_reason: "tool_calls",
message: {
role: "assistant",
content: null,
tool_calls: [{
id: "call_1",
type: "function",
function: {
name: "apply_patch",
arguments: JSON.stringify({
call_id: "call_1",
operation: {
type: "delete_file",
path: "src/obsolete.ts"
}
})
}
}]
}
}]
})
))
})
))
)
const toolkit = Toolkit.make(CompatApplyPatchTool({}))
const toolkitLayer = toolkit.toLayer({
CompatApplyPatch: () =>
Effect.succeed({
status: "completed",
output: "deleted"
})
})
const result = yield* LanguageModel.generateText({
prompt: "delete src/obsolete.ts",
toolkit,
toolChoice: { tool: "CompatApplyPatch" },
disableToolCallResolution: true
}).pipe(
Effect.provide(OpenAiLanguageModel.model("gpt-4o-mini")),
Effect.provide(toolkitLayer),
Effect.provide(layer)
)
const toolCall = result.content.find((part) => part.type === "tool-call")
assert.isDefined(toolCall)
if (toolCall?.type !== "tool-call") {
return
}
assert.strictEqual(toolCall.name, "CompatApplyPatch")
assert.deepStrictEqual(toolCall.params, {
call_id: "call_1",
operation: {
type: "delete_file",
path: "src/obsolete.ts"
}
})
assert.isDefined(capturedRequest)
if (capturedRequest === undefined) {
return
}
const requestBody = yield* getRequestBody(capturedRequest)
const functionTool = requestBody.tools.find((tool: any) => tool.type === "function")
assert.isDefined(functionTool)
assert.strictEqual(functionTool.function.name, "apply_patch")
assert.deepStrictEqual(requestBody.tool_choice, {
type: "function",
function: {
name: "apply_patch"
}
})
}))
it.effect("decodes usage when token detail fields are absent", () =>
Effect.gen(function*() {
const layer = OpenAiClient.layer({ apiKey: Redacted.make("sk-test-key") }).pipe(
Layer.provide(Layer.succeed(
HttpClient.HttpClient,
makeHttpClient((request) =>
Effect.succeed(jsonResponse(
request,
makeChatCompletion({
choices: [{
index: 0,
finish_reason: "stop",
message: {
role: "assistant",
content: "Hello"
}
}],
usage: {
prompt_tokens: 4,
completion_tokens: 5,
total_tokens: 9,
provider_future_field: true
}
})
))
)
))
)
const result = yield* LanguageModel.generateText({ prompt: "hello" }).pipe(
Effect.provide(OpenAiLanguageModel.model("gpt-4o-mini")),
Effect.provide(layer)
)
const finish = result.content.find((part) => part.type === "finish")
assert.isDefined(finish)
if (finish?.type !== "finish") {
return
}
assert.deepStrictEqual(finish.usage.inputTokens, {
uncached: 4,
total: 4,
cacheRead: 0,
cacheWrite: undefined
})
assert.deepStrictEqual(finish.usage.outputTokens, {
total: 5,
text: 5,
reasoning: 0
})
}))
})
describe("generateObject", () => {
it.effect("uses json_schema format for structured output", () =>
Effect.gen(function*() {
let capturedRequest: HttpClientRequest.HttpClientRequest | undefined
const layer = OpenAiClient.layer({ apiKey: Redacted.make("sk-test-key") }).pipe(
Layer.provide(Layer.succeed(
HttpClient.HttpClient,
makeHttpClient((request) => {
capturedRequest = request
return Effect.succeed(jsonResponse(
request,
makeChatCompletion({
choices: [{
index: 0,
finish_reason: "stop",
message: {
role: "assistant",
content: JSON.stringify({ name: "Ada", age: 37 })
}
}]
})
))
})
))
)
const person = yield* LanguageModel.generateObject({
prompt: "Return a person",
schema: Schema.Struct({
name: Schema.String,
age: Schema.Number
})
}).pipe(
Effect.provide(OpenAiLanguageModel.model("gpt-4o-mini")),
Effect.provide(layer)
)
assert.strictEqual(person.value.name, "Ada")
assert.strictEqual(person.value.age, 37)
assert.isDefined(capturedRequest)
if (capturedRequest === undefined) {
return
}
const requestBody = yield* getRequestBody(capturedRequest)
assert.strictEqual(requestBody.response_format.type, "json_schema")
assert.strictEqual(requestBody.response_format.json_schema.strict, true)
}))
})
describe("streamText", () => {
it.effect("streams known events and ignores unknown ones", () =>
Effect.gen(function*() {
let capturedRequest: HttpClientRequest.HttpClientRequest | undefined
const events = [
{
id: "chatcmpl_stream_1",
object: "chat.completion.chunk",
model: "gpt-4o-mini",
created: 1,
choices: [{
index: 0,
delta: { content: "Hello" },
finish_reason: null
}]
},
{
id: "chatcmpl_stream_1",
object: "chat.completion.chunk",
model: "gpt-4o-mini",
created: 1,
choices: [{
index: 0,
delta: {},
finish_reason: "stop"
}],
usage: {
prompt_tokens: 10,
completion_tokens: 7,
total_tokens: 17,
prompt_tokens_details: {
cached_tokens: 3
},
completion_tokens_details: {
reasoning_tokens: 2
}
},
provider_future_field: { accepted: true }
},
"[DONE]"
]
const layer = OpenAiClient.layer({ apiKey: Redacted.make("sk-test-key") }).pipe(
Layer.provide(Layer.succeed(
HttpClient.HttpClient,
makeHttpClient((request) => {
capturedRequest = request
return Effect.succeed(sseResponse(request, events))
})
))
)
const partsChunk = yield* LanguageModel.streamText({ prompt: "hello" }).pipe(
Stream.runCollect,
Effect.provide(OpenAiLanguageModel.model("gpt-4o-mini")),
Effect.provide(layer)
)
const parts = globalThis.Array.from(partsChunk)
const metadata = parts.find((part) => part.type === "response-metadata")
const finish = parts.find((part) => part.type === "finish")
const deltas = parts.filter((part) => part.type === "text-delta")
assert.isDefined(metadata)
assert.isDefined(finish)
assert.strictEqual(deltas.length, 1)
assert.strictEqual(deltas[0]?.delta, "Hello")
if (finish?.type === "finish") {
assert.strictEqual(finish.reason, "stop")
assert.deepStrictEqual(finish.usage.inputTokens, {
uncached: 7,
total: 10,
cacheRead: 3,
cacheWrite: undefined
})
assert.deepStrictEqual(finish.usage.outputTokens, {
total: 7,
text: 5,
reasoning: 2
})
}
assert.isDefined(capturedRequest)
if (capturedRequest === undefined) {
return
}
const requestBody = yield* getRequestBody(capturedRequest)
assert.strictEqual(requestBody.stream, true)
assert.isTrue(capturedRequest.url.endsWith("/chat/completions"))
}))
})
})
const TestTool = Tool.make("TestTool", {
description: "A test tool",
parameters: Schema.Struct({ input: Schema.String }),
success: Schema.Struct({ output: Schema.String })
})
const TestToolkit = Toolkit.make(TestTool)
const TestToolkitLayer = TestToolkit.toLayer({
TestTool: ({ input }) => Effect.succeed({ output: input })
})
const CompatApplyPatchTool = Tool.providerDefined({
id: "compat.apply_patch",
customName: "CompatApplyPatch",
providerName: "apply_patch",
requiresHandler: true,
parameters: Schema.Struct({
call_id: Schema.String,
operation: Schema.Any
}),
success: Schema.Struct({
status: Schema.Literals(["completed", "failed"]),
output: Schema.optionalKey(Schema.NullOr(Schema.String))
})
})
const makeHttpClient = (
handler: (
request: HttpClientRequest.HttpClientRequest
) => Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError>
) =>
HttpClient.makeWith(
Effect.fnUntraced(function*(requestEffect) {
const request = yield* requestEffect
return yield* handler(request)
}),
Effect.succeed as HttpClient.HttpClient.Preprocess<HttpClientError.HttpClientError, never>
)
const makeChatCompletion = (overrides: Record<string, unknown> = {}) => ({
id: "chatcmpl_test_1",
object: "chat.completion",
model: "gpt-4o-mini",
created: 1,
choices: [{
index: 0,
finish_reason: "stop",
message: {
role: "assistant",
content: ""
}
}],
...overrides
})
const jsonResponse = (
request: HttpClientRequest.HttpClientRequest,
body: unknown
): HttpClientResponse.HttpClientResponse =>
HttpClientResponse.fromWeb(
request,
new Response(JSON.stringify(body), {
status: 200,
headers: {
"content-type": "application/json"
}
})
)
const sseResponse = (
request: HttpClientRequest.HttpClientRequest,
events: ReadonlyArray<unknown>
): HttpClientResponse.HttpClientResponse =>
HttpClientResponse.fromWeb(
request,
new Response(toSseBody(events), {
status: 200,
headers: {
"content-type": "text/event-stream"
}
})
)
const getRequestBody = (request: HttpClientRequest.HttpClientRequest) =>
Effect.gen(function*() {
const body = request.body
if (body._tag === "Uint8Array") {
const text = new TextDecoder().decode(body.body)
return JSON.parse(text)
}
return yield* Effect.die(new Error("Expected Uint8Array body"))
})
const toSseBody = (events: ReadonlyArray<unknown>): string =>
events.map((event) => {
if (typeof event === "string") {
return `data: ${event}\n\n`
}
return `data: ${JSON.stringify(event)}\n\n`
}).join("")
@@ -0,0 +1,27 @@
import {
OpenAiClient,
OpenAiConfig,
OpenAiError,
OpenAiLanguageModel,
OpenAiStructuredOutput,
OpenAiTelemetry
} from "@effect/ai-openai-compat"
import { assert, describe, it } from "@effect/vitest"
describe("OpenAi compat scaffold", () => {
it("exports the expected modules", () => {
const modules = [
OpenAiClient,
OpenAiConfig,
OpenAiError,
OpenAiLanguageModel,
OpenAiStructuredOutput,
OpenAiTelemetry
]
assert.strictEqual(modules.length, 6)
for (const mod of modules) {
assert.isDefined(mod)
}
})
})
@@ -0,0 +1,335 @@
import { OpenAiClient, OpenAiLanguageModel } from "@effect/ai-openai-compat"
import { assert, describe, it } from "@effect/vitest"
import { deepStrictEqual, strictEqual } from "@effect/vitest/utils"
import { Effect, Layer, Redacted, Ref, Schema, Stream } from "effect"
import { LanguageModel, Prompt, Tool, Toolkit } from "effect/unstable/ai"
import { HttpClient, type HttpClientError, type HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
describe("OpenAiLanguageModel", () => {
describe("streamText", () => {
it.effect("handles chat completion stream chunks", () =>
Effect.gen(function*() {
const partsChunk = yield* LanguageModel.streamText({ prompt: "test" }).pipe(
Stream.runCollect,
Effect.provide(OpenAiLanguageModel.model("gpt-4o-mini"))
)
const parts = Array.from(partsChunk)
assert.isTrue(parts.some((part) => part.type === "response-metadata"))
const finish = parts.find((part) => part.type === "finish")
assert.isDefined(finish)
if (finish?.type === "finish") {
assert.strictEqual(finish.reason, "stop")
}
}).pipe(
Effect.provide(makeTestLayer([
{
id: "chatcmpl_test123",
object: "chat.completion.chunk",
model: "gpt-4o-mini",
created: 1,
choices: [{
index: 0,
delta: {},
finish_reason: "stop"
}]
},
"[DONE]"
]))
))
it.effect("maps local shell stream tool calls to local_shell call outputs", () =>
Effect.gen(function*() {
const capturedRequests = yield* Ref.make<ReadonlyArray<HttpClientRequest.HttpClientRequest>>([])
const requestCount = yield* Ref.make(0)
const httpClient = HttpClient.makeWith(
Effect.fnUntraced(function*(requestEffect) {
const request = yield* requestEffect
yield* Ref.update(capturedRequests, (requests) => [...requests, request])
const index = yield* Ref.getAndUpdate(requestCount, (value) => value + 1)
if (index === 0) {
return HttpClientResponse.fromWeb(
request,
new Response(toSseBody([makeLocalShellChunk(), "[DONE]"]), {
status: 200,
headers: { "content-type": "text/event-stream" }
})
)
}
return HttpClientResponse.fromWeb(
request,
new Response(JSON.stringify(makeChatCompletion()), {
status: 200,
headers: { "content-type": "application/json" }
})
)
}),
Effect.succeed as HttpClient.HttpClient.Preprocess<HttpClientError.HttpClientError, never>
)
const layer = OpenAiClient.layer({ apiKey: Redacted.make("sk-test-key") }).pipe(
Layer.provide(Layer.succeed(HttpClient.HttpClient, httpClient))
)
const toolkit = Toolkit.make(CompatLocalShellTool({}))
const toolkitLayer = toolkit.toLayer({
CompatLocalShell: () => Effect.succeed("done")
})
const partsChunk = yield* LanguageModel.streamText({
prompt: "Run pwd",
toolkit,
disableToolCallResolution: true
}).pipe(
Stream.runCollect,
Effect.provide(OpenAiLanguageModel.model("gpt-4o-mini")),
Effect.provide(toolkitLayer),
Effect.provide(layer)
)
const toolCall = globalThis.Array.from(partsChunk).find((part) => part.type === "tool-call")
assert.isDefined(toolCall)
if (toolCall?.type !== "tool-call") {
return
}
strictEqual(toolCall.name, "CompatLocalShell")
deepStrictEqual(toolCall.params, { action: localShellAction })
yield* LanguageModel.generateText({
prompt: Prompt.make([
{ role: "user", content: "Run pwd" },
{
role: "assistant",
content: [Prompt.toolCallPart({
id: toolCall.id,
name: toolCall.name,
params: { action: localShellAction },
providerExecuted: false,
options: {
openai: {
itemId: "ls_call_1"
}
}
})]
},
{
role: "tool",
content: [Prompt.toolResultPart({
id: toolCall.id,
name: toolCall.name,
isFailure: false,
result: "done"
})]
}
]),
toolkit
}).pipe(
Effect.provide(OpenAiLanguageModel.model("gpt-4o-mini")),
Effect.provide(toolkitLayer),
Effect.provide(layer)
)
const requests = yield* Ref.get(capturedRequests)
const followUpRequest = requests[1]
assert.isDefined(followUpRequest)
if (followUpRequest === undefined) {
return
}
const followUpBody = yield* getRequestBody(followUpRequest)
const localShellCall = followUpBody.messages.find((item: any) =>
item.role === "assistant" && item.tool_calls?.[0]?.function?.name === "local_shell"
)
assert.isDefined(localShellCall)
strictEqual(localShellCall.tool_calls[0].id, toolCall.id)
const localShellOutput = followUpBody.messages.find((item: any) => item.role === "tool")
assert.isDefined(localShellOutput)
strictEqual(localShellOutput.tool_call_id, toolCall.id)
strictEqual(localShellOutput.content, "done")
}))
it.effect("maps apply_patch stream tool calls to custom provider-defined tool", () =>
Effect.gen(function*() {
const layer = makeTestLayer([
{
id: "chatcmpl_apply_patch_1",
object: "chat.completion.chunk",
model: "gpt-4o-mini",
created: 1,
choices: [{
index: 0,
delta: {
tool_calls: [{
index: 0,
id: "patch_call_1",
type: "function",
function: {
name: "apply_patch",
arguments: JSON.stringify({
call_id: "patch_call_1",
operation: {
type: "delete_file",
path: "src/legacy.ts"
}
})
}
}]
},
finish_reason: "tool_calls"
}]
},
"[DONE]"
])
const toolkit = Toolkit.make(CompatApplyPatchTool({}))
const toolkitLayer = toolkit.toLayer({
CompatApplyPatch: () =>
Effect.succeed({
status: "completed",
output: "deleted"
})
})
const partsChunk = yield* LanguageModel.streamText({
prompt: "Delete src/legacy.ts",
toolkit,
disableToolCallResolution: true
}).pipe(
Stream.runCollect,
Effect.provide(OpenAiLanguageModel.model("gpt-4o-mini")),
Effect.provide(toolkitLayer),
Effect.provide(layer)
)
const toolCall = globalThis.Array.from(partsChunk).find((part) => part.type === "tool-call")
assert.isDefined(toolCall)
if (toolCall?.type !== "tool-call") {
return
}
strictEqual(toolCall.name, "CompatApplyPatch")
deepStrictEqual(toolCall.params, {
call_id: "patch_call_1",
operation: {
type: "delete_file",
path: "src/legacy.ts"
}
})
}))
})
})
const localShellAction = {
type: "exec",
command: ["pwd"],
env: {}
}
const CompatLocalShellTool = Tool.providerDefined({
id: "compat.local_shell",
customName: "CompatLocalShell",
providerName: "local_shell",
requiresHandler: true,
parameters: Schema.Struct({
action: Schema.Any
}),
success: Schema.String
})
const CompatApplyPatchTool = Tool.providerDefined({
id: "compat.apply_patch",
customName: "CompatApplyPatch",
providerName: "apply_patch",
requiresHandler: true,
parameters: Schema.Struct({
call_id: Schema.String,
operation: Schema.Any
}),
success: Schema.Struct({
status: Schema.Literals(["completed", "failed"]),
output: Schema.optionalKey(Schema.NullOr(Schema.String))
})
})
const makeLocalShellChunk = () => ({
id: "chatcmpl_local_shell_1",
object: "chat.completion.chunk",
model: "gpt-4o-mini",
created: 1,
choices: [{
index: 0,
delta: {
tool_calls: [{
index: 0,
id: "local_shell_call_1",
type: "function",
function: {
name: "local_shell",
arguments: JSON.stringify({ action: localShellAction })
}
}]
},
finish_reason: "tool_calls"
}]
})
const makeChatCompletion = () => ({
id: "chatcmpl_followup",
object: "chat.completion",
model: "gpt-4o-mini",
created: 1,
choices: [{
index: 0,
finish_reason: "stop",
message: {
role: "assistant",
content: ""
}
}]
})
const makeTestLayer = (events: ReadonlyArray<unknown>) =>
OpenAiClient.layer({ apiKey: Redacted.make("sk-test-key") }).pipe(
Layer.provide(Layer.succeed(HttpClient.HttpClient, makeHttpClient(events)))
)
const makeHttpClient = (events: ReadonlyArray<unknown>) =>
HttpClient.makeWith(
Effect.fnUntraced(function*(requestEffect) {
const request = yield* requestEffect
return HttpClientResponse.fromWeb(
request,
new Response(toSseBody(events), {
status: 200,
headers: { "content-type": "text/event-stream" }
})
)
}),
Effect.succeed as HttpClient.HttpClient.Preprocess<HttpClientError.HttpClientError, never>
)
const getRequestBody = (request: HttpClientRequest.HttpClientRequest) =>
Effect.gen(function*() {
const body = request.body
if (body._tag === "Uint8Array") {
const text = new TextDecoder().decode(body.body)
return JSON.parse(text)
}
return yield* Effect.die(new Error("Expected Uint8Array body"))
})
const toSseBody = (events: ReadonlyArray<unknown>): string =>
events.map((event) => {
if (typeof event === "string") {
return `data: ${event}\n\n`
}
return `data: ${JSON.stringify(event)}\n\n`
}).join("")
+8
View File
@@ -0,0 +1,8 @@
{
"$schema": "http://json.schemastore.org/tsconfig",
"extends": "../../../tsconfig.base.json",
"include": ["src"],
"references": [
{ "path": "../../effect" }
]
}
@@ -0,0 +1,6 @@
import { mergeConfig, type ViteUserConfig } from "vitest/config"
import shared from "../../../vitest.shared.ts"
const config: ViteUserConfig = {}
export default mergeConfig(shared, config)
+13 -36
View File
@@ -25562,28 +25562,23 @@ export const make = (
: (request) => Effect.flatMap(httpClient.execute(request), withOptionalResponse)
}
const sseRequest = <
Type extends {
readonly id?: string | undefined
readonly event: string
readonly data: unknown
},
Type,
DecodingServices
>(
schema: Schema.Decoder<Type, DecodingServices>
) =>
(
request: HttpClientRequest.HttpClientRequest
): Stream.Stream<Type, HttpClientError.HttpClientError | SchemaError | Sse.Retry, DecodingServices> =>
): Stream.Stream<
{ readonly event: string; readonly id: string | undefined; readonly data: Type },
HttpClientError.HttpClientError | SchemaError | Sse.Retry,
DecodingServices
> =>
HttpClient.filterStatusOk(httpClient).execute(request).pipe(
Effect.map((response) => response.stream),
Stream.unwrap,
Stream.decodeText(),
Stream.pipeThroughChannel(Sse.decodeSchema<
Type,
DecodingServices,
HttpClientError.HttpClientError,
unknown
>(schema))
Stream.pipeThroughChannel(Sse.decodeDataSchema(schema))
)
const binaryRequest = (
request: HttpClientRequest.HttpClientRequest
@@ -25657,10 +25652,7 @@ export const make = (
"createSpeechSse": (options) =>
HttpClientRequest.post(`/audio/speech`).pipe(
HttpClientRequest.bodyJsonUnsafe(options.payload),
sseRequest(Schema.Struct({
...Sse.EventEncoded.fields,
data: CreateSpeech200Sse
}))
sseRequest(CreateSpeech200Sse)
),
"createSpeechStream": (options) =>
HttpClientRequest.post(`/audio/speech`).pipe(
@@ -25678,10 +25670,7 @@ export const make = (
"createTranscriptionSse": (options) =>
HttpClientRequest.post(`/audio/transcriptions`).pipe(
HttpClientRequest.bodyFormData(options.payload as any),
sseRequest(Schema.Struct({
...Sse.EventEncoded.fields,
data: CreateTranscription200Sse
}))
sseRequest(CreateTranscription200Sse)
),
"createTranslation": (options) =>
HttpClientRequest.post(`/audio/translations`).pipe(
@@ -25798,10 +25787,7 @@ export const make = (
"createChatCompletionSse": (options) =>
HttpClientRequest.post(`/chat/completions`).pipe(
HttpClientRequest.bodyJsonUnsafe(options.payload),
sseRequest(Schema.Struct({
...Sse.EventEncoded.fields,
data: CreateChatCompletion200Sse
}))
sseRequest(CreateChatCompletion200Sse)
),
"getChatCompletion": (completionId, options) =>
HttpClientRequest.get(`/chat/completions/${completionId}`).pipe(
@@ -26240,10 +26226,7 @@ export const make = (
"createImageEditSse": (options) =>
HttpClientRequest.post(`/images/edits`).pipe(
HttpClientRequest.bodyFormData(options.payload as any),
sseRequest(Schema.Struct({
...Sse.EventEncoded.fields,
data: CreateImageEdit200Sse
}))
sseRequest(CreateImageEdit200Sse)
),
"createImage": (options) =>
HttpClientRequest.post(`/images/generations`).pipe(
@@ -26256,10 +26239,7 @@ export const make = (
"createImageSse": (options) =>
HttpClientRequest.post(`/images/generations`).pipe(
HttpClientRequest.bodyJsonUnsafe(options.payload),
sseRequest(Schema.Struct({
...Sse.EventEncoded.fields,
data: CreateImage200Sse
}))
sseRequest(CreateImage200Sse)
),
"createImageVariation": (options) =>
HttpClientRequest.post(`/images/variations`).pipe(
@@ -27182,10 +27162,7 @@ export const make = (
"createResponseSse": (options) =>
HttpClientRequest.post(`/responses`).pipe(
HttpClientRequest.bodyJsonUnsafe(options.payload),
sseRequest(Schema.Struct({
...Sse.EventEncoded.fields,
data: CreateResponse200Sse
}))
sseRequest(CreateResponse200Sse)
),
"getResponse": (responseId, options) =>
HttpClientRequest.get(`/responses/${responseId}`).pipe(
+1 -7
View File
@@ -13,7 +13,6 @@ import { identity } from "effect/Function"
import * as Layer from "effect/Layer"
import * as Predicate from "effect/Predicate"
import * as Redacted from "effect/Redacted"
import * as Schema from "effect/Schema"
import * as ServiceMap from "effect/ServiceMap"
import * as Stream from "effect/Stream"
import type * as AiError from "effect/unstable/ai/AiError"
@@ -196,11 +195,6 @@ export const make = Effect.fnUntraced(
})
)
const SseEvent = Schema.Struct({
...Sse.EventEncoded.fields,
data: Generated.ResponseStreamEvent
})
const buildResponseStream = (
response: HttpClientResponse.HttpClientResponse
): [
@@ -209,7 +203,7 @@ export const make = Effect.fnUntraced(
] => {
const stream = response.stream.pipe(
Stream.decodeText(),
Stream.pipeThroughChannel(Sse.decodeSchema(SseEvent)),
Stream.pipeThroughChannel(Sse.decodeDataSchema(Generated.ResponseStreamEvent)),
Stream.takeUntil((event) =>
event.data.type === "response.completed" ||
event.data.type === "response.incomplete"
@@ -1414,7 +1414,7 @@ const makeStreamResponse = Effect.fnUntraced(
case "response.output_item.added": {
switch (event.item.type) {
case "apply_patch_call": {
const toolId = event.item.id
const toolId = event.item.call_id
const toolName = toolNameMapper.getCustomName("apply_patch")
const operation = event.item.operation
activeToolCalls[event.output_index] = {
@@ -1449,7 +1449,7 @@ const makeStreamResponse = Effect.fnUntraced(
type: "tool-params-delta",
id: toolId,
delta: `{"call_id":"${InternalUtilities.escapeJSONDelta(toolId)}",` +
`"operation"{"type":"${InternalUtilities.escapeJSONDelta(operation.type)}",` +
`"operation":{"type":"${InternalUtilities.escapeJSONDelta(operation.type)}",` +
`"path":"${InternalUtilities.escapeJSONDelta(operation.path)}","diff":"`
})
}
@@ -1752,7 +1752,7 @@ const makeStreamResponse = Effect.fnUntraced(
}
case "local_shell_call": {
const toolName = toolNameMapper.getCustomName("")
const toolName = toolNameMapper.getCustomName("local_shell")
parts.push({
type: "tool-call",
id: event.item.call_id,
@@ -2568,7 +2568,7 @@ const getUsage = (usage: Generated.ResponseUsage | null | undefined): Response.U
const inputTokens = usage.input_tokens
const outputTokens = usage.output_tokens
const cachedTokens = usage.input_tokens_details.cached_tokens
const reasoningTokens = usage.input_tokens_details.cached_tokens
const reasoningTokens = usage.output_tokens_details.reasoning_tokens
return {
inputTokens: {
@@ -1,9 +1,9 @@
import { Generated, OpenAiClient, OpenAiLanguageModel, OpenAiTool } from "@effect/ai-openai"
import { assert, describe, it } from "@effect/vitest"
import { deepStrictEqual, strictEqual } from "@effect/vitest/utils"
import { Array, Effect, Layer, Redacted, Ref, Schema, ServiceMap } from "effect"
import { Array, Effect, Layer, Redacted, Ref, Schema, ServiceMap, Stream } from "effect"
import { LanguageModel, Prompt, Tool, Toolkit } from "effect/unstable/ai"
import { HttpClient, type HttpClientError, type HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
import { HttpClient, type HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
describe("OpenAiLanguageModel", () => {
describe("make", () => {
@@ -760,6 +760,76 @@ describe("OpenAiLanguageModel", () => {
})
})
describe("streamText", () => {
it.effect("emits valid apply_patch tool params JSON for update_file diffs", () =>
Effect.gen(function*() {
const diff = "@@ -1 +1 @@\n-old\n+new\n"
const outputItem = {
type: "apply_patch_call",
id: "patch_item_1",
call_id: "patch_call_1",
status: "in_progress",
operation: {
type: "update_file",
path: "src/example.ts",
diff
}
} as const
const streamEvents = [
{
type: "response.created",
sequence_number: 1,
response: makeDefaultResponse({
id: "resp_patch_stream",
status: "in_progress",
output: []
})
},
{
type: "response.output_item.added",
output_index: 0,
sequence_number: 2,
item: outputItem
},
{
type: "response.apply_patch_call_operation_diff.delta",
sequence_number: 3,
output_index: 0,
item_id: outputItem.id,
delta: diff
},
{
type: "response.apply_patch_call_operation_diff.done",
sequence_number: 4,
output_index: 0,
item_id: outputItem.id
}
] as unknown as ReadonlyArray<typeof Generated.ResponseStreamEvent.Type>
const partsChunk = yield* LanguageModel.streamText({
prompt: "Update src/example.ts",
disableToolCallResolution: true
}).pipe(
Stream.runCollect,
Effect.provide(OpenAiLanguageModel.model("gpt-4o-mini")),
Effect.provide(makeStreamTestLayer(streamEvents))
)
const parts = globalThis.Array.from(partsChunk)
const params = decodeToolParamsFromStream(parts, outputItem.call_id)
deepStrictEqual(params, {
call_id: outputItem.call_id,
operation: {
type: "update_file",
path: "src/example.ts",
diff
}
})
}))
})
describe("withConfigOverride", () => {
it.effect("merges config overrides", () =>
Effect.gen(function*() {
@@ -836,6 +906,26 @@ const makeHttpClient = Effect.gen(function*() {
const HttpClientLayer = Layer.effectServices(makeHttpClient)
const makeStreamTestLayer = (events: ReadonlyArray<typeof Generated.ResponseStreamEvent.Type>) => {
const response = HttpClientResponse.fromWeb(
HttpClientRequest.get("https://api.openai.com/v1/responses"),
new Response("", {
status: 200,
headers: { "content-type": "text/event-stream" }
})
)
return Layer.succeed(
OpenAiClient.OpenAiClient,
OpenAiClient.OpenAiClient.of({
client: undefined as any,
createResponse: () => Effect.die(new Error("unexpected createResponse call")),
createResponseStream: () => Effect.succeed([response, Stream.fromIterable(events)]),
createEmbedding: () => Effect.die(new Error("unexpected createEmbedding call"))
})
)
}
const makeDefaultResponse = (
overrides: Partial<Generated.Response> = {}
): Generated.Response => ({
@@ -881,6 +971,23 @@ const getRequestBody = (request: HttpClientRequest.HttpClientRequest) =>
return yield* Effect.die(new Error("Expected Uint8Array body"))
})
const decodeToolParamsFromStream = (
parts: ReadonlyArray<any>,
toolCallId: string
): Record<string, unknown> => {
const start = parts.find((part) => part.type === "tool-params-start" && part.id === toolCallId)
const end = parts.find((part) => part.type === "tool-params-end" && part.id === toolCallId)
assert.isDefined(start)
assert.isDefined(end)
const deltas = parts
.filter((part) => part.type === "tool-params-delta" && part.id === toolCallId)
.map((part) => part.delta)
.join("")
return JSON.parse(deltas) as Record<string, unknown>
}
const makeTextOutput = (
text: string,
overrides: Partial<Generated.OutputMessage> = {}
+8 -8
View File
@@ -67,7 +67,7 @@ export const decodeSchema = <
Type extends {
readonly id?: string | undefined
readonly event: string
readonly data: unknown
readonly data: string
},
DecodingServices,
IE,
@@ -328,7 +328,7 @@ export const encode = <IE, Done>(): Channel.Channel<
export const encodeSchema = <
S extends Schema.Codec<
any,
{ readonly id?: string | undefined; readonly event: string; readonly data: unknown },
{ readonly id?: string | undefined; readonly event: string; readonly data: string },
any,
any
>,
@@ -375,11 +375,11 @@ export interface Event {
export const EventEncoded: Schema.Struct<{
readonly id: Schema.UndefinedOr<Schema.String>
readonly event: Schema.String
readonly data: Schema.UnknownFromJsonString
readonly data: Schema.String
}> = Schema.Struct({
id: Schema.UndefinedOr(Schema.String),
event: Schema.String,
data: Schema.UnknownFromJsonString
data: Schema.String
})
/**
@@ -390,12 +390,12 @@ export const Event: Schema.Struct<{
readonly _tag: Schema.tag<"Event">
readonly id: Schema.UndefinedOr<Schema.String>
readonly event: Schema.String
readonly data: Schema.UnknownFromJsonString
readonly data: Schema.String
}> = Schema.Struct({
_tag: Schema.tag("Event"),
id: Schema.UndefinedOr(Schema.String),
event: Schema.String,
data: Schema.UnknownFromJsonString
data: Schema.String
})
/**
@@ -405,12 +405,12 @@ export const Event: Schema.Struct<{
export const transformEvent = Transformation.transform<{
readonly id?: string | undefined
readonly event: string
readonly data: unknown
readonly data: string
}, {
readonly _tag: "Event"
readonly id: string | undefined
readonly event: string
readonly data: unknown
readonly data: string
}>({
decode: (event) => event,
encode: (event) => ({
@@ -0,0 +1,62 @@
import { assert, describe, it } from "@effect/vitest"
import { Effect, Stream } from "effect"
import * as Schema from "effect/Schema"
import * as Sse from "effect/unstable/encoding/Sse"
describe("Sse", () => {
it("Event preserves string payloads", () => {
const decode = Schema.decodeUnknownSync(Sse.Event)
const encode = Schema.encodeSync(Sse.Event)
const event = decode({
_tag: "Event",
event: "message",
id: undefined,
data: "{\"type\":\"ok\"}"
})
assert.strictEqual(event.data, "{\"type\":\"ok\"}")
assert.deepStrictEqual(encode(event), {
_tag: "Event",
event: "message",
id: undefined,
data: "{\"type\":\"ok\"}"
})
})
it("EventEncoded consumers can explicitly decode json payloads", () => {
const EventWithJsonPayload = Schema.Struct({
...Sse.EventEncoded.fields,
data: Schema.fromJsonString(Schema.Struct({
type: Schema.String
}))
})
const decode = Schema.decodeUnknownSync(EventWithJsonPayload)
const event = decode({
event: "message",
id: undefined,
data: "{\"type\":\"ok\"}"
})
assert.deepStrictEqual(event.data, { type: "ok" })
})
it.effect("decodeDataSchema decodes json payload from SSE stream", () =>
Effect.gen(function*() {
const events = yield* Stream.make(
"event: message\ndata: {\"type\":\"ok\"}\n\n"
).pipe(
Stream.pipeThroughChannel(Sse.decodeDataSchema(Schema.Struct({ type: Schema.String }))),
Stream.runCollect
)
assert.deepStrictEqual([...events], [{
event: "message",
id: undefined,
data: {
type: "ok"
}
}])
}))
})
@@ -309,7 +309,7 @@ export const make = (
)
}
const operationToSseImpl = (importName: string, operation: ParsedOperation) => {
const operationToSseImpl = (_importName: string, operation: ParsedOperation) => {
const args: Array<string> = [...operation.pathIds]
const hasOptions = (operation.params && !operation.paramsOptional) || operation.payload
if (hasOptions || operation.params || operation.payload) {
@@ -341,11 +341,7 @@ export const make = (
pipeline.push(`HttpClientRequest.bodyJsonUnsafe(options.payload)`)
}
const eventSchema = `${importName}.Struct({
...Sse.EventEncoded.fields,
data: ${operation.sseSchema}
})`
pipeline.push(`sseRequest(${eventSchema})`)
pipeline.push(`sseRequest(${operation.sseSchema})`)
return (
`"${operation.id}Sse": (${params}) => ` +
@@ -848,28 +844,23 @@ const commonSource = `const unexpectedStatus = (response: HttpClientResponse.Htt
const sseRequestSource = (_importName: string) =>
`const sseRequest = <
Type extends {
readonly id?: string | undefined
readonly event: string
readonly data: unknown
},
Type,
DecodingServices
>(
schema: Schema.Decoder<Type, DecodingServices>
) =>
(
request: HttpClientRequest.HttpClientRequest
): Stream.Stream<Type, HttpClientError.HttpClientError | SchemaError | Sse.Retry, DecodingServices> =>
): Stream.Stream<
{ readonly event: string; readonly id: string | undefined; readonly data: Type },
HttpClientError.HttpClientError | SchemaError | Sse.Retry,
DecodingServices
> =>
HttpClient.filterStatusOk(httpClient).execute(request).pipe(
Effect.map((response) => response.stream),
Stream.unwrap,
Stream.decodeText(),
Stream.pipeThroughChannel(Sse.decodeSchema<
Type,
DecodingServices,
HttpClientError.HttpClientError,
unknown
>(schema))
Stream.pipeThroughChannel(Sse.decodeDataSchema(schema))
)`
const binaryRequestSource =
@@ -35,6 +35,23 @@ function assertTypeOnly(spec: OpenAPISpec, expected: string) {
)
}
function assertRuntimeIncludes(spec: OpenAPISpec, includes: ReadonlyArray<string>) {
return Effect.gen(function*() {
const generator = yield* OpenApiGenerator.OpenApiGenerator
const result = yield* generator.generate(spec, {
name: "TestClient",
typeOnly: false
})
for (const expected of includes) {
assert.include(result, expected)
}
}).pipe(
Effect.provide(OpenApiGenerator.layerTransformerSchema)
)
}
describe("OpenApiGenerator", () => {
describe("schema", () => {
it.effect("get operation", () =>
@@ -217,6 +234,61 @@ export const TestClientError = <Tag extends string, E>(
request: response.request,
}) as any`
))
it.effect("sse operation decodes event payload from json string", () =>
assertRuntimeIncludes(
{
openapi: "3.1.0",
info: {
title: "Test API",
version: "1.0.0"
},
paths: {
"/events": {
get: {
operationId: "streamEvents",
parameters: [],
responses: {
200: {
description: "Events streamed successfully",
content: {
"text/event-stream": {
schema: {
type: "object",
properties: {
type: {
type: "string"
},
value: {
type: "string"
}
},
required: ["type", "value"],
additionalProperties: false
}
}
}
}
},
tags: ["Events"],
security: []
}
}
},
components: {
schemas: {},
securitySchemes: {}
},
security: [],
tags: []
},
[
`import * as Sse from "effect/unstable/encoding/Sse"`,
`readonly "streamEventsSse": () => Stream.Stream<{ readonly event: string; readonly id: string | undefined; readonly data: typeof StreamEvents200Sse.Type }, HttpClientError.HttpClientError | SchemaError | Sse.Retry, typeof StreamEvents200Sse.DecodingServices>`,
`"streamEventsSse": () => HttpClientRequest.get(\`/events\`).pipe(`,
`sseRequest(StreamEvents200Sse)`
]
))
})
describe("type-only", () => {
+24 -26
View File
@@ -161,6 +161,12 @@ importers:
specifier: workspace:^
version: link:../../effect
packages/ai/openai-compat:
devDependencies:
effect:
specifier: workspace:^
version: link:../../effect
packages/atom/react:
devDependencies:
'@testing-library/dom':
@@ -684,6 +690,9 @@ importers:
'@effect/ai-openai':
specifier: workspace:*
version: link:../packages/ai/openai
'@effect/ai-openai-compat':
specifier: workspace:*
version: link:../packages/ai/openai-compat
'@effect/opentelemetry':
specifier: workspace:*
version: link:../packages/opentelemetry
@@ -6652,7 +6661,7 @@ snapshots:
'@babel/types': 7.29.0
'@jridgewell/remapping': 2.3.5
convert-source-map: 2.0.0
debug: 4.4.3
debug: 4.4.3(supports-color@10.2.2)
gensync: 1.0.0-beta.2
json5: 2.2.3
semver: 6.3.1
@@ -6948,7 +6957,7 @@ snapshots:
'@babel/parser': 7.29.0
'@babel/template': 7.28.6
'@babel/types': 7.29.0
debug: 4.4.3
debug: 4.4.3(supports-color@10.2.2)
transitivePeerDependencies:
- supports-color
@@ -8217,7 +8226,7 @@ snapshots:
'@tokenizer/inflate@0.4.1':
dependencies:
debug: 4.4.3
debug: 4.4.3(supports-color@10.2.2)
token-types: 6.1.2
transitivePeerDependencies:
- supports-color
@@ -8386,7 +8395,7 @@ snapshots:
dependencies:
'@typescript-eslint/tsconfig-utils': 8.54.0(typescript@5.9.3)
'@typescript-eslint/types': 8.54.0
debug: 4.4.3
debug: 4.4.3(supports-color@10.2.2)
typescript: 5.9.3
transitivePeerDependencies:
- supports-color
@@ -8403,7 +8412,7 @@ snapshots:
'@typescript-eslint/tsconfig-utils': 8.54.0(typescript@5.9.3)
'@typescript-eslint/types': 8.54.0
'@typescript-eslint/visitor-keys': 8.54.0
debug: 4.4.3
debug: 4.4.3(supports-color@10.2.2)
minimatch: 9.0.5
semver: 7.7.3
tinyglobby: 0.2.15
@@ -8885,7 +8894,7 @@ snapshots:
dependencies:
bytes: 3.1.2
content-type: 1.0.5
debug: 4.4.3
debug: 4.4.3(supports-color@10.2.2)
http-errors: 2.0.1
iconv-lite: 0.7.2
on-finished: 2.4.1
@@ -9176,10 +9185,6 @@ snapshots:
dependencies:
ms: 2.0.0
debug@4.4.3:
dependencies:
ms: 2.1.3
debug@4.4.3(supports-color@10.2.2):
dependencies:
ms: 2.1.3
@@ -9530,7 +9535,7 @@ snapshots:
content-type: 1.0.5
cookie: 0.7.2
cookie-signature: 1.2.2
debug: 4.4.3
debug: 4.4.3(supports-color@10.2.2)
depd: 2.0.0
encodeurl: 2.0.0
escape-html: 1.0.3
@@ -9685,7 +9690,7 @@ snapshots:
finalhandler@2.1.1:
dependencies:
debug: 4.4.3
debug: 4.4.3(supports-color@10.2.2)
encodeurl: 2.0.0
escape-html: 1.0.3
on-finished: 2.4.1
@@ -9956,19 +9961,12 @@ snapshots:
http-proxy-agent@7.0.2:
dependencies:
agent-base: 7.1.4
debug: 4.4.3
debug: 4.4.3(supports-color@10.2.2)
transitivePeerDependencies:
- supports-color
http2-client@1.3.5: {}
https-proxy-agent@7.0.6:
dependencies:
agent-base: 7.1.4
debug: 4.4.3
transitivePeerDependencies:
- supports-color
https-proxy-agent@7.0.6(supports-color@10.2.2):
dependencies:
agent-base: 7.1.4
@@ -10297,7 +10295,7 @@ snapshots:
decimal.js: 10.6.0
html-encoding-sniffer: 6.0.0
http-proxy-agent: 7.0.2
https-proxy-agent: 7.0.6
https-proxy-agent: 7.0.6(supports-color@10.2.2)
is-potential-custom-element-name: 1.0.1
parse5: 8.0.0
saxes: 6.0.0
@@ -10480,7 +10478,7 @@ snapshots:
chalk: 4.1.2
commander: 7.2.0
commondir: 1.0.1
debug: 4.4.3
debug: 4.4.3(supports-color@10.2.2)
dependency-tree: 11.2.0
ora: 5.4.1
pluralize: 8.0.0
@@ -11582,7 +11580,7 @@ snapshots:
rollup-plugin-esbuild@6.2.1(esbuild@0.27.2)(rollup@4.57.1):
dependencies:
debug: 4.4.3
debug: 4.4.3(supports-color@10.2.2)
es-module-lexer: 1.7.0
esbuild: 0.27.2
get-tsconfig: 4.13.1
@@ -11645,7 +11643,7 @@ snapshots:
router@2.2.0:
dependencies:
debug: 4.4.3
debug: 4.4.3(supports-color@10.2.2)
depd: 2.0.0
is-promise: 4.0.0
parseurl: 1.3.3
@@ -11733,7 +11731,7 @@ snapshots:
send@1.2.1:
dependencies:
debug: 4.4.3
debug: 4.4.3(supports-color@10.2.2)
encodeurl: 2.0.0
escape-html: 1.0.3
etag: 1.8.1
@@ -12383,7 +12381,7 @@ snapshots:
vite-tsconfig-paths@6.0.5(typescript@5.9.3)(vite@7.3.1(@types/node@25.2.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)):
dependencies:
debug: 4.4.3
debug: 4.4.3(supports-color@10.2.2)
globrex: 0.1.2
tsconfck: 3.1.6(typescript@5.9.3)
vite: 7.3.1(@types/node@25.2.0)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2)
+1
View File
@@ -6,6 +6,7 @@
"dependencies": {
"@effect/ai-anthropic": "workspace:*",
"@effect/ai-openai": "workspace:*",
"@effect/ai-openai-compat": "workspace:*",
"effect": "workspace:*",
"@effect/opentelemetry": "workspace:*",
"@effect/platform-bun": "workspace:*",
+2
View File
@@ -39,6 +39,8 @@
"effect/*": ["./packages/effect/src/*.ts"],
"@effect/ai-anthropic": ["./packages/ai/anthropic/src/index.ts"],
"@effect/ai-anthropic/*": ["./packages/ai/anthropic/src/*.ts"],
"@effect/ai-openai-compat": ["./packages/ai/openai-compat/src/index.ts"],
"@effect/ai-openai-compat/*": ["./packages/ai/openai-compat/src/*.ts"],
"@effect/ai-openai": ["./packages/ai/openai/src/index.ts"],
"@effect/ai-openai/*": ["./packages/ai/openai/src/*.ts"],
"@effect/atom-react": ["./packages/atom/react/src/index.ts"],
+1
View File
@@ -5,6 +5,7 @@
"references": [
{ "path": "packages/effect" },
{ "path": "packages/ai/anthropic" },
{ "path": "packages/ai/openai-compat" },
{ "path": "packages/ai/openai" },
{ "path": "packages/atom/react" },
{ "path": "packages/atom/vue" },