configure-sdk-options
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseConfigure 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: Useskill instead. This skill is for configuring an existing SDK.start-new-sdk-project
为现有的Speakeasy SDK配置gen.yaml选项。支持TypeScript、Python、Go、Java、C#、PHP和Ruby语言。
新SDK项目注意:请使用技能。本技能仅用于配置已有的SDK。start-new-sdk-project
Language-Specific Guides
语言专属指南
For comprehensive configuration details, see the language-specific guides:
| Language | Guide | Key Features |
|---|---|---|
| TypeScript | content/languages/typescript.md | Zod validation, React Query, standalone functions, dual module format |
| Python | content/languages/python.md | Pydantic models, async modes (both/split), uv/poetry support |
| Go | content/languages/go.md | Response formats, interface generation, K8s integration |
| Java | content/languages/java.md | Builder pattern, Gradle customization, Maven Central publishing |
| C# | content/languages/csharp.md | Async/await, cancellation tokens, DI integration, NuGet |
| PHP | content/languages/php.md | Laravel integration, Guzzle config, Packagist publishing |
| Ruby | content/languages/ruby.md | Sorbet typing, Rails integration, RubyGems publishing |
These guides include detailed configuration options, code examples, framework integrations, and publishing instructions.
如需详细的配置说明,请查看各语言专属指南:
| 语言 | 指南 | 核心特性 |
|---|---|---|
| TypeScript | content/languages/typescript.md | Zod验证、React Query、独立函数、双模块格式 |
| Python | content/languages/python.md | Pydantic模型、异步模式(混合/分离)、uv/poetry支持 |
| Go | content/languages/go.md | 响应格式、接口生成、K8s集成 |
| Java | content/languages/java.md | 建造者模式、Gradle自定义、Maven Central发布 |
| C# | content/languages/csharp.md | Async/await、取消令牌、DI集成、NuGet发布 |
| PHP | content/languages/php.md | Laravel集成、Guzzle配置、Packagist发布 |
| Ruby | content/languages/ruby.md | Sorbet类型检查、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
输入参数
| Input | Required | Description |
|---|---|---|
| Existing SDK | Yes | SDK with |
| Target language | Yes | TypeScript, Python, Go, Java, C#, PHP, or Ruby |
| 输入项 | 是否必填 | 描述 |
|---|---|---|
| 现有SDK | 是 | 已创建 |
| 目标语言 | 是 | TypeScript、Python、Go、Java、C#、PHP或Ruby |
Outputs
输出结果
| Output | Description |
|---|---|
| Updated gen.yaml | Language-specific configuration |
| Hook files | Custom hooks if enabled |
| 输出项 | 描述 |
|---|---|
| 更新后的gen.yaml | 语言专属的配置文件 |
| 钩子文件 | 若启用则生成自定义钩子文件 |
Prerequisites
前置条件
You must have an existing SDK with . If not, run:
.speakeasy/workflow.yamlbash
speakeasy quickstart --skip-interactive --output console \
-s openapi.yaml -t <language> -n "MySDK" -p "<package-name>"你必须拥有一个已创建的SDK。若没有,请执行以下命令:
.speakeasy/workflow.yamlbash
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: trueTypeScript 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| Feature | Notes |
|---|---|
| Zod validation | Automatic for all models |
| Tree-shaking | Use |
| JSR publishing | Create |
| npm publishing | Standard |
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 | 使用 |
| JSR发布 | 创建 |
| npm发布 | 使用标准 |
支持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| Feature | Notes |
|---|---|
| Pydantic models | Automatic for all models |
Async mode | |
Async mode | |
| PyPI publishing | |
Async patterns:
python
undefinedyaml
python:
version: 1.0.0
packageName: "my-sdk"
asyncMode: both # both或split
packageManager: uv # uv或poetry
envVarPrefix: "" # 环境变量配置前缀| 特性 | 说明 |
|---|---|
| Pydantic模型 | 为所有模型自动生成Pydantic定义 |
异步模式 | 同时支持 |
异步模式 | 分别提供 |
| PyPI发布 | 使用 |
异步模式示例:
python
undefinedasyncMode: 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
undefinedsdk = MySDK() # 仅同步客户端
async_sdk = AsyncMySDK() # 仅异步客户端
undefinedGo 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| Feature | Notes |
|---|---|
| Interfaces | Generate with ifacemaker |
| Mocks | Generate with mockery |
| K8s integration | Add 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
mockeryyaml
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
mockeryJava Configuration
Java配置
yaml
java:
version: 1.0.0
groupID: com.myorg
artifactID: my-sdk
packageName: com.myorg.mysdk
methodArguments: require-security-and-request| Feature | Notes |
|---|---|
| Builder pattern | Automatic for all classes |
| Build customization | Use |
| Maven Central | |
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| 特性 | 说明 |
|---|---|
| 建造者模式 | 为所有类自动生成建造者实现 |
| 构建自定义 | 编辑 |
| Maven Central发布 | 执行 |
客户端使用示例:
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| Feature | Notes |
|---|---|
| Async/await | All operations async by default |
| SSE streaming | |
| NuGet publishing | |
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流 | 支持 |
| NuGet发布 | 执行 |
带取消令牌的异步调用示例:
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| Feature | Notes |
|---|---|
| PHP 8.2+ | Required minimum version |
| Guzzle | HTTP client (configurable timeout) |
| Packagist | Tag 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| Feature | Notes |
|---|---|
| Sorbet typing | Optional, enable with |
| Faraday | HTTP client |
| RubyGems | |
yaml
ruby:
version: 1.0.0
packageName: my-sdk
module: MySdk
typingStrategy: sorbet # sorbet或none| 特性 | 说明 |
|---|---|
| Sorbet类型检查 | 可选特性,通过 |
| Faraday客户端 | HTTP客户端 |
| RubyGems发布 | 执行 |
SDK Hooks (All Languages)
SDK钩子(所有语言)
Enable custom hooks with . Hook files are preserved across regeneration.
enableCustomCodeRegions: true| Language | Hook Location |
|---|---|
| TypeScript | |
| Python | |
| Go | |
| Java | |
| C# | |
| PHP | |
| Ruby | |
See skill for detailed hook implementation.
customize-sdk-hooks设置即可启用自定义钩子。钩子文件在SDK重新生成时会被保留。
enableCustomCodeRegions: true| 语言 | 钩子文件位置 |
|---|---|
| TypeScript | |
| Python | |
| Go | |
| Java | |
| C# | |
| PHP | |
| Ruby | |
如需钩子的详细实现说明,请查看技能。
customize-sdk-hooksRuntime 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
undefinedOpenAPI spec
OpenAPI规范示例
servers:
- url: https://api.example.com x-speakeasy-server-id: production
- url: https://sandbox.example.com x-speakeasy-server-id: sandbox
| 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:
- url: https://api.example.com x-speakeasy-server-id: production
- url: https://sandbox.example.com x-speakeasy-server-id: sandbox
| 语言 | 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-retriesTypeScript:
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-retriesTypeScript示例:
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:
| Language | Global | Per-call |
|---|---|---|
| TypeScript | | |
| Python | | |
| Go | | |
可在SDK构造函数中设置全局超时,或在单次调用时单独配置:
| 语言 | 全局配置 | 单次调用配置 |
|---|---|---|
| TypeScript | | |
| Python | | |
| Go | | |
Pagination Usage
分页使用
SDK auto-generates pagination helpers when is set in spec:
x-speakeasy-paginationtypescript
// 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规范中设置了时,SDK会自动生成分页辅助方法:
x-speakeasy-paginationtypescript
// 自动遍历所有分页
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
决策框架
| Situation | Action |
|---|---|
| Need tree-shaking (TS) | Set |
| Need async/sync (Python) | Set |
| Need separate async client | Set |
| Need interfaces for testing (Go) | Use ifacemaker + mockery |
| Need custom build config (Java) | Edit |
| Need runtime retry override | Pass |
| Need runtime timeout override | Set |
| Need server switching | Use |
| 场景 | 操作 |
|---|---|
| TypeScript需要Tree-shaking | 设置 |
| Python需要同步/异步兼容 | 设置 |
| Python需要独立异步客户端 | 设置 |
| Go需要测试用接口 | 使用ifacemaker + mockery工具 |
| Java需要自定义构建配置 | 编辑 |
| 需要覆盖运行时重试策略 | 在单次调用选项中传入 |
| 需要覆盖运行时超时 | 在构造函数或单次调用时设置 |
| 需要切换服务器 | 在规范中添加 |
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 that aren't in preserved directories (hooks, extra)
src/
- 请勿将本技能用于SDK初始生成——请使用
start-new-sdk-project - 请勿在自定义代码区域外编辑生成的文件
- 请勿修改目录中非保留目录(钩子、extra)下的文件
src/
Troubleshooting
故障排查
| Language | Issue | Solution |
|---|---|---|
| TypeScript | Bundle too large | Use standalone functions |
| Python | Async pagination blocking | Enable |
| Go | Interface not generated | Ensure struct is exported (capitalized) |
| Java | Gradle sync fails | Run |
| C# | Async deadlock | Use |
| PHP | PHP version error | Requires PHP 8.2+ |
| Ruby | Sorbet errors | Run |
| All | Retries not working | Ensure |
| All | Server ID not recognized | Add |
| All | Pagination | Add |
| 语言 | 问题 | 解决方案 |
|---|---|---|
| TypeScript | 打包体积过大 | 使用独立函数 |
| Python | 异步分页阻塞 | 启用 |
| Go | 接口未生成 | 确保结构体为公开(首字母大写) |
| Java | Gradle同步失败 | 执行 |
| C# | 异步死锁 | 使用 |
| PHP | PHP版本错误 | 升级至PHP 8.2+ |
| Ruby | Sorbet报错 | 执行 |
| 所有语言 | 重试策略不生效 | 确保在文档根节点或操作级别设置了 |
| 所有语言 | 服务器ID不被识别 | 为每个服务器条目添加 |
| 所有语言 | 分页 | 在列表操作中添加 |
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 consoleChanges to gen.yaml only take effect after regeneration.
修改gen.yaml配置后,请提示用户重新生成SDK:
配置完成。是否现在执行重新生成SDK?speakeasy run
若用户确认,请执行以下命令:
bash
speakeasy run --output consolegen.yaml的修改需在SDK重新生成后才会生效。
Related Skills
相关技能
- - Initial SDK generation
start-new-sdk-project - - Detailed hook implementation
customize-sdk-hooks - - Spec customization
manage-openapi-overlays
- - SDK初始生成
start-new-sdk-project - - 钩子详细实现
customize-sdk-hooks - - 规范自定义
manage-openapi-overlays