configure-sdk-options

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Configure SDK Options

配置SDK选项

Configure gen.yaml options for an existing Speakeasy SDK. Supports TypeScript, Python, Go, Java, C#, PHP, and Ruby.
For new SDK projects: Use
start-new-sdk-project
skill instead. This skill is for configuring an existing SDK.
为现有的Speakeasy SDK配置gen.yaml选项。支持TypeScript、Python、Go、Java、C#、PHP和Ruby语言。
新SDK项目注意:请使用
start-new-sdk-project
技能。本技能仅用于配置已有的SDK。

Language-Specific Guides

语言专属指南

For comprehensive configuration details, see the language-specific guides:
LanguageGuideKey Features
TypeScriptcontent/languages/typescript.mdZod validation, React Query, standalone functions, dual module format
Pythoncontent/languages/python.mdPydantic models, async modes (both/split), uv/poetry support
Gocontent/languages/go.mdResponse formats, interface generation, K8s integration
Javacontent/languages/java.mdBuilder pattern, Gradle customization, Maven Central publishing
C#content/languages/csharp.mdAsync/await, cancellation tokens, DI integration, NuGet
PHPcontent/languages/php.mdLaravel integration, Guzzle config, Packagist publishing
Rubycontent/languages/ruby.mdSorbet typing, Rails integration, RubyGems publishing
These guides include detailed configuration options, code examples, framework integrations, and publishing instructions.
如需详细的配置说明,请查看各语言专属指南:
语言指南核心特性
TypeScriptcontent/languages/typescript.mdZod验证、React Query、独立函数、双模块格式
Pythoncontent/languages/python.mdPydantic模型、异步模式(混合/分离)、uv/poetry支持
Gocontent/languages/go.md响应格式、接口生成、K8s集成
Javacontent/languages/java.md建造者模式、Gradle自定义、Maven Central发布
C#content/languages/csharp.mdAsync/await、取消令牌、DI集成、NuGet发布
PHPcontent/languages/php.mdLaravel集成、Guzzle配置、Packagist发布
Rubycontent/languages/ruby.mdSorbet类型检查、Rails集成、RubyGems发布
这些指南包含详细的配置选项、代码示例、框架集成及发布说明。

When to Use

适用场景

  • Configuring language-specific gen.yaml options on an existing SDK
  • Setting up SDK hooks, async patterns, or publishing
  • Configuring runtime behavior (retries, timeouts, server selection) in application code
  • User says: "configure SDK", "gen.yaml options", "SDK config", "runtime override", "per-call config"
  • User asks about: Zod, Pydantic, NuGet, PyPI, npm, Maven Central, Packagist, RubyGems
  • 为现有SDK配置语言专属的gen.yaml选项
  • 设置SDK钩子、异步模式或发布配置
  • 在应用代码中配置运行时行为(重试、超时、服务器选择)
  • 用户提及:"configure SDK"、"gen.yaml options"、"SDK config"、"runtime override"、"per-call config"
  • 用户咨询:Zod、Pydantic、NuGet、PyPI、npm、Maven Central、Packagist、RubyGems相关内容

Inputs

输入参数

InputRequiredDescription
Existing SDKYesSDK with
.speakeasy/workflow.yaml
already created
Target languageYesTypeScript, Python, Go, Java, C#, PHP, or Ruby
输入项是否必填描述
现有SDK已创建
.speakeasy/workflow.yaml
的SDK
目标语言TypeScript、Python、Go、Java、C#、PHP或Ruby

Outputs

输出结果

OutputDescription
Updated gen.yamlLanguage-specific configuration
Hook filesCustom hooks if enabled
输出项描述
更新后的gen.yaml语言专属的配置文件
钩子文件若启用则生成自定义钩子文件

Prerequisites

前置条件

You must have an existing SDK with
.speakeasy/workflow.yaml
. If not, run:
bash
speakeasy quickstart --skip-interactive --output console \
  -s openapi.yaml -t <language> -n "MySDK" -p "<package-name>"
