Skip to main content
本文档由 AI 自动翻译。如有任何不准确之处,请参考 英文原版
插件可以反向调用 Dify 内部的 LLM 能力,涵盖平台内的所有模型类型和功能,例如 TTS 和 Rerank。若不熟悉反向调用的基础知识,请先阅读 反向调用 Dify 服务 每次调用模型都需传入一个 ModelConfig 类型的参数。它的结构定义在 通用规范定义 中,并会因模型类型而略有差异。 例如,LLM 类型的模型还需要 completion_paramsmode 参数。你可手动构建该结构,也可使用 model-selector 类型的参数或配置。

调用 LLM

入口点

    self.session.model.llm

接口

    def invoke(
        self,
        model_config: LLMModelConfig,
        prompt_messages: list[PromptMessage],
        tools: list[PromptMessageTool] | None = None,
        stop: list[str] | None = None,
        stream: bool = True,
    ) -> Generator[LLMResultChunk, None, None] | LLMResult:
        pass
如果你调用的模型不具备 tool_call 能力,这里传入的 tools 不会生效。

使用示例

以下示例在 Tool 中调用 OpenAI 的 gpt-4o-mini 模型:
from collections.abc import Generator
from typing import Any

from dify_plugin import Tool
from dify_plugin.entities.model.llm import LLMModelConfig
from dify_plugin.entities.tool import ToolInvokeMessage
from dify_plugin.entities.model.message import SystemPromptMessage, UserPromptMessage

class LLMTool(Tool):
    def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage]:
        response = self.session.model.llm.invoke(
            model_config=LLMModelConfig(
                provider='openai',
                model='gpt-4o-mini',
                mode='chat',
                completion_params={}
            ),
            prompt_messages=[
                SystemPromptMessage(
                    content='you are a helpful assistant'
                ),
                UserPromptMessage(
                    content=tool_parameters.get('query')
                )
            ],
            stream=True
        )

        for chunk in response:
            if chunk.delta.message:
                assert isinstance(chunk.delta.message.content, str)
                yield self.create_text_message(text=chunk.delta.message.content)
注意,代码会从 tool_parameters 中取出 query 参数。

最佳实践

避免手动构建 LLMModelConfig,而应让用户在 UI 中选择想要的模型:在工具的参数列表中添加一个 model 参数即可。
identity:
  name: llm
  author: Dify
  label:
    en_US: LLM
    zh_Hans: LLM
    pt_BR: LLM
description:
  human:
    en_US: A tool for invoking a large language model
    zh_Hans: 用于调用大型语言模型的工具
    pt_BR: A tool for invoking a large language model
  llm: A tool for invoking a large language model
parameters:
  - name: prompt
    type: string
    required: true
    label:
      en_US: Prompt string
      zh_Hans: 提示字符串
      pt_BR: Prompt string
    human_description:
      en_US: used for searching
      zh_Hans: 用于搜索网页内容
      pt_BR: used for searching
    llm_description: key words for searching
    form: llm
  - name: model
    type: model-selector
    scope: llm
    required: true
    label:
      en_US: Model
      zh_Hans: 使用的模型
      pt_BR: Model
    human_description:
      en_US: Model
      zh_Hans: 使用的模型
      pt_BR: Model
    llm_description: which Model to invoke
    form: form
extra:
  python:
    source: tools/llm.py
由于 model 参数的 scopellm,用户只能选择 llm 类型的模型。此时,前面的使用示例可改写为:
from collections.abc import Generator
from typing import Any

from dify_plugin import Tool
from dify_plugin.entities.model.llm import LLMModelConfig
from dify_plugin.entities.tool import ToolInvokeMessage
from dify_plugin.entities.model.message import SystemPromptMessage, UserPromptMessage

class LLMTool(Tool):
    def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage]:
        response = self.session.model.llm.invoke(
            model_config=tool_parameters.get('model'),
            prompt_messages=[
                SystemPromptMessage(
                    content='you are a helpful assistant'
                ),
                UserPromptMessage(
                    content=tool_parameters.get('prompt')
                )
            ],
            stream=True
        )

        for chunk in response:
            if chunk.delta.message:
                assert isinstance(chunk.delta.message.content, str)
                yield self.create_text_message(text=chunk.delta.message.content)

调用 Summary

此接口使用当前工作空间内的系统模型来总结一段文本。

入口点

    self.session.model.summary

接口

    def invoke(
        self, text: str, instruction: str,
    ) -> str:
  • text:要总结的文本。
  • instruction:额外的指令,让你可控制摘要的风格。

调用 TextEmbedding

入口点

    self.session.model.text_embedding

接口

    def invoke(
        self,
        model_config: TextEmbeddingModelConfig,
        texts: list[str],
        input_type: EmbeddingInputType = EmbeddingInputType.QUERY,
    ) -> TextEmbeddingResult:
        pass

调用 Rerank

入口点

    self.session.model.rerank

接口

    def invoke(
        self, model_config: RerankModelConfig, docs: list[str], query: str
    ) -> RerankResult:
        pass

调用 TTS

入口点

    self.session.model.tts

接口

    def invoke(
        self, model_config: TTSModelConfig, content_text: str
    ) -> Generator[bytes, None, None]:
        pass
tts 接口返回的 bytes 流是 mp3 音频字节流,每次迭代返回一个完整的音频片段。若需更深入的处理,请选择合适的音频库。

调用 Speech2Text

入口点

    self.session.model.speech2text

接口

    def invoke(
        self, model_config: Speech2TextModelConfig, file: IO[bytes]
    ) -> str:
        pass
其中 file 是以 mp3 格式编码的音频文件。

调用 Moderation

入口点

    self.session.model.moderation

接口

    def invoke(self, model_config: ModerationModelConfig, text: str) -> bool:
        pass
返回值为 true 表示 text 中包含敏感内容。

相关资源

Last modified on June 25, 2026