Skip to main content
⚠️ このドキュメントはAIによって自動翻訳されています。不正確な部分がある場合は、英語版を参照してください。

構築するもの

このガイドを終えると、以下の機能を持つDifyプラグインが完成します:
  • Flomoメモ取りAPIへの接続
  • AIとの会話から直接Flomoにメモを保存する機能
  • 認証とエラー状態の適切な処理
  • Dify Marketplaceでの配布準備完了

所要時間

10分

前提条件

基本的なPythonの知識とFlomoアカウント

ステップ1:Dify CLIのインストールとプロジェクト作成

1

Dify CLIのインストール

  • Mac
  • Linux
brew tap langgenius/dify
brew install dify
インストールを確認:
dify version
2

プラグインプロジェクトの初期化

以下のコマンドで新しいプラグインプロジェクトを作成します:
dify plugin init
プロンプトに従ってプラグインをセットアップします:
  • 名前を「flomo」にする
  • プラグインタイプとして「tool」を選択
  • その他の必須フィールドを入力
3

プロジェクトに移動

cd flomo
これにより、必要なすべてのファイルを含むプラグインの基本構造が作成されます。

ステップ2:プラグインマニフェストの定義

manifest.yamlファイルはプラグインのメタデータ、権限、機能を定義します。
manifest.yamlファイルを作成します:
version: 0.0.4
type: plugin
author: yourname
label:
  en_US: Flomo
  zh_Hans: Flomo 浮墨笔记
created_at: "2023-10-01T00:00:00Z"
icon: icon.png

resource:
  memory: 67108864  # 64MB
  permission:
    storage:
      enabled: false

plugins:
  tools:
    - flomo.yaml
  
meta:
  version: 0.0.1
  arch:
    - amd64
    - arm64
  runner:
    language: python
    version: 3.12
    entrypoint: main

ステップ3:ツール定義の作成

ツールインターフェースを定義するflomo.yamlファイルを作成します:
identity:
  author: yourname
  name: flomo
  label:
    en_US: Flomo Note
    zh_Hans: Flomo 浮墨笔记
description:
  human:
    en_US: Add notes to your Flomo account directly from Dify.
    zh_Hans: 直接从Dify添加笔记到您的Flomo账户。
  llm: >
    A tool that allows users to save notes to Flomo. Use this tool when users want to save important information from the conversation. The tool accepts a 'content' parameter that contains the text to be saved as a note.
credential_schema:
  api_url:
    type: string
    required: true
    label:
      en_US: API URL
      zh_Hans: API URL
    human_description:
      en_US: Flomo API URL from your Flomo account settings.
      zh_Hans: 从您的Flomo账户设置中获取的API URL。
tool_schema:
  content:
    type: string
    required: true
    label:
      en_US: Note Content
      zh_Hans: 笔记内容
    human_description:
      en_US: Content to save as a note in Flomo.
      zh_Hans: 要保存为Flomo笔记的内容。

ステップ4:コアユーティリティ関数の実装

API連携用のユーティリティモジュールをutils/flomo_utils.pyに作成します:
import requests

def send_flomo_note(api_url: str, content: str) -> None:
    """
    Send a note to Flomo via the API URL. Raises requests.RequestException on network errors,
    and ValueError on invalid status codes or input.
    """
    api_url = api_url.strip()
    if not api_url:
        raise ValueError("API URL is required and cannot be empty.")
    if not api_url.startswith('https://flomoapp.com/iwh/'):
        raise ValueError(
            "API URL should be in the format: https://flomoapp.com/iwh/{token}/{secret}/"
        )
    if not content:
        raise ValueError("Content cannot be empty.")
    
    headers = {'Content-Type': 'application/json'}
    response = requests.post(api_url, json={"content": content}, headers=headers, timeout=10)
    
    if response.status_code != 200:
        raise ValueError(f"API URL is not valid. Received status code: {response.status_code}")

ステップ5:ツールプロバイダーの実装