你必须拥有一个已创建
.speakeasy/workflow.yaml
的SDK。若没有,请执行以下命令:
bash
speakeasy quickstart --skip-interactive --output console \
  -s openapi.yaml -t <language> -n "MySDK" -p "<package-name>"

Common Configuration (All Languages)

通用配置(所有语言)

These options apply to all SDK targets in gen.yaml:
yaml
<language>:
  version: 1.0.0
  packageName: "my-sdk"

  # Method signatures
  maxMethodParams: 4              # Params before request object
  flatteningOrder: parameters-first

  # Error handling
  responseFormat: flat            # or "envelope" (Go)
  clientServerStatusCodesAsErrors: true
以下选项适用于gen.yaml中的所有SDK目标:
yaml
<language>:
  version: 1.0.0
  packageName: "my-sdk"

  # 方法签名
  maxMethodParams: 4              # 使用请求对象前的参数数量
  flatteningOrder: parameters-first

  # 错误处理
  responseFormat: flat            # 或"envelope"(仅Go支持)
  clientServerStatusCodesAsErrors: true

TypeScript Configuration

TypeScript配置

yaml
typescript:
  version: 1.0.0
  packageName: "@myorg/my-sdk"
  moduleFormat: dual              # esm, commonjs, or dual
  zodVersion: v4-mini             # v3, v4, or v4-mini
  enableCustomCodeRegions: true   # For custom code
  enableReactQuery: true          # React Query hooks
FeatureNotes
Zod validationAutomatic for all models
Tree-shakingUse
moduleFormat: dual
+ standalone functions
JSR publishingCreate
jsr.json
, run
deno publish
npm publishingStandard
npm publish
Standalone functions for tree-shaking:
typescript
import { TodoCore } from "my-sdk/core.js";
import { todosCreate } from "my-sdk/funcs/todosCreate.js";
const sdk = new TodoCore({ apiKey: "..." });
yaml
typescript:
  version: 1.0.0
  packageName: "@myorg/my-sdk"
  moduleFormat: dual              # esm、commonjs或dual
  zodVersion: v4-mini             # v3、v4或v4-mini
  enableCustomCodeRegions: true   # 启用自定义代码区域
  enableReactQuery: true          # 启用React Query钩子
特性说明
Zod验证为所有模型自动生成验证逻辑
Tree-shaking使用
moduleFormat: dual
+ 独立函数实现
JSR发布创建
jsr.json
后执行
deno publish
npm发布使用标准
npm publish
命令
支持Tree-shaking的独立函数用法:
typescript
import { TodoCore } from "my-sdk/core.js";
import { todosCreate } from "my-sdk/funcs/todosCreate.js";
const sdk = new TodoCore({ apiKey: "..." });

Python Configuration

Python配置

yaml
python:
  version: 1.0.0
  packageName: "my-sdk"
  asyncMode: both                 # both or split
  packageManager: uv              # uv or poetry
  envVarPrefix: ""                # Prefix for env config
FeatureNotes
Pydantic modelsAutomatic for all models
Async mode
both
sdk.method()
and
sdk.method_async()
Async mode
split
SDK()
and
AsyncSDK()
constructors
PyPI publishing
uv publish
or
poetry publish
Async patterns:
python
undefined
yaml
python:
  version: 1.0.0
  packageName: "my-sdk"
  asyncMode: both                 # both或split
  packageManager: uv              # uv或poetry
  envVarPrefix: ""                # 环境变量配置前缀
特性说明
Pydantic模型为所有模型自动生成Pydantic定义
异步模式
both
同时支持
sdk.method()
(同步)和
sdk.method_async()
(异步)
异步模式
split
分别提供
SDK()
(仅同步)和
AsyncSDK()
(仅异步)构造函数
PyPI发布使用
uv publish
poetry publish
命令
异步模式示例:
python
undefined

