Skip to main content

Introduction

This document details the interfaces and data structures required to implement Dify model plugins. It serves as a technical reference for developers integrating AI models with the Dify platform.
Before diving into this API reference, we recommend first reading the Model Design Rules and Model Plugin Introduction for conceptual understanding.

Provider Implementation

Learn how to implement model provider classes for different AI service providers

Model Types

Implementation details for the five supported model types: LLM, Embedding, Rerank, Speech2Text, and Text2Speech

Data Structures

Comprehensive reference for all data structures used in the model API

Error Handling

Guidelines for proper error mapping and exception handling

Model Provider

Every model provider must inherit from the __base.model_provider.ModelProvider base class and implement the credential validation interface.

Provider Credential Validation

dict
Credential information as defined in the provider’s YAML configuration under provider_credential_schema. Typically includes fields like api_key, organization_id, etc.
If validation fails, your implementation must raise a CredentialsValidateFailedError exception. This ensures proper error handling in the Dify UI.
For predefined model providers, you should implement a thorough validation method that verifies the credentials work with your API. For custom model providers (where each model has its own credentials), a simplified implementation is sufficient.

Models

Dify supports five distinct model types, each requiring implementation of specific interfaces. However, all model types share some common requirements.

Common Interfaces

Every model implementation, regardless of type, must implement these two fundamental methods:

1. Model Credential Validation

string
required
The specific model identifier to validate (e.g., “gpt-4”, “claude-3-opus”)
dict
required
Credential information as defined in the provider’s configuration

2. Error Mapping

class
Network connection failures, timeouts
class
Service provider is down or unavailable
class
Rate limits or quota limits reached
class
Authentication or permission issues
class
Invalid parameters or requests
You can alternatively raise these standardized error types directly in your code instead of relying on the error mapping. This approach gives you more control over error messages.

LLM Implementation

To implement a Large Language Model provider, inherit from the __base.large_language_model.LargeLanguageModel base class and implement these methods:

1. Model Invocation

This core method handles both streaming and non-streaming API calls to language models.
string
required
Model identifier (e.g., “gpt-4”, “claude-3”)
dict
required
Authentication credentials for the API
list[PromptMessage]
required
Message list in Dify’s standardized format:
  • For completion models: Include a single UserPromptMessage
  • For chat models: Include SystemPromptMessage, UserPromptMessage, AssistantPromptMessage, ToolPromptMessage as needed
dict
required
Model-specific parameters (temperature, top_p, etc.) as defined in the model’s YAML configuration
list[PromptMessageTool]
Tool definitions for function calling capabilities
list[string]
Stop sequences that will halt model generation when encountered
boolean
default:true
Whether to return a streaming response
string
User identifier for API monitoring
Generator[LLMResultChunk, None, None]
A generator yielding chunks of the response as they become available
LLMResult
A complete response object with the full generated text
We recommend implementing separate helper methods for streaming and non-streaming calls to keep your code organized and maintainable.

2. Token Counting

If the model doesn’t provide a tokenizer, you can use the base class’s _get_num_tokens_by_gpt2(text) method for a reasonable approximation.

3. Custom Model Schema (Optional)

This method is only necessary for providers that support custom models. It allows custom models to inherit parameter rules from base models.

TextEmbedding Implementation

Text embedding models convert text into high-dimensional vectors that capture semantic meaning, which is useful for retrieval, similarity search, and classification.
To implement a Text Embedding provider, inherit from the __base.text_embedding_model.TextEmbeddingModel base class:

1. Core Embedding Method

string
required
Embedding model identifier
dict
required
Authentication credentials for the embedding service
list[string]
required
List of text inputs to embed
string
User identifier for API monitoring
object
required
A structured response containing:
  • model: The model used for embedding
  • embeddings: List of embedding vectors corresponding to input texts
  • usage: Metadata about token usage and costs

2. Token Counting Method

For embedding models, accurate token counting is important for cost estimation, but not critical for functionality. The _get_num_tokens_by_gpt2 method provides a reasonable approximation for most models.

Rerank Implementation

