mirror of
https://github.com/Effect-TS/effect.git
synced 2026-11-30 02:55:45 +08:00
9.4 KiB
9.4 KiB
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-compatunderpackages/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-openaibehavior.
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-openaiusesGenerated.tswith full OpenAI OpenAPI codegen.OpenAiClientdepends on generated client and schemas for responses, streaming, and embeddings.OpenAiLanguageModelrelies onGenerated.*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.tssrc/OpenAiLanguageModel.tssrc/OpenAiTool.tssrc/OpenAiStructuredOutput.tssrc/OpenAiTelemetry.tssrc/OpenAiError.tssrc/OpenAiConfig.tssrc/internal/errors.tssrc/internal/utilities.ts(if needed by LanguageModel)src/index.ts(generated viapnpm 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)OpenAiClientOpenAiConfigOpenAiErrorOpenAiLanguageModelOpenAiStructuredOutputOpenAiTelemetryOpenAiTool
Compatibility Notes
- Runtime behavior and error semantics should match
@effect/ai-openaifor 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.tsmanually (no codegen) with only:CreateResponserequest schema (fields used by LanguageModel).Response,ResponseUsage,ResponseStreamEventschemas (fields used for LM output conversion).Tooland tool call item schemas needed by LM andOpenAiTool.Annotationschema for citations.CreateEmbeddingRequestandCreateEmbeddingResponseschemas.
- 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.Jsonfor nested structures not required by LM logic.
- Allow unknown keys via
- Provide type exports matching names used in
OpenAiLanguageModelso 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.
InputItemandInputContent:role+contentfor 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.
- Function tools with
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 (asSchema.Json).
ResponseStreamEvent:typeplus 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[]withembedding: number[],index,object, plusmodelandusagewhen present.
OpenAiClient (compat)
- Implement HTTP calls directly using
HttpClient:createResponse: POST/responses.createResponseStream: POST/responseswithstream: true, decode SSE viaSse.decodeSchemausing minimalResponseStreamEventschema.createEmbedding: POST/embeddings.
- Reuse
OpenAiConfigfor 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.tswith minimal changes:- Use compat
Generatedtypes and schemas. Modeltype should be a union of known literals plusstring & {}(allow any string).- Keep tool mapping, structured output, streaming, reasoning, and metadata behavior consistent.
- Ensure request construction uses minimal
CreateResponseschema with permissive extra fields.
- Use compat
- Continue to use
OpenAiStructuredOutputfor JSON schema conversion. - Continue to add OpenAI telemetry attributes via
OpenAiTelemetry.
Streaming Semantics
- Decode SSE events with
Sse.decodeSchemausing minimalResponseStreamEvent. - Handle the same event types as
@effect/ai-openai; unknown events should be ignored. - Treat
response.completed,response.incomplete, andresponse.failedas terminal events that emit a finish part.
OpenAiTool (compat)
- Keep provider-defined tools but relax schemas:
- Parameters and outputs for complex tools use
Schema.Jsonor minimal structs. - Avoid importing full generated field schemas.
- Parameters and outputs for complex tools use
- 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.jsonshould excludesrc/OpenAiSchema.tsandsrc/internal/**.index.tsmust be generated viapnpm codegen(no manual edits).
Workspace Updates
- Add new path mappings in
tsconfig.jsonandtsconfig.packages.json:@effect/ai-openai-compatand@effect/ai-openai-compat/*.
- Ensure
pnpm-lock.yamlupdates 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/vitestandit.effectpattern, 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 cleanthen re-run). - Run
pnpm build. - Run
pnpm docgen.
Implementation Plan
- Scaffold
packages/ai/openai-compatwithpackage.json,tsconfig.json,vitest.config.ts,docgen.json, basesrcfolder, and workspace path mappings. Include minimal, valid module stubs required by exports sopnpm check/build/docgencan pass once codegen runs. - Implement minimal
src/OpenAiSchema.ts,OpenAiClient.ts,OpenAiConfig.ts,OpenAiError.ts, andsrc/internal/errors.tstogether, with direct HTTP calls and permissive schemas for Responses + Embeddings. - Implement
OpenAiLanguageModel,OpenAiTelemetry,OpenAiStructuredOutput,OpenAiTool, and any shared utilities in one step to keep feature parity and avoid validation gaps. - Add compat test suite (client, LM, structured output/tool smoke, permissive schema handling) using
@effect/vitestpatterns. - Run
pnpm codegento generatesrc/index.tsexports and then run validations:pnpm lint-fix,pnpm test <new tests>,pnpm check(andpnpm cleanif needed),pnpm build,pnpm docgen.