asyncMode: both (default)

asyncMode: both(默认)

result = sdk.users.list() # sync result = await sdk.users.list_async() # async
result = sdk.users.list() # 同步调用 result = await sdk.users.list_async() # 异步调用

asyncMode: split

asyncMode: split

sdk = MySDK() # sync only async_sdk = AsyncMySDK() # async only
undefined
sdk = MySDK() # 仅同步客户端 async_sdk = AsyncMySDK() # 仅异步客户端
undefined

Go Configuration

Go配置

yaml
go:
  version: 0.1.0
  packageName: github.com/myorg/my-sdk
  maxMethodParams: 2
  methodArguments: require-security-and-request
  responseFormat: envelope
  flattenGlobalSecurity: true
FeatureNotes
InterfacesGenerate with ifacemaker
MocksGenerate with mockery
K8s integrationAdd kubebuilder markers, run controller-gen
Interface generation for testing:
bash
go install github.com/vburenin/ifacemaker@latest
go install github.com/vektra/mockery/v2@latest
ifacemaker --file consumers.go --struct Consumers --iface ConsumersSDK --output consumers_i.go
mockery
yaml
go:
  version: 0.1.0
  packageName: github.com/myorg/my-sdk
  maxMethodParams: 2
  methodArguments: require-security-and-request
  responseFormat: envelope
  flattenGlobalSecurity: true
特性说明
接口生成使用ifacemaker工具生成接口
Mock生成使用mockery工具生成Mock对象
K8s集成添加kubebuilder标记后执行controller-gen
用于测试的接口生成命令:
bash
go install github.com/vburenin/ifacemaker@latest
go install github.com/vektra/mockery/v2@latest
ifacemaker --file consumers.go --struct Consumers --iface ConsumersSDK --output consumers_i.go
mockery

Java Configuration

Java配置

yaml
java:
  version: 1.0.0
  groupID: com.myorg
  artifactID: my-sdk
  packageName: com.myorg.mysdk
  methodArguments: require-security-and-request
FeatureNotes
Builder patternAutomatic for all classes
Build customizationUse
build-extras.gradle
(preserved)
Maven Central
./gradlew publishToSonatype closeAndReleaseSonatypeStagingRepository
Client usage:
java
MySdk sdk = MySdk.builder()
    .security(Security.builder().apiKey("key").build())
    .build();
yaml
java:
  version: 1.0.0
  groupID: com.myorg
  artifactID: my-sdk
  packageName: com.myorg.mysdk
  methodArguments: require-security-and-request
特性说明
建造者模式为所有类自动生成建造者实现
构建自定义编辑
build-extras.gradle
(会被保留)
Maven Central发布执行
./gradlew publishToSonatype closeAndReleaseSonatypeStagingRepository
客户端使用示例:
java
MySdk sdk = MySdk.builder()
    .security(Security.builder().apiKey("key").build())
    .build();

C# Configuration

C#配置

yaml
csharp:
  version: 1.0.0
  packageName: MyOrg.MySDK
  dotnetVersion: "6.0"
  baseErrorName: MySDKException
FeatureNotes
Async/awaitAll operations async by default
SSE streaming
EventStream<T>
support
NuGet publishing
dotnet pack -c Release && dotnet nuget push
Async with cancellation:
csharp
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var result = await sdk.Users.ListAsync(cancellationToken: cts.Token);
yaml
csharp:
  version: 1.0.0
  packageName: MyOrg.MySDK
  dotnetVersion: "6.0"
  baseErrorName: MySDKException
特性说明
Async/await所有操作默认支持异步
SSE流支持
EventStream<T>
类型
NuGet发布执行
dotnet pack -c Release && dotnet nuget push
带取消令牌的异步调用示例:
csharp
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var result = await sdk.Users.ListAsync(cancellationToken: cts.Token);

PHP Configuration

PHP配置

