> ## Documentation index
> Fetch the complete documentation index at: https://dify-docs.docs7.io/llms.txt
> Ask it with GET https://dify-docs.docs7.io/ask?q=<keywords or question>. Short keywords rank best.
> Use these to discover all available pages before exploring further.

# 工具返回

> 工具插件如何返回消息（文本、链接、图片、文件、JSON）、创建标准变量和流式变量，以及定义输出模式以供工作流引用

> 本文档由 AI 自动翻译。如有任何不准确之处，请参考 [英文原版](/en/develop-plugin/features-and-specs/plugin-types/tool)。

## 概述

工具以消息和变量的形式返回结果。本页介绍消息接口、变量创建和输出模式定义。

<CardGroup cols={2}>
  <Card title="消息类型" icon="comment-dots" href="#消息返回">
    返回不同类型的消息，如文本、链接、图片和 JSON
  </Card>
  <Card title="变量" icon="code-branch" href="#变量">
    创建和操作变量以实现工作流集成
  </Card>
  <Card title="输出模式" icon="diagram-project" href="#自定义输出变量">
    定义自定义输出变量以供工作流引用
  </Card>
</CardGroup>

## 数据结构

### 消息返回

Dify 支持多种消息类型，包括文本、链接、图片、文件 blob 和 JSON，每种类型都通过专用接口返回。

默认情况下，工作流中工具的输出包含三个固定变量：`files`、`text` 和 `json`。以下方法用于填充这些变量。

<Tip>
虽然你可使用 `create_image_message` 等方法返回图片，但工具也支持自定义输出变量，从而更便于在工作流中引用特定数据。
</Tip>

### 消息类型

<CodeGroup>
```python Image URL
def create_image_message(self, image: str) -> ToolInvokeMessage:
    """
    Return an image URL message
    
    Dify will automatically download the image from the provided URL
    and display it to the user.
    
    Args:
        image: URL to an image file
        
    Returns:
        ToolInvokeMessage: Message object for the tool response
    """
    pass
```

```python Link
def create_link_message(self, link: str) -> ToolInvokeMessage:
    """
    Return a clickable link message
    
    Args:
        link: URL to be displayed as a clickable link
        
    Returns:
        ToolInvokeMessage: Message object for the tool response
    """
    pass
```

```python Text
def create_text_message(self, text: str) -> ToolInvokeMessage:
    """
    Return a text message
    
    Args:
        text: Text content to be displayed
        
    Returns:
        ToolInvokeMessage: Message object for the tool response
    """
    pass
```

```python File
def create_blob_message(self, blob: bytes, meta: dict = None) -> ToolInvokeMessage:
    """
    Return a file blob message
    
    For returning raw file data such as images, audio, video, 
    or documents (PPT, Word, Excel, etc.)
    
    Args:
        blob: Raw file data in bytes
        meta: File metadata dictionary. Include 'mime_type' to specify 
              the file type, otherwise 'octet/stream' will be used
              
    Returns:
        ToolInvokeMessage: Message object for the tool response
    """
    pass
```

```python JSON
def create_json_message(self, json: dict) -> ToolInvokeMessage:
    """
    Return a formatted JSON message
    
    Useful for data transmission between workflow nodes.
    In agent mode, most LLMs can read and understand JSON data.
    
    Args:
        json: Python dictionary to be serialized as JSON
        
    Returns:
        ToolInvokeMessage: Message object for the tool response
    """
    pass
```
</CodeGroup>

<Accordion title="参数">
  <ParamField path="image" type="string" required>
    将被下载并显示的图片 URL
  </ParamField>
  
  <ParamField path="link" type="string" required>
    将显示为可点击链接的 URL
  </ParamField>
  
  <ParamField path="text" type="string" required>
    要显示的文本内容
  </ParamField>
  
  <ParamField path="blob" type="bytes" required>
    字节格式的原始文件数据
  </ParamField>
  
  <ParamField path="meta" type="dict">
    文件元数据，包括：

    - `mime_type`：文件的 MIME 类型（例如 `image/png`）
    - 与文件相关的其他元数据
  </ParamField>
  
  <ParamField path="json" type="dict" required>
    要序列化为 JSON 的 Python 字典
  </ParamField>
</Accordion>

<Tip>
处理文件 blob 时，请始终在 `meta` 字典中指定 `mime_type`，以确保文件得到正确处理。例如：`{"mime_type": "image/png"}`。
</Tip>

### 变量

<CodeGroup>
```python Standard Variable
from typing import Any

def create_variable_message(self, variable_name: str, variable_value: Any) -> ToolInvokeMessage:
    """
    Create a named variable for workflow integration
    
    For non-streaming output variables. If multiple instances with the 
    same name are created, the latest one overrides previous values.
    
    Args:
        variable_name: Name of the variable to create
        variable_value: Value of the variable (any Python data type)
        
    Returns:
        ToolInvokeMessage: Message object for the tool response
    """
    pass
```