Reranking models help improve search quality by re-ordering a set of candidate documents based on their relevance to a query, typically after an initial retrieval phase.
To implement a Reranking provider, inherit from the __base.rerank_model.RerankModel base class:
string
required
Reranking model identifier
dict
required
Authentication credentials for the API
string
required
The search query text
list[string]
required
List of document texts to be reranked
float
Optional minimum score threshold for filtering results
int
Optional limit on number of results to return
string
User identifier for API monitoring
object
required
A structured response containing:
  • model: The model used for reranking
  • docs: List of RerankDocument objects with index, text, and score
Reranking can be computationally expensive, especially with large document sets. Implement batching for large document collections to avoid timeouts or excessive resource consumption.

Speech2Text Implementation

Speech-to-text models convert spoken language from audio files into written text, enabling applications like transcription services, voice commands, and accessibility features.
To implement a Speech-to-Text provider, inherit from the __base.speech2text_model.Speech2TextModel base class:
string
required
Speech-to-text model identifier
dict
required
Authentication credentials for the API
IO[bytes]
required
Binary file object containing the audio to transcribe
string
User identifier for API monitoring
string
required
The transcribed text from the audio file
Audio format detection is important for proper handling of different file types. Consider implementing a helper method to detect the format from the file header as shown in the example.
Some speech-to-text APIs have file size limitations. Consider implementing chunking for large audio files if necessary.

Text2Speech Implementation

Text-to-speech models convert written text into natural-sounding speech, enabling applications such as voice assistants, screen readers, and audio content generation.
To implement a Text-to-Speech provider, inherit from the __base.text2speech_model.Text2SpeechModel base class:
string
required
Text-to-speech model identifier
dict
required
Authentication credentials for the API
string
required
Text content to be converted to speech
boolean
required
Whether to return streaming audio or complete file
string
User identifier for API monitoring
Generator[bytes, None, None]
A generator yielding audio chunks as they become available
bytes
Complete audio data as bytes
Most text-to-speech APIs require you to specify a voice along with the model. Consider implementing a mapping between Dify’s model identifiers and the provider’s voice options.
Long text inputs may need to be chunked for better speech synthesis quality. Consider implementing text preprocessing to handle punctuation, numbers, and special characters properly.

Moderation Implementation

Moderation models analyze content for potentially harmful, inappropriate, or unsafe material, helping maintain platform safety and content policies.
To implement a Moderation provider, inherit from the __base.moderation_model.ModerationModel base class:
string
required
Moderation model identifier
dict
required
Authentication credentials for the API
string
required
Text content to be analyzed
string
User identifier for API monitoring
boolean
required
Boolean indicating content safety:
  • False: The content is safe
  • True: The content contains harmful material
Moderation is often used as a safety mechanism. Consider the implications of false negatives (letting harmful content through) versus false positives (blocking safe content) when implementing your solution.
Many moderation APIs provide detailed category scores rather than just a binary result. Consider extending this implementation to return more detailed information about specific categories of harmful content if your application needs it.

Entities

PromptMessageRole

Message role

PromptMessageContentType

Message content type, divided into plain text and images.

PromptMessageContent

Message content base class, used only for parameter declaration, cannot be initialized.
Currently supports two types: text and images, and can support text and multiple images simultaneously. You need to initialize TextPromptMessageContent and ImagePromptMessageContent separately.

TextPromptMessageContent

When passing in text and images, text needs to be constructed as this entity as part of the content list.

ImagePromptMessageContent

When passing in text and images, images need to be constructed as this entity as part of the content list. data can be a url or an image base64 encoded string.

PromptMessage

Base class for all Role message bodies, used only for parameter declaration, cannot be initialized.

UserPromptMessage

UserMessage message body, represents user messages.

AssistantPromptMessage

Represents model response messages, typically used for few-shots or chat history input.
Here tool_calls is the list of tool call returned by the model after passing in tools to the model.

SystemPromptMessage

Represents system messages, typically used to set system instructions for the model.

ToolPromptMessage

Represents tool messages, used to pass results to the model for next-step planning after a tool has been executed.
The base class’s content passes in the tool execution result.

PromptMessageTool

LLMResult

LLMResultChunkDelta

Delta entity within each iteration in streaming response

LLMResultChunk

Iteration entity in streaming response

LLMUsage

TextEmbeddingResult

EmbeddingUsage

RerankResult

RerankDocument


Edit this page | Report an issue