yaml
php:
  version: 1.0.0
  packageName: myorg/my-sdk
  namespace: MyOrg\MySDK
FeatureNotes
PHP 8.2+Required minimum version
GuzzleHTTP client (configurable timeout)
PackagistTag release, register on Packagist.org
Security callback for token refresh:
php
$sdk = MySDK\MySDK::builder()
    ->setSecuritySource(fn() => getTokenFromCache() ?? refreshToken())
    ->build();
yaml
php:
  version: 1.0.0
  packageName: myorg/my-sdk
  namespace: MyOrg\MySDK
特性说明
PHP版本要求最低支持PHP 8.2+
Guzzle客户端可配置超时的HTTP客户端
Packagist发布打版本标签后在Packagist.org注册
用于令牌刷新的安全回调示例:
php
$sdk = MySDK\MySDK::builder()
    ->setSecuritySource(fn() => getTokenFromCache() ?? refreshToken())
    ->build();

Ruby Configuration

Ruby配置

yaml
ruby:
  version: 1.0.0
  packageName: my-sdk
  module: MySdk
  typingStrategy: sorbet          # sorbet or none
FeatureNotes
Sorbet typingOptional, enable with
typingStrategy: sorbet
FaradayHTTP client
RubyGems
gem build && gem push
yaml
ruby:
  version: 1.0.0
  packageName: my-sdk
  module: MySdk
  typingStrategy: sorbet          # sorbet或none
特性说明
Sorbet类型检查可选特性,通过
typingStrategy: sorbet
启用
Faraday客户端HTTP客户端
RubyGems发布执行
gem build && gem push

SDK Hooks (All Languages)

SDK钩子(所有语言)

Enable custom hooks with
enableCustomCodeRegions: true
. Hook files are preserved across regeneration.
LanguageHook Location
TypeScript
src/hooks/
Python
src/<pkg>/_hooks/
Go
internal/hooks/
Java
src/main/java/.../hooks/
C#
src/.../Hooks/
PHP
src/Hooks/
Ruby
lib/.../sdk_hooks/
See
customize-sdk-hooks
skill for detailed hook implementation.
设置
enableCustomCodeRegions: true
即可启用自定义钩子。钩子文件在SDK重新生成时会被保留。
语言钩子文件位置
TypeScript
src/hooks/
Python
src/<pkg>/_hooks/
Go
internal/hooks/
Java
src/main/java/.../hooks/
C#
src/.../Hooks/
PHP
src/Hooks/
Ruby
lib/.../sdk_hooks/
如需钩子的详细实现说明,请查看
customize-sdk-hooks
技能。

Runtime Overrides

运行时覆盖

Runtime behavior can be configured at SDK instantiation or per-call. These override gen.yaml defaults.
可在SDK实例化时或单次调用时配置运行时行为,这些配置会覆盖gen.yaml中的默认值。

Server Selection

服务器选择

Define server IDs in OpenAPI spec, then select at runtime:
yaml
undefined
在OpenAPI规范中定义服务器ID,即可在运行时选择对应服务器:
yaml
undefined

OpenAPI spec

OpenAPI规范示例

servers:

| Language | SDK Constructor | Custom URL |
|----------|-----------------|------------|
| TypeScript | `new SDK({ server: "sandbox" })` | `new SDK({ serverURL: "..." })` |
| Python | `SDK(server="sandbox")` | `SDK(server_url="...")` |
| Go | `SDK.New(SDK.WithServer("sandbox"))` | `SDK.WithServerURL("...")` |
servers:

| 语言 | SDK构造函数配置 | 自定义URL配置 |
|----------|-----------------|------------|
| TypeScript | `new SDK({ server: "sandbox" })` | `new SDK({ serverURL: "..." })` |
| Python | `SDK(server="sandbox")` | `SDK(server_url="...")` |
| Go | `SDK.New(SDK.WithServer("sandbox"))` | `SDK.WithServerURL("...")` |

Retry Overrides

重试策略覆盖

