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.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
Available Error Types
Available Error Types
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.Parameters
Parameters
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
completionmodels: Include a singleUserPromptMessage - For
chatmodels: IncludeSystemPromptMessage,UserPromptMessage,AssistantPromptMessage,ToolPromptMessageas 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
Return Values
Return Values
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.
__base.text_embedding_model.TextEmbeddingModel base class:
1. Core Embedding Method
Parameters
Parameters
Return Value
Return Value
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
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.
__base.rerank_model.RerankModel base class:
Parameters
Parameters
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
Return Value
Return Value
object
required
A structured response containing:
- model: The model used for reranking
- docs: List of RerankDocument objects with index, text, and score
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.
__base.speech2text_model.Speech2TextModel base class:
Parameters
Parameters
Return Value
Return Value
string
required
The transcribed text from the audio file
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.
__base.text2speech_model.Text2SpeechModel base class:
Parameters
Parameters
Return Value
Return Value
Moderation Implementation
Moderation models analyze content for potentially harmful, inappropriate, or unsafe material, helping maintain platform safety and content policies.
__base.moderation_model.ModerationModel base class:
Parameters
Parameters
Return Value
Return Value
boolean
required
Boolean indicating content safety:
- False: The content is safe
- True: The content contains harmful material
Entities
PromptMessageRole
Message rolePromptMessageContentType
Message content type, divided into plain text and images.PromptMessageContent
Message content base class, used only for parameter declaration, cannot be initialized.TextPromptMessageContent and ImagePromptMessageContent separately.
TextPromptMessageContent
content list.
ImagePromptMessageContent
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 forfew-shots or chat history input.
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.content passes in the tool execution result.
PromptMessageTool
LLMResult
LLMResultChunkDelta
Delta entity within each iteration in streaming responseLLMResultChunk
Iteration entity in streaming responseLLMUsage
TextEmbeddingResult
EmbeddingUsage
RerankResult
RerankDocument
Related Resources
- Model Design Rules - Understand the standards for model configuration
- Model Plugin Introduction - Quickly understand the basic concepts of model plugins
- Quickly Integrate a New Model - Learn how to add new models to existing providers
- Create a New Model Provider - Learn how to develop brand new model providers
Edit this page | Report an issue