Skip to main content

Overview#

Most plugin tools and endpoints operate in a stateless, single-round interaction model:

  1. Receive a request
  2. Process data
  3. Return a response
  4. End the interaction

However, many real-world applications require maintaining state across multiple interactions. This is where persistent storage becomes essential.

Info

Persistent storage lets plugins keep data within the same workspace across interactions, enabling stateful applications and memory features.

Dify currently provides a key-value (KV) storage system for plugins; more flexible and powerful storage interfaces are planned based on developer needs.

Access Storage#

All storage operations are performed through the storage object available in your plugin’s session:

Storage Operations#

Store Data#

Store data with the set method:

Warning

The value must be in bytes format. This provides flexibility to store various types of data, including files.

Example: Storing Different Data Types#

Retrieve Data#

Retrieve stored data with the get method:

Example: Retrieving and Converting Data#

Delete Data#

Delete stored data with the delete method:

Best Practices#

Use Descriptive Keys

Create a consistent naming scheme for your keys to avoid conflicts and make your code more maintainable.

Handle Missing Keys

Always check if data exists before processing it, as the key might not be found.

Serialize Complex Data

Convert complex objects to JSON or other serialized formats before storing.

Implement Error Handling

Wrap storage operations in try/except blocks to handle potential errors gracefully.

Common Use Cases#

  • User preferences: Store user settings and preferences between sessions.
  • Conversation history: Maintain context from previous conversations.
  • API tokens: Store authentication tokens securely.
  • Cached data: Store frequently accessed data to reduce API calls.
  • File storage: Store user-uploaded files or generated content.