Override retry behavior per-call (spec defaults set via
x-speakeasy-retries
):
TypeScript:
typescript
const res = await sdk.payments.create({ amount: 1000 }, {
  retries: {
    strategy: "backoff",
    backoff: { initialInterval: 1000, maxInterval: 30000, maxElapsedTime: 120000, exponent: 2.0 },
    retryConnectionErrors: true,
  },
});
Python:
python
from sdk.utils import BackoffStrategy, RetryConfig
res = sdk.payments.create(amount=1000, retries=RetryConfig("backoff",
    backoff=BackoffStrategy(1000, 30000, 120000, 2.0), retry_connection_errors=True))
Go:
go
res, err := sdk.Payments.Create(ctx, req, operations.WithRetries(retry.Config{
    Strategy: "backoff", Backoff: &retry.BackoffStrategy{
        InitialInterval: 1000, MaxInterval: 30000, MaxElapsedTime: 120000, Exponent: 2.0},
    RetryConnectionErrors: true}))
可在单次调用时覆盖重试行为(规范中的默认值通过
x-speakeasy-retries
设置):
TypeScript示例:
typescript
const res = await sdk.payments.create({ amount: 1000 }, {
  retries: {
    strategy: "backoff",
    backoff: { initialInterval: 1000, maxInterval: 30000, maxElapsedTime: 120000, exponent: 2.0 },
    retryConnectionErrors: true,
  },
});
Python示例:
python
from sdk.utils import BackoffStrategy, RetryConfig
res = sdk.payments.create(amount=1000, retries=RetryConfig("backoff",
    backoff=BackoffStrategy(1000, 30000, 120000, 2.0), retry_connection_errors=True))
Go示例:
go
res, err := sdk.Payments.Create(ctx, req, operations.WithRetries(retry.Config{
    Strategy: "backoff", Backoff: &retry.BackoffStrategy{
        InitialInterval: 1000, MaxInterval: 30000, MaxElapsedTime: 120000, Exponent: 2.0},
    RetryConnectionErrors: true}))

Timeout Overrides

超时配置覆盖

Set global timeout on SDK constructor, or per-call:
LanguageGlobalPer-call
TypeScript
new SDK({ timeoutMs: 30000 })
sdk.op({}, { timeoutMs: 60000 })
Python
SDK(timeout_ms=30000)
sdk.op(timeout_ms=60000)
Go
SDK.WithTimeoutMs(30000)
operations.WithTimeoutMs(60000)
可在SDK构造函数中设置全局超时,或在单次调用时单独配置:
语言全局配置单次调用配置
TypeScript
new SDK({ timeoutMs: 30000 })
sdk.op({}, { timeoutMs: 60000 })
Python
SDK(timeout_ms=30000)
sdk.op(timeout_ms=60000)
Go
SDK.WithTimeoutMs(30000)
operations.WithTimeoutMs(60000)

Pagination Usage

分页使用

SDK auto-generates pagination helpers when
x-speakeasy-pagination
is set in spec:
typescript
// Auto-iterate all pages
for await (const user of await sdk.users.list({ limit: 50 })) {
  console.log(user.name);
}

// Manual pagination
let page = await sdk.users.list({ limit: 50 });
while (page) {
  for (const user of page.data) { console.log(user.name); }
  page = await page.next();
}
当OpenAPI规范中设置了
x-speakeasy-pagination
时,SDK会自动生成分页辅助方法:
typescript
// 自动遍历所有分页
for await (const user of await sdk.users.list({ limit: 50 })) {
  console.log(user.name);
}

// 手动分页
let page = await sdk.users.list({ limit: 50 });
while (page) {
  for (const user of page.data) { console.log(user.name); }
  page = await page.next();
}

Decision Framework

决策框架