ツールプロバイダーは認証情報の検証を処理します。provider/flomo.pyを作成します:
from typing import Any
from dify_plugin import ToolProvider
from dify_plugin.errors.tool import ToolProviderCredentialValidationError
import requests
from utils.flomo_utils import send_flomo_note

class FlomoProvider(ToolProvider):
    def _validate_credentials(self, credentials: dict[str, Any]) -> None:
        try:
            api_url = credentials.get('api_url', '').strip()
            # Use utility for validation and sending test note
            send_flomo_note(api_url, "Hello, #flomo https://flomoapp.com")
        except ValueError as e:
            raise ToolProviderCredentialValidationError(str(e))
        except requests.RequestException as e:
            raise ToolProviderCredentialValidationError(f"Connection error: {str(e)}")

ステップ6:ツールの実装

Toolクラスはユーザーがプラグインを呼び出したときに実際のAPI呼び出しを処理します。tools/flomo.pyを作成します:
from collections.abc import Generator
from typing import Any
from dify_plugin import Tool
from dify_plugin.entities.tool import ToolInvokeMessage
import requests
from utils.flomo_utils import send_flomo_note

class FlomoTool(Tool):
    def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage]:
        content = tool_parameters.get("content", "")
        api_url = self.runtime.credentials.get("api_url", "")
        
        try:
            send_flomo_note(api_url, content)
        except ValueError as e:
            yield self.create_text_message(str(e))
            return
        except requests.RequestException as e:
            yield self.create_text_message(f"Connection error: {str(e)}")
            return
            
        # Return success message and structured data
        yield self.create_text_message(
            "Note created successfully! Your content has been sent to Flomo."
        )
        yield self.create_json_message({
            "status": "success",
            "content": content,
        })
常に例外を適切に処理し、ユーザーフレンドリーなエラーメッセージを返すようにしてください。あなたのプラグインはDifyエコシステムにおけるブランドを代表するものであることを忘れないでください。

ステップ7:プラグインのテスト

1

デバッグ環境のセットアップ

サンプル環境ファイルをコピーします:
cp .env.example .env
.envファイルをDify環境の詳細で編集します:
INSTALL_METHOD=remote
REMOTE_INSTALL_HOST=debug-plugin.dify.dev
REMOTE_INSTALL_PORT=5003
REMOTE_INSTALL_KEY=your_debug_key
デバッグキーとホストはDifyダッシュボードで確認できます:右上の「プラグイン」アイコンをクリックし、デバッグアイコンをクリックします。ポップアップウィンドウで「APIキー」と「ホストアドレス」をコピーしてください。
2

依存関係のインストールと実行

pip install -r requirements.txt
python -m main
プラグインがデバッグモードでDifyインスタンスに接続されます。
3

機能のテスト

Difyインスタンスでプラグインに移動し、デバッグ中のプラグイン(「debugging」とマークされています)を見つけます。 Flomo APIの認証情報を追加し、メモの送信をテストします。

ステップ9:パッケージ化と配布

プラグインを共有する準備ができたら:
dify plugin package ./
これにより、Dify Marketplaceにアップロードできるplugin.difypkgファイルが作成されます。

FAQとトラブルシューティング

.envファイルが正しく設定されていること、正しいデバッグキーを使用していることを確認してください。
Flomo API URLの形式を再確認してください。形式は次のようになっている必要があります:https://flomoapp.com/iwh/{token}/{secret}/
必要なすべてのファイルが存在し、manifest.yamlの構造が有効であることを確認してください。

まとめ

外部APIサービスと連携する機能的なDifyプラグインを構築しました!この同じパターンは、データベースや検索エンジンから生産性ツールやカスタムAPIまで、何千ものサービスとの統合に使用できます。

ドキュメント

機能、セットアップ、使用例を説明するREADME.mdを英語(en_US)で作成してください

ローカライズ

他の言語用にreadme/README_zh_Hans.mdのような追加のREADMEファイルを作成してください

Edit this page | Report an issue