添加自定义代码

以 Markdown 格式查看

本页面介绍如何向您的 Python SDK 添加自定义逻辑、方法和依赖项。

添加自定义逻辑

开始添加自定义代码:

1

创建新文件并添加您的自定义逻辑

src/<package>/helper.py
1def my_helper() -> None:
2 print("Hello World!")
2

将您的文件添加到 .fernignore

.fernignore
1# 指定不应由 Fern 修改的文件
2
3src/<package>/helper.py
3

使用辅助函数

Now your users can consume the helper function by importing it from the SDK.

1from package.helper import my_helper
2
3my_helper()

添加自定义 SDK 方法

Fern also allows you to add custom methods to the SDK itself (e.g. client.my_method() ) by inheriting the Fern generated client and then extending it.

在 ElevenLabs 的 Python SDK 中查看使用此流程的示例。

1

更新 generators.yml 配置

将您的 Fern 生成的客户端命名为 BaseClient,以反映 该客户端将被扩展。配置生成器以在名为 base_client.py 的文件中输出 客户端。

generators.yml
1- name: fernapi/fern-python-sdk
2 version: "..."
3 config:
4 client:
5 class_name: BaseClient # 您将扩展的生成客户端的名称
6 filename: base_client.py # 生成客户端将存放的文件名称
7 exported_class_name: YourClient # 您将创建的扩展生成客户端的类名称
8 exported_filename: client.py
2

生成 SDK

通过运行 fern generate 触发 SDK 生成:

$fern generate --group sdk
3

导入并扩展生成的客户端

首先,从 .base_client.py 导入 Fern 生成的基础客户端并扩展它们以创建您的自定义客户端。然后,添加您想要的任何方法。

src/<package>/client.py
1 from .base_client import BaseClient // 导入生成的客户端
2
3 class YourClient(BaseClient): // 扩展生成的客户端
4 def my_helper(self) -> None:
5 print("Hello World!")
6 def my_helper(self) -> None:
7 print("Hello World")

在 ElevenLabs 查看示例 client.py

4

更新 .fernignore

client.py 添加到 .fernignore

.fernignore
1+ src/<package>/client.py

在 ElevenLabs 查看示例 .fernignore

5

使用方法

Now your users can consume the helper function by importing it from the SDK.

1client.my_helper()

添加自定义依赖项

专业版和企业版功能

此功能仅适用于专业版和企业版计划。如需开始使用,请联系 support@buildwithfern.com

要添加您的自定义代码所需的包,请更新您的 generators.yml

generators.yml
1- name: fernapi/fern-python-sdk
2 version: "..."
3 config:
4 extra_dependencies:
5 numpy: '1.2.0'
6 extra_dev_dependencies:
7 requests_mock: '1.12.1'