SituationAction
Need tree-shaking (TS)Set
moduleFormat: dual
, use standalone functions
Need async/sync (Python)Set
asyncMode: both
(default)
Need separate async clientSet
asyncMode: split
(Python)
Need interfaces for testing (Go)Use ifacemaker + mockery
Need custom build config (Java)Edit
build-extras.gradle
Need runtime retry overridePass
retries
config in per-call options
Need runtime timeout overrideSet
timeoutMs
on constructor or per-call
Need server switchingUse
x-speakeasy-server-id
in spec, select at runtime
场景操作
TypeScript需要Tree-shaking设置
moduleFormat: dual
并使用独立函数
Python需要同步/异步兼容设置
asyncMode: both
(默认值)
Python需要独立异步客户端设置
asyncMode: split
Go需要测试用接口使用ifacemaker + mockery工具
Java需要自定义构建配置编辑
build-extras.gradle
需要覆盖运行时重试策略在单次调用选项中传入
retries
配置
需要覆盖运行时超时在构造函数或单次调用时设置
timeoutMs
需要切换服务器在规范中添加
x-speakeasy-server-id
,运行时选择对应ID

What NOT to Do

禁止操作

  • Do NOT use this skill for initial SDK generation - use
    start-new-sdk-project
  • Do NOT edit generated files outside custom code regions
  • Do NOT modify files in
    src/
    that aren't in preserved directories (hooks, extra)
  • 请勿将本技能用于SDK初始生成——请使用
    start-new-sdk-project
  • 请勿在自定义代码区域外编辑生成的文件
  • 请勿修改
    src/
    目录中非保留目录(钩子、extra)下的文件

Troubleshooting

故障排查

LanguageIssueSolution
TypeScriptBundle too largeUse standalone functions
PythonAsync pagination blockingEnable
fixFlags.asyncPaginationSep2025: true
GoInterface not generatedEnsure struct is exported (capitalized)
JavaGradle sync failsRun
./gradlew --refresh-dependencies
C#Async deadlockUse
await
not
.Result
PHPPHP version errorRequires PHP 8.2+
RubySorbet errorsRun
bundle exec tapioca gems
AllRetries not workingEnsure
x-speakeasy-retries
at document root or operation level
AllServer ID not recognizedAdd
x-speakeasy-server-id
to each server entry
AllPagination
next()
undefined
Add
x-speakeasy-pagination
to the list operation
语言问题解决方案
TypeScript打包体积过大使用独立函数
Python异步分页阻塞启用
fixFlags.asyncPaginationSep2025: true
Go接口未生成确保结构体为公开(首字母大写)
JavaGradle同步失败执行
./gradlew --refresh-dependencies
C#异步死锁使用
await
而非
.Result
PHPPHP版本错误升级至PHP 8.2+
RubySorbet报错执行
bundle exec tapioca gems
所有语言重试策略不生效确保在文档根节点或操作级别设置了
x-speakeasy-retries
所有语言服务器ID不被识别为每个服务器条目添加
x-speakeasy-server-id
所有语言分页
next()
方法未定义
在列表操作中添加
x-speakeasy-pagination

After Making Changes

修改配置后操作

After modifying gen.yaml configuration, prompt the user to regenerate the SDK:
Configuration complete. Would you like to regenerate the SDK now with
speakeasy run
?
If the user confirms, run:
bash
speakeasy run --output console
Changes to gen.yaml only take effect after regeneration.
修改gen.yaml配置后,请提示用户重新生成SDK:
配置完成。是否现在执行
speakeasy run
重新生成SDK?
若用户确认,请执行以下命令:
bash
speakeasy run --output console
gen.yaml的修改需在SDK重新生成后才会生效。

Related Skills

相关技能

  • start-new-sdk-project
    - Initial SDK generation
  • customize-sdk-hooks
    - Detailed hook implementation
  • manage-openapi-overlays
    - Spec customization
  • start-new-sdk-project
    - SDK初始生成
  • customize-sdk-hooks
    - 钩子详细实现
  • manage-openapi-overlays
    - 规范自定义