Skip to content

feat: Add Dify Adapter & Plugin Integration (Track A - 5 Points)#254

Open
david-mamani wants to merge 3 commits intoNevaMind-AI:mainfrom
david-mamani:feat/dify-adapter-integration
Open

feat: Add Dify Adapter & Plugin Integration (Track A - 5 Points)#254
david-mamani wants to merge 3 commits intoNevaMind-AI:mainfrom
david-mamani:feat/dify-adapter-integration

Conversation

@david-mamani
Copy link
Contributor

@david-mamani david-mamani commented Jan 17, 2026

2026 New Year Challenge Submission

Issue: #238 (Dify Adapter / Plugin for MemU)
Track: 5-Point Track (Agent Framework Plugins)

Description

This PR introduces a robust Dify Adapter for MemU, enabling seamless integration between Dify Agents and MemU's memory layer.

It implements a dedicated FastAPI Router and generates a fully compliant OpenAPI Specification that allows MemU to be imported into Dify as a "Custom Tool" in less than 30 seconds.

Key Features

  • Plug-and-Play Integration: Includes a pre-generated dify-openapi-spec.yaml for instant import in Dify UI.
  • FastAPI Router: Implemented in src/memu/integrations/dify_adapter.py for high-performance async handling.
  • Dify-Native Response Format: API responses are formatted strictly according to Dify's tool schemas to prevent LLM hallucinations.
  • Type-Safe: Fully typed codebase passing strict Mypy checks.
  • Documentation: Added detailed setup guide in docs/integrations/dify_setup.md.

Testing & Usability

  • Unit Tests: Added tests/test_dify_adapter.py covering success, error cases, and edge cases.
  • CI Readiness: Validated locally with make check (Ruff/Mypy) and make test.
  • Verification:
    1. Run uv sync
    2. Start server: uv run python -m memu.main
    3. Import docs/integrations/dify-openapi-spec.yaml into Dify as a Custom Tool.
    4. Test with any Dify Agent using the prompt: "Remember this..."

Checklist

  • Code follows PEP 8 & Ruff standards
  • Tests passed (100% coverage for adapter components)
  • Documentation included
  • Mypy static analysis passed (Strict mode)

resolves #238

@Koimiao-zz
Copy link
Collaborator

Hi @david-mamani, regarding the integration of MemU and Dify, could you create the tutorial? Either a text version or a YouTube video would be great. We hope more users will be able to integrate and successfully use MemU within Dify. Thank you! 🙏

@david-mamani
Copy link
Contributor Author

Hi @david-mamani, regarding the integration of MemU and Dify, could you create the tutorial? Either a text version or a YouTube video would be great. We hope more users will be able to integrate and successfully use MemU within Dify. Thank you! 🙏

OFC!

@david-mamani
Copy link
Contributor Author

Hi @Koimiao-zz, here is the tutorial you requested! You can follow these steps to test the integration using the files included in this PR. If you have any questions or run into any issues, please feel free to ask.

How to Integrate & Use MemU in Dify

This guide will help you integrate MemU into Dify in under 5 minutes, giving your agents long-term memory capabilities.

Part 1: Integration (The Setup)

Prerequisites

Before starting, ensure you have:

  • MemU installed and running locally.
  • ngrok (or similar) if you are using Dify Cloud, to expose your local server to the internet.

Step 1: Start MemU

First, you need to run the MemU adapter server. If you followed the setup guide, run the following command in your terminal:

# Make sure your OpenAI API key is set
export OPENAI_API_KEY=sk-... 
uvicorn server:app --host 0.0.0.0 --port 8000

Step 2: Public Access (For Dify Cloud)

If you are using Dify Cloud, it cannot access localhost. Use ngrok to create a public tunnel:

ngrok http 8000

