diff --git a/en/guides/workflow/node/code.mdx b/en/guides/workflow/node/code.mdx index 01866f9a..582c41b8 100644 --- a/en/guides/workflow/node/code.mdx +++ b/en/guides/workflow/node/code.mdx @@ -1,36 +1,29 @@ --- -title: "Code Execution" +title: "Code" --- -## Table of Contents - -- [Introduction](#introduction) -- [Usage Scenarios](#usage-scenarios) -- [Local Deployment](#local-deployment) -- [Security Policies](#security-policies) - ## Introduction -The code node supports running Python/NodeJS code to perform data transformations within a workflow. It can simplify your workflow and is suitable for scenarios such as arithmetic operations, JSON transformations, text processing, and more. +The Code node allows you to embed custom Python or JavaScript scripts into your workflow to manipulate variables in ways that built-in nodes cannot achieve. It can simplify your workflow and is suitable for scenarios such as arithmetic operations, JSON transformations, text processing, and more. -This node significantly enhances the flexibility for developers, allowing them to embed custom Python or JavaScript scripts within the workflow and manipulate variables in ways that preset nodes cannot achieve. Through configuration options, you can specify the required input and output variables and write the corresponding execution code: +To use variables from other nodes in a Code node, you must select them in the `Input Variables` field and then reference them in your code. -## Configuration +## What a Code Node Can Do -If you need to use variables from other nodes in the code node, you must define the variable names in the `input variables` and reference these variables. You can refer to [Variable References](/en/guides/workflow/variables). - -## Usage Scenarios - -Using the code node, you can perform the following common operations: +With the Code node, you can perform common operations such as structured data processing, mathematical calculations, and data concatenation. ### Structured Data Processing -In workflows, you often have to deal with unstructured data processing, such as parsing, extracting, and transforming JSON strings. A typical example is data processing from an HTTP node. In common API return structures, data may be nested within multiple layers of JSON objects, and you need to extract certain fields. The code node can help you perform these operations. Here is a simple example that extracts the `data.name` field from a JSON string returned by an HTTP node: +In workflows, you often have to deal with unstructured data processing, such as parsing, extracting, and transforming JSON strings. + +A typical example is data processing from an HTTP node: in common API return structures, data may be nested within multiple layers of JSON objects, and you need to extract certain fields. The Code node can help you perform these operations. + +Here is a simple example that extracts the `data.name` field from a JSON string returned by an HTTP node: ```python def main(http_response: str) -> dict: @@ -44,7 +37,9 @@ def main(http_response: str) -> dict: ### Mathematical Calculations -When you need to perform complex mathematical calculations in a workflow, you can also use the code node. For example, calculating a complex mathematical formula or performing some statistical analysis on data. Here is a simple example that calculates the variance of an array: +When you need to perform complex mathematical calculations in a workflow, you can also use the Code node. For example, calculating a complex mathematical formula or performing some statistical analysis on data. + +Here is a simple example that calculates the variance of an array: ```python def main(x: list) -> dict: @@ -56,7 +51,9 @@ def main(x: list) -> dict: ### Data Concatenation -Sometimes, you may need to concatenate multiple data sources, such as multiple knowledge retrievals, data searches, API calls, etc. The code node can help you integrate these data sources together. Here is a simple example that merges data from two knowledge bases: +Sometimes you may need to concatenate multiple data sources, such as multiple knowledge retrievals, data searches, API calls, etc. The Code node can help you integrate these data sources together. + +Here is a simple example that merges data from two knowledge bases: ```python def main(knowledge1: list, knowledge2: list) -> dict: @@ -68,43 +65,59 @@ def main(knowledge1: list, knowledge2: list) -> dict: ## Local Deployment -If you are a local deployment user, you need to start a sandbox service to ensure that malicious code is not executed. This service requires the use of Docker. You can find specific information about the sandbox service [here](https://github.com/langgenius/dify/tree/main/docker/docker-compose.middleware.yaml). You can also start the service directly via `docker-compose`: +If you are a local deployment user, you need to start a sandbox service to prevent the execution of malicious code. + +This sandbox service requires Docker. You can start it directly using `docker-compose`: ```bash docker-compose -f docker-compose.middleware.yaml up -d ``` + + If your system has Docker Compose V2 installed, use `docker compose` instead of `docker-compose`. You can check the version with `$ docker compose version`. + + For more information, see the [official Docker documentation](https://docs.docker.com/compose/#compose-v2-and-the-new-docker-compose-command). + + + + You can learn more about the sandbox service [here](https://github.com/langgenius/dify/tree/main/docker/docker-compose.middleware.yaml). + + ## Security Policies -Both Python and JavaScript execution environments are strictly isolated (sandboxed) to ensure security. This means that developers cannot use functions that consume large amounts of system resources or may pose security risks, such as direct file system access, making network requests, or executing operating system-level commands. These limitations ensure the safe execution of the code while avoiding excessive consumption of system resources. +Both Python and JavaScript execution environments are strictly isolated (sandboxed) to ensure security. This means that functions that consume large amounts of system resources or may pose security risks are prohibited, such as direct file system access, making network requests, or executing operating system-level commands. These limitations ensure the safe execution of the code while avoiding excessive consumption of system resources. ### Advanced Features -**Retry on Failure** +#### Retry on Failure -For some exceptions that occur in the node, it is usually sufficient to retry the node again. When the error retry function is enabled, the node will automatically retry according to the preset strategy when an error occurs. You can adjust the maximum number of retries and the interval between each retry to set the retry strategy. +Certain node errors are transient and can often be resolved by rerunning the node. By enabling the error retry feature, the node will automatically attempt to rerun according to a predefined policy upon failure. + +You can adjust the maximum number of retries and the interval between each retry to set the retry strategy. - The maximum number of retries is 10 - The maximum retry interval is 5000 ms ![](https://assets-docs.dify.ai/2024/12/9fdd5525a91dc925b79b89272893becf.png) -**Error Handling** +#### Error Handling -When processing information, code nodes may encounter code execution exceptions. Developers can follow these steps to configure fail branches, enabling contingency plans when nodes encounter exceptions, thus avoiding workflow interruptions. +When processing information, Code nodes may encounter code execution errors. You can follow these steps to configure error branches. This allows you to enable a contingency plan when an error occurs in the node, preventing the entire workflow from being interrupted. -1. Enable "Error Handling" in the code node -2. Select and configure an error handling strategy +1. Enable **Error Handling** for the Code node. +2. Select and configure an error handling strategy. -![Code Error handling](https://assets-docs.dify.ai/2024/12/58f392734ce44b22cd8c160faf28cd14.png) +![Code Error Handling](https://assets-docs.dify.ai/2024/12/58f392734ce44b22cd8c160faf28cd14.png) -For more information about exception handling approaches, please refer to [Error Handling](/en/guides/workflow/error-handling). + +For more information about error handling approaches, see [Error Handling](/en/guides/workflow/error-handling/README). + ### FAQ -**Why can't I save the code it in the code node?** +**Why can't I save the code it in the Code node?** -Please check if the code contains potentially dangerous behaviors. For example: +Check if the code contains potentially dangerous behaviors. For example: ```python def main() -> dict: @@ -115,52 +128,62 @@ def main() -> dict: This code snippet has the following issues: -- **Unauthorized file access:** The code attempts to read the "/etc/passwd" file, which is a critical system file in Unix/Linux systems that stores user account information. -- **Sensitive information disclosure:** The "/etc/passwd" file contains important information about system users, such as usernames, user IDs, group IDs, home directory paths, etc. Direct access could lead to information leakage. +- **Unauthorized file access**: The code attempts to read the `/etc/passwd` file, which is a critical system file in Unix/Linux systems that stores user account information. +- **Sensitive information disclosure**: The `/etc/passwd` file contains important information about system users, such as usernames, user IDs, group IDs, home directory paths, etc. Direct access could lead to information leakage. -Dangerous code will be automatically blocked by Cloudflare WAF. You can check if it's been blocked by looking at the "Network" tab in your browser's "Web Developer Tools". +Dangerous code will be automatically blocked by Cloudflare WAF. You can check if it's been blocked by looking at the **Network** tab in your browser's **Web Developer Tools**. ![Cloudflare WAF](https://assets-docs.dify.ai/2024/12/ad4dc065c4c567c150ab7fa7bfd123a3.png) -The **Code Fix** feature enables **automatic code correction** by leveraging the previous run’s `current_code` and `error_message` variables. +## Code Fix -# When a Code Node fails: +The **Code Fix** feature enables automatic code fix by leveraging the previous run’s `current_code` and `error_message` variables. + +When a Code node fails: - The system captures the code and error message. - These are passed into the prompt as context variables. - A new version of the code is generated for review and retry. -**Configuration:** +### Fix Prompt -1. **Write Repair Prompt**: +You can customize a prompt like: -In the prompt editor, use the variable insertion menu (`/` or `{`) to insert variables. You may customize a prompt like: +``` +Fix the following code based on this error message: -`Fix the following code based on this error message: Code: {{current_code}} Error: {{error_message}}` +Code: {{current_code}} + +Error: {{error_message}}` +``` + + +In the prompt editor, use the variable insertion menu (`/` or `{`) to insert variables. + ![Codefix PN](/images/codefix.PNG) -2. **Using Context Variables (if needed later in workflow)** +### Context Variables -To enable automatic code repair, reference the following **context variables** in your prompt: +To enable automatic code fix, reference the following context variables in your prompt: -- `{{current_code}}`: The code from the last run of this node. -- `{{error_message}}`: The error message if the last run failed. +- `current_code`: The code from the last run of this node. +- `error_message`: The error message from the last run if it failed; otherwise, empty. -You can also reference output variables from any predecessor nodes. +These variables are automatically available when the Code node runs, allowing the model to use prior run information for iterative correction. -These variables are automatically available when the Code Node is run and allow the model to use prior run information for iterative correction. + + - The `last_run` variable can be used to reference the input/output of the previous run. + - In addition to the variable above, you can reference the output variables of any preceding nodes as needed. + + +### Version Management + +Version management reduces manual copy-paste and allows iterative debugging directly within the workflow. -3. **Use Version Management**: 1. Each correction attempt is saved as a separate version (e.g., Version 1, Version 2). - 2. Users can **switch between versions** via the dropdown in the result display area. + 2. You can switch between versions via the dropdown in the result display area. -**Notes:** - -- `error_message` is empty if the last run succeeds. -- `last_run` can be used to reference previous input/output. - -This reduces manual copy-paste and allows iterative debugging directly within the workflow. --- diff --git a/ja-jp/guides/workflow/node/code.mdx b/ja-jp/guides/workflow/node/code.mdx index 9fccf368..9f8c6082 100644 --- a/ja-jp/guides/workflow/node/code.mdx +++ b/ja-jp/guides/workflow/node/code.mdx @@ -1,27 +1,28 @@ --- -title: コード +title: コード実行 version: '日本語' --- ## 紹介 -コードノードは、Python / NodeJSコードを実行してワークフロー内でデータ変換を行うことをサポートします。これにより、Arithmetic、JSON変換、テキスト処理などのシナリオでワークフローが簡素化されます。 +コードノードを使用すると、カスタムのPythonまたはJavascriptスクリプトをワークフローに埋め込み、組み込みノードでは実現できない方法で変数を操作できます。コードノードは、算術、JSON変換、テキスト処理などのシナリオに適しており、ワークフローを簡素化できます。 -このノードは開発者の柔軟性を大幅に向上させ、ワークフロー内にカスタムPythonまたはJavascriptスクリプトを埋め込んで、事前設定されたノードでは達成できない方法で変数を操作することができます。設定オプションを使用して、必要な入力変数と出力変数を指定し、対応する実行コードを記述できます。 +コードノードで他のノードの変数を使用するには、まず`入力変数`でその変数を選択してから、コード内で参照する必要があります。 -![](/ja-jp/img/904eeba8ee23e89c189497c5fd90f499.png) - -## 設定 - -他のノードの変数をコードノードで使用する必要がある場合は、`入力変数`で変数名を定義し、これらの変数を参照する必要があります。[変数参照](/ja-jp/guides/workflow/concepts)を参考にしてください。 + ## 使用シナリオ -コードノードを使用して、以下の一般的な操作を実行できます: +コードノードを使用することで、構造化データの処理、数学計算、データの連結などの操作を実現できます。 ### 構造化データ処理 -ワークフローでは、しばしば非構造化データの処理が必要です。例えば、JSON文字列の解析、抽出、変換などです。典型的な例として、HTTPノードのデータ処理があります。一般的なAPI応答構造では、データが多層のJSONオブジェクトにネストされていることがあり、特定のフィールドを抽出する必要があります。コードノードはこれらの操作を支援します。以下は、HTTPノードから返されたJSON文字列から`data.name`フィールドを抽出する簡単な例です: +ワークフローでは、JSON文字列の解析、抽出、変換など、非構造化データを頻繁に処理する必要があります。最も典型的な例は、HTTPノードのデータ処理です。一般的なAPIの戻り値の構造では、データが複数階層のJSONオブジェクトにネストされている可能性があり、その中から特定のフィールドを抽出する必要があります。コードノードは、これらの操作を完了するのに役立ちます。 + +例えば、以下のコードを使用して、HTTPノードから返されたJSON文字列から `data.name` フィールドを抽出できます。 ```python def main(http_response: str) -> dict: @@ -35,7 +36,9 @@ def main(http_response: str) -> dict: ### 数学計算 -ワークフロー内で複雑な数学計算を行う必要がある場合、コードノードを使用できます。例えば、複雑な数学公式の計算やデータの統計分析です。以下は、配列の平方差を計算する簡単な例です: +ワークフローで複雑な数学計算(複雑な数式の計算やデータの統計分析など)が必要な場合も、コードノードを使用できます。 + +例えば、次のコードを使用して、配列の二乗和を計算できます。 ```python def main(x: list) -> dict: @@ -47,7 +50,9 @@ def main(x: list) -> dict: ### データの結合 -時には、複数のデータソースを結合する必要がある場合があります。例えば、複数の知識検索、データサーチ、API呼び出しなどです。コードノードはこれらのデータソースを統合するのに役立ちます。以下は、2つのナレッジベースのデータを結合する簡単な例です: +複数のデータソース(複数のナレッジ検索、データ検索、API呼び出しなど)を連結する必要がある場合、コードノードを使用してこれらのデータソースを統合できます。 + +例えば、次のコードを使用して、2つのナレッジベースのデータを統合できます。 ```python def main(knowledge1: list, knowledge2: list) -> dict: @@ -59,23 +64,58 @@ def main(knowledge1: list, knowledge2: list) -> dict: ## ローカルデプロイ -ローカルデプロイのユーザーである場合、悪意のあるコードが実行されないようにするためのサンドボックスサービスを起動する必要があります。このサービスを起動するにはDockerサービスを使用します。サンドボックスサービスの詳細は[こちら](https://github.com/langgenius/dify/tree/main/docker/docker-compose.middleware.yaml)から確認できます。また、`docker-compose`を使用してサービスを直接起動することもできます: +ローカル環境にデプロイしているユーザーの場合、悪意のあるコードが実行されないようにサンドボックスサービス(Sandbox)を起動する必要があります。 + +サンドボックスサービスの起動にはDockerが必要です。docker-compose を使用して直接サービスを起動できます。 ```bash docker-compose -f docker-compose.middleware.yaml up -d ``` -> システムにDocker Compose V2がインストールされている場合は、`docker compose`を使用し;V1の場合、`docker-compose`を使用しください。`$docker compose version` でこれに該当するかどうかを確認してください。詳細は[こちら](https://docs.docker.com/compose/#compose-v2-and-the-new-docker-compose-command)をご覧ください。 + +お使いのシステムに Docker Compose V2 がインストールされている場合は、`docker-compose` の代わりに `docker compose` を使用してください。バージョン情報は `$ docker compose version` で確認できます。 +詳細については、[Docker 公式ドキュメント](https://docs.docker.com/compose/#compose-v2-and-the-new-docker-compose-command) をお読みください。 + + + +サンドボックスサービスの詳細については、[こちら](https://github.com/langgenius/dify/tree/main/docker/docker-compose.middleware.yaml) をご覧ください。 + ## セキュリティポリシー Python3とJavascriptのいずれであっても、その実行環境は安全性を確保するために厳密に隔離(サンドボックス化)されています。これにより、ファイルシステムへの直接アクセス、ネットワークリクエストの実行、OSレベルのコマンドの実行など、システムリソースを大量に消費する可能性がある機能を使用することはできません。これらの制限により、コードの安全な実行が保証され、システムリソースの過剰消費が防止されます。 +### 高度な機能 + +#### エラーリトライ + +ノードで発生する一部の例外的な状況については、通常、ノードを再実行することで解決できます。エラーリトライ機能を有効にすると、ノードはエラー発生時に事前に設定されたポリシーに従って自動的にリトライします。 + +最大リトライ回数と各リトライの間隔を調整できます。 + +- 最大リトライ回数は10回です +- 最大リトライ間隔は5000msです + +![](https://assets-docs.dify.ai/2024/12/9fdd5525a91dc925b79b89272893becf.png) + +#### 例外処理 + +コードノードが情報を処理する際に、コードの実行例外が発生する可能性があります。以下の手順に従って例外分岐を設定することで、ノードで例外が発生した際に代替案を有効にし、プロセス全体の中断を避けることができます。 + +1. コードノードで **例外処理** を有効にします。 +2. 例外処理のプランを選択し、設定します。 + +![Code Error Handling](https://assets-docs.dify.ai/2024/12/58f392734ce44b22cd8c160faf28cd14.png) + + +例外処理の方法についてさらに詳しく知りたい場合は、[例外処理](/ja-jp/guides/workflow/error-handling/README) をお読みください。 + + ### よくある質問 **コード ノードにコードを入力した後にコードを保存できないのはなぜですか?** -コードに危険な動作がないか確認してください。例えば: +コードに危険な動作が含まれていないか確認してください。例: ```python def main() -> dict: @@ -86,55 +126,63 @@ def main() -> dict: このコードには次の問題が含まれています。 -* **不正なファイル アクセス:** コードは、ユーザー アカウント情報を保存する Unix/Linux システムの重要なシステム ファイルである`/etc/passwd`ファイルを読み取ろうとしました。 -* **機密情報の漏洩:** `/etc/passwd`ファイルには、ユーザー名、ユーザー ID、グループ ID、ホーム ディレクトリのパスなど、システム ユーザーの重要な情報が含まれています。直接アクセスすると情報が漏洩する可能性があります。 +- **不正なファイル アクセス**: コードは、ユーザー アカウント情報を保存する Unix/Linux システムの重要なシステム ファイルである`/etc/passwd`ファイルを読み取ろうとしました。 +- **機密情報の漏洩**: `/etc/passwd`ファイルには、ユーザー名、ユーザー ID、グループ ID、ホーム ディレクトリのパスなど、システム ユーザーの重要な情報が含まれています。直接アクセスすると情報が漏洩する可能性があります。 危険なコードはCloudflare WAFによって自動的にブロックされます。ブロックされているかどうかは、「Webデバッグツール」の「ネットワーク」から確認できます。 -![](/ja-jp/img/7d29e700be8e5b6dfb91ff1263624368.png) +![Cloudflare WAF](https://assets-docs.dify.ai/2024/12/ad4dc065c4c567c150ab7fa7bfd123a3.png) -## **コード修正** +## コード修正 -この機能は、前回の実行時の`current_code`と`error_message`変数を活用し、**自動できにコードの修正**を実現できます。 +前回実行時の `current_code` と `error_message` 変数を利用して、自動でコードを修正することができます。 -コードノードが失敗した時: +コードノードの実行が失敗した場合: -- システムはコードとエラーメッセージを取得 -- それらをコンテキスト変数としてプロンプトに渡します -- コードの新しいバージョンが生成され、レビューや再試行に提供されます。 +- システムはコードとエラーメッセージをキャプチャします。 +- これらの情報はコンテキスト変数としてプロンプトに渡されます。 +- システムはレビューと再試行のために新しいバージョンのコードを生成します。 -**設定** +### 修正プロンプト -1. **修正プロンプトの作成**: +次のように、修正用のプロンプトをカスタマイズできます。 -プロンプトエディタでは、変数挿入メニュー(`/` または `{`)を使用して変数を挿入可能です。例えば、次のようなプロンプトをカスタマイズできます。 +``` +以下のエラーメッセージに基づいてコードを修正してください: -`以下のエラーメッセージに基づいてコードを修正してください: -Code: {{current_code}} -Error: {{error_message}}` +コード: +{{current_code}} -![](/images/codefix.PNG) +エラー: +{{error_message}} +``` -2. **コンテキスト変数の使用(ワークフローで必要な場合)** -自動コード修正を有効にするためには、プロンプト内で以下のコンテキスト変数を参照してください: + +プロンプトエディタで、変数挿入メニュー(`/`または`{`)を使用して変数を挿入します。 + -`{{current_code}}`: このノードの前回実行からのコード。 -`{{error_message}}`: 最後の実行が失敗した場合のエラーメッセージ。 +![Codefix](/images/codefix.PNG) -また、前のノードからの出力変数も参照可能です。 +### コンテキスト変数 -これらの変数は、コードノードが実行された際に自動的に利用可能になり、モデルが前回の実行データを用いて反復的な修正を行えます。 +自動コード修正を有効にするには、プロンプトで以下のコンテキスト変数を参照してください。 -3. **バージョン管理の利用**: - 1. 各修正試行は個別のバージョン(例:バージョン1、バージョン2)として保存されます。 - 2. ユーザーは結果表示エリアのドロップダウンからバージョンを切り替えられます。 +- `current_code`:このノードで前回実行されたコード。 +- `error_message`:前回の実行が失敗した場合はエラーメッセージ、成功した場合は空になります。 -**注意点:** +コードノードが実行されると、これらの変数は自動的に利用可能になり、大規模言語モデルが前回の実行情報を使用してコードを修正できるようになります。 -- `error_message`は、最後の実行が成功した場合は空になります。 -- `last_run`は前回の入力/出力を参照するために使用できます。 + + - `last_run` 変数は、前回の入力/出力を参照するために使用できます。 + - 上記の変数に加えて、必要に応じて任意の前段ノードの出力変数を参照することもできます。 + -これにより、手動でのコピー&ペーストが減少し、ワークフロー内で直接反復的なデバッグが可能になります。 +### バージョン管理 + +バージョン管理により、手動でのコピー&ペースト作業が減り、ワークフロー内で直接コードを繰り返しデバッグできるようになります。 + +- 修正が試みられるたびに、個別のバージョンとして保存されます(例:バージョン1、バージョン2)。 +- 結果表示エリアのドロップダウンメニューから、異なるバージョンを切り替えることができます。 {/* Contributing Section diff --git a/zh-hans/guides/workflow/node/code.mdx b/zh-hans/guides/workflow/node/code.mdx index bfb54743..83096d2f 100644 --- a/zh-hans/guides/workflow/node/code.mdx +++ b/zh-hans/guides/workflow/node/code.mdx @@ -2,32 +2,26 @@ title: "代码执行" --- -## 目录 - -- [介绍](#介绍) -- [使用场景](#使用场景) -- [本地部署](#本地部署) -- [安全策略](#安全策略) - ## 介绍 -代码节点支持运行 Python / NodeJS 代码以在工作流程中执行数据转换。它可以简化你的工作流程,适用于Arithmetic、JSON transform、文本处理等情景。 +通过代码节点,你可以在工作流中嵌入自定义的 Python 或 Javascript 脚本,以内置节点无法实现的方式对变量进行操作。代码节点能够简化你的工作流,适用于 Arithmetic、JSON transform、文本处理等场景。 -该节点极大地增强了开发人员的灵活性,使他们能够在工作流程中嵌入自定义的 Python 或 Javascript 脚本,并以预设节点无法达到的方式操作变量。通过配置选项,你可以指明所需的输入和输出变量,并撰写相应的执行代码: +若要在代码节点中使用其他节点的变量,需在`输入变量`中选择变量,然后在代码中进行引用。 -![](https://assets-docs.dify.ai/dify-enterprise-mintlify/zh_CN/guides/workflow/node/9969aa1bc1912aebe366f5d8f5dde296.png) - -## 配置 - -如果你需要在代码节点中使用其他节点的变量,你需要在`输入变量`中定义变量名,并引用这些变量,可以参考[变量引用](../key-concepts#变量)。 + ## 使用场景 -使用代码节点,你可以完成以下常见的操作: +通过代码节点,你可以实现结构化数据处理、数学计算和拼接数据等操作。 ### 结构化数据处理 -在工作流中,经常要面对非结构化的数据处理,如 JSON 字符串的解析、提取、转换等。最典型的例子就是 HTTP 节点的数据处理,在常见的 API 返回结构中,数据可能会被嵌套在多层 JSON 对象中,而我们需要提取其中的某些字段。代码节点可以帮助你完成这些操作,下面是一个简单的例子,它从 HTTP 节点返回的 JSON 字符串中提取了`data.name`字段: +在工作流中,经常需要处理非结构化数据,如 JSON 字符串的解析、提取、转换等。最典型的例子是 HTTP 节点的数据处理:在常见的 API 返回结构中,数据可能会被嵌套在多层 JSON 对象中,而我们需要提取其中的某些字段。代码节点可以帮助你完成这些操作。 + +例如,你可以通过以下代码从 HTTP 节点返回的 JSON 字符串中提取 `data.name` 字段: ```python def main(http_response: str) -> dict: @@ -41,7 +35,9 @@ def main(http_response: str) -> dict: ### 数学计算 -当工作流中需要进行一些复杂的数学计算时,也可以使用代码节点。例如,计算一个复杂的数学公式,或者对数据进行一些统计分析。下面是一个简单的例子,它计算了一个数组的平方差: +当工作流中需要进行复杂的数学计算时(如计算复杂的数学公式或对数据进行统计分析),也可以使用代码节点。 + +例如,你可以通过以下代码计算一个数组的平方差: ```python def main(x: list) -> dict: @@ -53,7 +49,9 @@ def main(x: list) -> dict: ### 拼接数据 -有时,也许你需要拼接多个数据源,如多个知识检索、数据搜索、API调用等,代码节点可以帮助你将这些数据源整合在一起。下面是一个简单的例子,它将两个知识库的数据合并在一起: +当你需要拼接多个数据源时(如多个知识检索、数据搜索、API 调用等),代码节点可以帮助你将这些数据源整合在一起。 + +例如,你可以通过以下代码合并两个知识库的数据: ```python def main(knowledge1: list, knowledge2: list) -> dict: @@ -65,39 +63,53 @@ def main(knowledge1: list, knowledge2: list) -> dict: ## 本地部署 -如果你是本地部署的用户,你需要启动一个沙盒服务,它会确保恶意代码不会被执行,同时,启动该服务需要使用Docker服务,你可以在[这里](https://github.com/langgenius/dify/tree/main/docker/docker-compose.middleware.yaml)找到Sandbox服务的具体信息,你也可以直接通过`docker-compose`启动服务: +如果你是本地部署的用户,则需要启动沙盒服务(Sandbox),以确保恶意代码不会被执行。 + +启动沙盒服务需要使用 Docker。你可以直接通过 `docker-compose` 启动该服务: ```bash docker-compose -f docker-compose.middleware.yaml up -d ``` -> 如果你的系统安装了 Docker Compose V2 而不是 V1,请使用 `docker compose` 而不是 `docker-compose`。通过`$ docker compose version`检查这是否为情况。在[这里](https://docs.docker.com/compose/#compose-v2-and-the-new-docker-compose-command)阅读更多信息。 + + 如果你的系统安装的是 Docker Compose V2,请使用 `docker compose` 而非 `docker-compose`。你可以通过 `$ docker compose version` 确认版本信息。 + + 了解更多信息,请阅读 [Docker 官方文档](https://docs.docker.com/compose/#compose-v2-and-the-new-docker-compose-command)。 + + + + 你可以在 [这里](https://github.com/langgenius/dify/tree/main/docker/docker-compose.middleware.yaml) 了解沙盒服务的更多信息。 + ## 安全策略 -无论是 Python3 还是 Javascript 代码执行器,它们的执行环境都被严格隔离(沙箱化),以确保安全性。这意味着开发者不能使用那些消耗大量系统资源或可能引发安全问题的功能,例如直接访问文件系统、进行网络请求或执行操作系统级别的命令。这些限制保证了代码的安全执行,同时避免了对系统资源的过度消耗。 +无论是 Python3 还是 Javascript 代码执行器,它们的执行环境都被严格隔离(沙箱化)以确保安全性。这意味着你无法使用那些消耗大量系统资源或可能引发安全问题的功能,例如直接访问文件系统、进行网络请求或执行操作系统级别的命令。这些限制保证了代码的安全执行,同时避免了对系统资源的过度消耗。 ### 高级功能 -**错误重试** +#### 错误重试 -针对节点发生的部分异常情况,通常情况下再次重试运行节点即可解决。开启错误重试功能后,节点将在发生错误的时候按照预设策略进行自动重试。你可以调整最大重试次数和每次重试间隔以设置重试策略。 +针对节点发生的部分异常情况,通常情况下再次重试运行节点即可解决。开启错误重试功能后,节点将在发生错误时按照预设策略进行自动重试。 + +你可以调整最大重试次数和每次重试间隔。 - 最大重试次数为 10 次 - 最大重试间隔时间为 5000 ms ![](https://assets-docs.dify.ai/2024/12/9fdd5525a91dc925b79b89272893becf.png) -**异常处理** +#### 异常处理 -代码节点处理信息时有可能会遇到代码执行异常的情况。应用开发者可以参考以下步骤配置异常分支,在节点出现异常时启用应对方案,而避免中断整个流程。 +代码节点处理信息时可能会遇到代码执行异常的情况。你可以参考以下步骤配置异常分支,以在节点出现异常时启用应对方案,从而避免中断整个流程。 -1. 在代码节点启用 “异常处理” -2. 选择异常处理方案并进行配置 +1. 在代码节点启用 **异常处理**。 +2. 选择异常处理方案并进行配置。 ![Code Error handling](https://assets-docs.dify.ai/2024/12/58f392734ce44b22cd8c160faf28cd14.png) -需了解更多应对异常的处理办法,请参考[异常处理](../error-handling/readme)。 + + 了解更多异常处理方法,请阅读 [异常处理](../error-handling/readme)。 + ### 常见问题 @@ -114,16 +126,16 @@ def main() -> dict: 这段代码包含以下问题: -- **未经授权的文件访问:** 代码试图读取 "/etc/passwd" 文件,这是 Unix/Linux 系统中存储用户账户信息的关键系统文件。 -- **敏感信息泄露:** "/etc/passwd" 文件包含系统用户的重要信息,如用户名、用户 ID、组 ID、home 目录路径等。直接访问可能会导致信息泄露。 +- **未经授权的文件访问**:代码试图读取 `/etc/passwd` 文件,这是 Unix/Linux 系统中存储用户账户信息的关键系统文件。 +- **敏感信息泄露**:`/etc/passwd` 文件包含系统用户的重要信息,如用户名、用户 ID、组 ID、home 目录路径等,直接访问可能会导致信息泄露。 -危险代码将会被 Cloudflare WAF 自动拦截,你可以通过 “网页调试工具” 中的 “网络” 查看是否被拦截。 +危险代码将会被 Cloudflare WAF 自动拦截。你可以通过浏览器的 **网页调试工具** 中的 **网络** 查看代码是否被拦截。 -![Cloudflare WAF](https://assets-docs.dify.ai/dify-enterprise-mintlify/zh_CN/guides/workflow/node/d1fe121991c51b26b66d42a55b18fb57.png) +![Cloudflare WAF](https://assets-docs.dify.ai/2024/12/ad4dc065c4c567c150ab7fa7bfd123a3.png) ## 代码修复 -此功能通过利用上次运行`current_codeerror_message`变量实现自动代码纠正。 +你可以通过利用上次运行的 `current_code` 和 `error_message` 变量实现自动代码修复。 当代码节点运行失败时: @@ -131,44 +143,46 @@ def main() -> dict: - 这些信息会作为上下文变量传递到提示中。 - 系统会生成一个新版本的代码供审查和重试。 -**配置:** +### 修复提示 -1. **编写修复提示:** +你可以自定义修复提示,例如: -你可以自定义一个提示,例如: +``` +根据以下错误信息修复代码: -在提示编辑器中,使用变量插入菜单(`/`或`{`)插入变量。 - -`根据以下错误信息修复代码: 代码: {{current_code}} + 错误: -{{error_message}}` +{{error_message}} +``` -![Codefix PN](/images/codefix.PNG) + +在提示编辑器中,使用变量插入菜单(`/`或`{`)插入变量。 + -2. **使用上下文变量(如果在工作流程后续需要)** +![Codefix](/images/codefix.PNG) -要启用自动代码修复,请在提示中引用以下上下文变量: +### 上下文变量 -- `{{current_code}}`:此节点上次运行的代码。 -- `{{error_message}}`:如果上次运行失败,则为错误消息。 +若要启用自动代码修复,请在提示中引用以下上下文变量: -你还可以引用任何前置节点的输出变量。 +- `current_code`:此节点上次运行的代码。 +- `error_message`:若上次运行失败,则为错误消息;若上次运行成功,则为空。 -当代码节点运行时,这些变量会自动可用,并允许模型使用先前的运行信息进行迭代修正。 +当代码节点运行时,这些变量会自动可用,允许大模型使用先前的运行信息修复代码。 -3. **版本管理** + + - `last_run` 变量可用于引用先前的输入/输出。 + - 除了以上变量外,你还可以按需引用任何前置节点的输出变量。 + -- 每次修正尝试都会保存为一个单独的版本(例如,版本1、版本2)。 -- 用户可以通过结果显示区域的下拉菜单在不同版本间切换。 +### 版本管理 -**注意事项:** +版本管理可减少手动复制粘贴操作,让你能够在工作流中直接对代码进行迭代调试。 -- 如果上次运行成功,error_message为空。 -- last_run可用于引用先前的输入/输出。 - -这减少了手动复制粘贴操作,并允许在工作流程中直接进行迭代调试。 +- 每次修复尝试都会保存为一个单独的版本(例如,版本 1、版本 2)。 +- 你可以通过结果显示区域的下拉菜单在不同版本间切换。 ---