```python Streaming Variable
def create_stream_variable_message(
    self, variable_name: str, variable_value: str
) -> ToolInvokeMessage:
    """
    Create a streaming variable with typewriter effect
    
    When referenced in an answer node in a chatflow application,
    the text will be output with a typewriter effect.
    
    Args:
        variable_name: Name of the variable to create
        variable_value: String value to stream (only strings supported)
        
    Returns:
        ToolInvokeMessage: Message object for the tool response
    """
    pass
```
</CodeGroup>

<Accordion title="参数">
  <ParamField path="variable_name" type="string" required>
    要创建或更新的变量名称
  </ParamField>
  
  <ParamField path="variable_value" type="Any/string" required>
    要分配给变量的值：

    - 标准变量：任何 Python 数据类型
    - 流式变量：仅支持字符串数据
  </ParamField>
</Accordion>

<Warning>
`create_stream_variable_message` 目前仅支持字符串数据。复杂数据类型无法通过打字机效果进行流式输出。
</Warning>

## 自定义输出变量

要在 Workflow 应用中引用工具的输出变量，需在工具清单中使用 [JSON Schema](https://json-schema.org/) 声明工具可能输出的变量。

### 定义输出模式

<CodeGroup>
```yaml Tool Manifest with Output Schema
identity:
  author: example_author
  name: example_tool
  label:
    en_US: Example Tool
    zh_Hans: 示例工具
    ja_JP: ツール例
    pt_BR: Ferramenta de exemplo
description:
  human:
    en_US: A simple tool that returns a name
    zh_Hans: 返回名称的简单工具
    ja_JP: 名前を返す簡単なツール
    pt_BR: Uma ferramenta simples que retorna um nome
  llm: A simple tool that returns a name variable
output_schema:
  type: object
  properties:
    name:
      type: string
      description: "The name returned by the tool"
    age:
      type: integer
      description: "The age returned by the tool"
    profile:
      type: object
      properties:
        interests:
          type: array
          items:
            type: string
        location:
          type: string
```
</CodeGroup>

<Accordion title="模式结构">
  <ParamField path="output_schema" type="object" required>
    定义工具输出模式的根对象
  </ParamField>
  
  <ParamField path="type" type="string" required>
    工具输出模式必须为 `object`
  </ParamField>
  
  <ParamField path="properties" type="object" required>
    所有可能输出变量的字典
  </ParamField>
  
  <ParamField path="properties.[variable_name]" type="object">
    每个输出变量的定义，包括其类型和描述
  </ParamField>
</Accordion>

<Warning>
仅定义输出模式还不够：实现代码仍须使用 `create_variable_message()` 返回每个变量。否则，工作流将收到该变量的 `None` 值。
</Warning>

### 实现示例

<CodeGroup>
```python Basic Variable Example
def run(self, inputs):
    # Process inputs and generate a name
    generated_name = "Alice"
    
    # Return the name as a variable that matches the output_schema
    return self.create_variable_message("name", generated_name)
```

```python Complex Structure Example
def run(self, inputs):
    # Generate complex structured data
    user_data = {
        "name": "Bob",
        "age": 30,
        "profile": {
            "interests": ["coding", "reading", "hiking"],
            "location": "San Francisco"
        }
    }
    
    # Return individual variables
    self.create_variable_message("name", user_data["name"])
    self.create_variable_message("age", user_data["age"])
    self.create_variable_message("profile", user_data["profile"])
    
    # Also return a text message for display
    return self.create_text_message(f"User {user_data['name']} processed successfully")
```
</CodeGroup>

<Tip>
对于复杂的工作流，您可以定义多个输出变量并全部返回。这为工作流设计者使用您的工具时提供了更大的灵活性。
</Tip>

## 示例

### 完整的工具实现

<CodeGroup>
```python Weather Forecast Tool
import requests
from typing import Any

class WeatherForecastTool:
    def run(self, inputs: dict) -> Any:
        # Get location from inputs
        location = inputs.get("location", "London")
        
        try:
            # Call weather API (example only)
            weather_data = self._get_weather_data(location)
            
            # Create variables for workflow use
            self.create_variable_message("temperature", weather_data["temperature"])
            self.create_variable_message("conditions", weather_data["conditions"])
            self.create_variable_message("forecast", weather_data["forecast"])
            
            # Create a JSON message for data transmission
            self.create_json_message(weather_data)
            
            # Create an image message for the weather map
            self.create_image_message(weather_data["map_url"])
            
            # Return a formatted text response
            return self.create_text_message(
                f"Weather in {location}: {weather_data['temperature']}°C, {weather_data['conditions']}. "
                f"Forecast: {weather_data['forecast']}"
            )
            
        except Exception as e:
            # Handle errors gracefully
            return self.create_text_message(f"Error retrieving weather data: {str(e)}")
    
    def _get_weather_data(self, location: str) -> dict:
        # Mock implementation - in a real tool, this would call a weather API
        return {
            "location": location,
            "temperature": 22,
            "conditions": "Partly Cloudy",
            "forecast": "Sunny with occasional showers tomorrow",
            "map_url": "https://example.com/weather-map.png"
        }
```
</CodeGroup>

<Tip>
设计工具时，请同时考虑直接输出（用户看到的内容）和变量输出（其他工作流节点可以使用的内容）。这种分离为工具的使用方式提供了灵活性。
</Tip>
