> ## Documentation Index
> Fetch the complete documentation index at: https://dify-6c0370d8-add-new-agent.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# モデルの逆呼び出し

> このドキュメントでは、プラグインがDifyプラットフォーム内でモデルサービスを逆呼び出しする方法について詳しく説明します。LLM、Summary、TextEmbedding、Rerank、TTS、Speech2Text、Moderationモデルの逆呼び出しの具体的な方法を網羅しています。各モデルの呼び出しには、エントリーポイント、インターフェースパラメータの説明、実用的なコード例、モデル呼び出しのベストプラクティス推奨事項が含まれています。

<Note> ⚠️ このドキュメントはAIによって自動翻訳されています。不正確な部分がある場合は、[英語版](/en/develop-plugin/features-and-specs/advanced-development/reverse-invocation-model)を参照してください。</Note>

モデルの逆呼び出しとは、プラグインがDifyの内部LLM機能を呼び出す能力を指し、TTS、Rerankなど、プラットフォーム内のすべてのモデルタイプと機能を含みます。逆呼び出しの基本概念に慣れていない場合は、まず[Difyサービスの逆呼び出し](/ja/develop-plugin/features-and-specs/advanced-development/reverse-invocation)をお読みください。

ただし、モデルを呼び出すには`ModelConfig`型のパラメータを渡す必要があることに注意してください。その構造は[一般仕様定義](/ja/develop-plugin/features-and-specs/plugin-types/general-specifications)で参照でき、この構造はモデルの種類によってわずかに異なります。

例えば、`LLM`型のモデルでは、`completion_params`と`mode`パラメータも含める必要があります。この構造を手動で構築するか、`model-selector`型のパラメータまたは設定を使用できます。

### LLMの呼び出し

#### **エントリーポイント**

```python theme={null}
    self.session.model.llm
```

#### **エンドポイント**

```python theme={null}
    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`モデルを呼び出したい場合は、以下のサンプルコードを参照してください：

```python theme={null}
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`パラメータを追加してツールのパラメータリストを変更できます：

```yaml theme={null}
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`の`scope`が`llm`として指定されていることに注意してください。これにより、ユーザーは`llm`型のパラメータのみを選択できます。したがって、前の使用例のコードは以下のように変更できます：

```python theme={null}
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('query') # Assuming 'query' is still needed, otherwise use 'prompt' from parameters
                )
            ],
            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の呼び出し

このエンドポイントにリクエストして、テキストを要約できます。現在のワークスペース内のシステムモデルを使用してテキストを要約します。

**エントリーポイント**

```python theme={null}
    self.session.model.summary
```

**エンドポイント**

* `text`は要約するテキストです。
* `instruction`は追加したい追加の指示で、テキストをスタイル的に要約できます。

```python theme={null}
    def invoke(
        self, text: str, instruction: str,
    ) -> str:
```

### TextEmbeddingの呼び出し

**エントリーポイント**

```python theme={null}
    self.session.model.text_embedding
```

**エンドポイント**

```python theme={null}
    def invoke(
        self, model_config: TextEmbeddingResult, texts: list[str]
    ) -> TextEmbeddingResult:
        pass
```

### Rerankの呼び出し

**エントリーポイント**

```python theme={null}
    self.session.model.rerank
```

**エンドポイント**

```python theme={null}
    def invoke(
        self, model_config: RerankModelConfig, docs: list[str], query: str
    ) -> RerankResult:
        pass
```

### TTSの呼び出し

**エントリーポイント**

```python theme={null}
    self.session.model.tts
```

**エンドポイント**

```python theme={null}
    def invoke(
        self, model_config: TTSModelConfig, content_text: str
    ) -> Generator[bytes, None, None]:
        pass
```

`tts`エンドポイントが返す`bytes`ストリームは`mp3`オーディオバイトストリームであることに注意してください。各イテレーションは完全なオーディオセグメントを返します。より詳細な処理タスクを実行したい場合は、適切なライブラリを選択してください。

### Speech2Textの呼び出し

**エントリーポイント**

```python theme={null}
    self.session.model.speech2text
```

**エンドポイント**

```python theme={null}
    def invoke(
        self, model_config: Speech2TextModelConfig, file: IO[bytes]
    ) -> str:
        pass
```

ここで`file`は`mp3`形式でエンコードされたオーディオファイルです。

### Moderationの呼び出し

**エントリーポイント**

```python theme={null}
    self.session.model.moderation
```

**エンドポイント**

```python theme={null}
    def invoke(self, model_config: ModerationModelConfig, text: str) -> bool:
        pass
```

このエンドポイントが`true`を返す場合、`text`に機密コンテンツが含まれていることを示します。

## 関連リソース

* [Difyサービスの逆呼び出し](/ja/develop-plugin/features-and-specs/advanced-development/reverse-invocation) - 逆呼び出しの基本概念を理解する
* [アプリの逆呼び出し](/ja/develop-plugin/features-and-specs/advanced-development/reverse-invocation-app) - プラットフォーム内でアプリを呼び出す方法を学ぶ
* [ツールの逆呼び出し](/ja/develop-plugin/features-and-specs/advanced-development/reverse-invocation-tool) - 他のプラグインを呼び出す方法を学ぶ
* [モデルプラグイン開発ガイド](/ja/develop-plugin/dev-guides-and-walkthroughs/creating-new-model-provider) - カスタムモデルプラグインの開発方法を学ぶ
* [モデル設計ルール](/ja/develop-plugin/features-and-specs/plugin-types/model-designing-rules) - モデルプラグインの設計原則を理解する

***

[Edit this page](https://github.com/langgenius/dify-docs/edit/main/en/develop-plugin/features-and-specs/advanced-development/reverse-invocation-model.mdx) | [Report an issue](https://github.com/langgenius/dify-docs/issues/new?template=docs.yml)