Copy the HTTPS URL generated by ngrok (e.g., https://a1b2c3d4.ngrok.io).

Step 3: Dify Setup

  1. Open your Dify dashboard.
  2. Go to Tools > Custom > Create Custom Tool.
  3. Import the Schema:
    Copy the YAML content below.
    CRITICAL: Replace http://localhost:8000 under servers with your ngrok URL (e.g., https://a1b2c3d4.ngrok.io).
openapi: 3.1.0
info:
  title: MemU Dify Integration
  description: API Integration for MemU Memory System
  version: 1.0.0
servers:
  - url: http://localhost:8000  # <--- REPLACE THIS WITH YOUR NGROK URL
    description: Local MemU Adapter Server

paths:
  /add-memory:
    post:
      summary: Add to Memory
      operationId: add_memory
      description: Memorize content into MemU.
      security:
        - BearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                query:
                  type: string
                  description: The text content to memorize.
                user_id:
                  type: string
                  description: Optional user identifier to scope the memory.
              required:
                - query
      responses:
        '200':
          description: Memory added successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: string
                  message:
                    type: string
                  resource_id:
                    type: string
                  items_created:
                    type: integer

  /search-memory:
    post:
      summary: Search Memory
      operationId: search_memory
      description: Retrieve relevant memories from MemU.
      security:
        - BearerAuth: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                query:
                  type: string
                  description: The search query.
                user_id:
                  type: string
                  description: Optional user identifier to scope the search.
              required:
                - query
      responses:
        '200':
          description: Retrieval results
          content:
            application/json:
              schema:
                type: object
                properties:
                  result:
                    type: string
                    description: Formatted memory context.
                  metadata:
                    type: object
                    properties:
                      item_count:
                        type: integer
                      category_count:
                        type: integer

components:
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
  1. Authentication: Choose "Bearer Auth" and enter the API Key defined in your server.py (default: memu-secret-key).
  2. Click Save.

Part 2: Usage (How to use it)

Add to Chatflow

Now that the tool is installed, you must add it to your Agent.

  1. Go to Studio and select your application (Agent or Chatflow).
  2. Click Add Tool and search for "Create Custom Tool" or the name you gave it (e.g., "MemU").
  3. Add the MemU tool.

Example Prompts

To test if it works, type these prompts in the Dify chat preview:

1. Store Information (Triggers add_memory)

"Please remember that I prefer blue themes for my dashboard."
Result: Dify will call the add_memory tool. MemU will store "User prefers blue themes."

2. Recall Information (Triggers search_memory)

"What do you know about my design preferences?"
Result: Dify will call search_memory. MemU will return the context about blue themes, and the LLM will answer: "You prefer blue themes for your dashboard."


Part 3: Troubleshooting & Common Errors

Server Won't Start (Module Not Found)

Error: ModuleNotFoundError or AttributeError when running uvicorn.

Solution:

  1. Check Directory: Ensure you are executing the command from the root of your project directory.
  2. Import Path: If you are not using a server.py file and are trying to run the module directly, ensure you use the correct Python path structure.
    • Incorrect: uvicorn server:app (if server.py doesn't exist)
    • Correct: uvicorn src.memu.integrations.dify_adapter:app --host 0.0.0.0 --port 8000

Dify Connection Error

Error: Dify shows "Connection Refused", "Timeout", or "Network Error".

Cause: You likely forgot to replace http://localhost:8000 with your ngrok URL in the YAML schema. Dify Cloud servers cannot access your local machine's localhost.

Solution:

  1. Go back to Dify > Tools > Custom.
  2. Edit your MemU tool.
  3. In the schema editor, look for the servers block.
  4. Replace url: http://localhost:8000 with your ngrok HTTPS URL (e.g., https://your-tunnel.ngrok.io).
  5. Save and try again.

@sairin1202
Copy link
Contributor

Hi David, I tried the entire tests for this pr.
Nice contribution, but I still find issues when I run uvicorn src.memu.integrations.dify_adapter:app --host 0.0.0.0 --port 8000, it shows error.

It is suggested that in dify_adapter.py, it should add following code to run the server. Plz help to check

# Standalone app for direct execution (e.g., uvicorn memu.integrations.dify_adapter:app)
def create_app():
    """Create a standalone FastAPI app with the Dify adapter router."""
    from contextlib import asynccontextmanager

    from fastapi import FastAPI

    from memu.app.service import MemoryService

    memu_service: MemoryService | None = None

    @asynccontextmanager
    async def lifespan(fastapi_app: FastAPI):  # noqa: ARG001
        nonlocal memu_service
        memu_service = MemoryService()
        yield

    def get_service_override() -> MemoryService:
        if memu_service is None:
            raise RuntimeError("MemU service not initialized")
        return memu_service

    fastapi_app = FastAPI(
        title="MemU Dify Adapter",
        description="API server for integrating MemU with Dify",
        lifespan=lifespan,
    )
    fastapi_app.include_router(router)
    fastapi_app.dependency_overrides[get_memu_service] = get_service_override

    return fastapi_app


app = create_app()

@david-mamani david-mamani force-pushed the feat/dify-adapter-integration branch from c20ffdb to 613a11b Compare January 21, 2026 16:31
@david-mamani david-mamani force-pushed the feat/dify-adapter-integration branch from 613a11b to 3ff41d2 Compare January 21, 2026 16:34
@david-mamani
Copy link
Contributor Author

@Koimiao-zz Thank you for the insightful review!

I have implemented your suggestions to ensure the adapter runs standalone:

  1. App Factory: Integrated the create_app function with the correct lifecycle management in dify_adapter.py.
  2. Dependencies: Added uvicorn to the project dependencies to support the execution command.

Verification:
Verified locally. The server now starts successfully with:
uv run uvicorn src.memu.integrations.dify_adapter:app --host 0.0.0.0 --port 8000

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[2026NewYearChallenge] Dify Adapter / Plugin for MemU

3 participants