Introduction
This page is the technical reference for the interfaces and data structures you implement when integrating AI models with Dify through a model plugin.Before diving into this API reference, we recommend reading Model Design Rules for the conceptual model and Creating a New Model Provider for a step-by-step walkthrough.
Quick Decision: Which Method Do I Implement?
Every provider also implements
validate_provider_credentials (provider-level auth) and, if the model is user-configurable, validate_credentials per model type.
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
Credential information as defined in the provider’s YAML configuration under
provider_credential_schema, typically fields such as api_key and organization_id.Models
Dify supports five distinct model types, each with its own interface. All model types share the common requirements below.Common Interfaces
Every model implementation, regardless of type, must implement these two fundamental methods:1. Model Credential Validation
The specific model identifier to validate (e.g., “gpt-4”, “claude-3-opus”)
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
Model identifier (e.g., “gpt-4”, “claude-3”)
Authentication credentials for the API
Message list in Dify’s standardized format:
- For
completionmodels: include a singleUserPromptMessage. - For
chatmodels: includeSystemPromptMessage,UserPromptMessage,AssistantPromptMessage, andToolPromptMessageas needed.
Model-specific parameters (temperature, top_p, etc.) as defined in the model’s YAML configuration
Tool definitions for function calling capabilities
Stop sequences that will halt model generation when encountered
Whether to return a streaming response
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
A structured response containing:
model: The model used for embedding.embeddings: Embedding vectors in the same order as the 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
Reranking model identifier
Authentication credentials for the API
The search query text
List of document texts to be reranked
Minimum score a document must reach to be included in the results
Maximum number of results to return
User identifier for API monitoring
Return Value
Return Value
A structured response containing:
model: The model used for reranking.docs: List ofRerankDocumentobjects 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
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 indicating content safety:
False: The content is safe.True: The content contains harmful material.
Entities
PromptMessageRole
The role of a message in a conversation.PromptMessageContentType
The type of message content: plain text or image.PromptMessageContent
Base class for message content. It exists only for type declarations—do not instantiate it directly.TextPromptMessageContent and ImagePromptMessageContent instead.
TextPromptMessageContent
content list.
ImagePromptMessageContent
content list. data accepts an image URL or a base64-encoded image string.
PromptMessage
Base class for all role-specific messages. It exists only for type declarations—do not instantiate it directly.UserPromptMessage
Represents a user message.AssistantPromptMessage
Represents a model response, typically used for few-shot examples or chat history input.tool_calls holds the tool calls the model returns when the request includes tools.
SystemPromptMessage
Represents a system message, typically used to set system instructions for the model.ToolPromptMessage
Represents a tool message, which passes a tool’s execution result back to the model for next-step planning.content field.
PromptMessageTool
LLMResult
LLMResultChunkDelta
The incremental delta within each chunk of a streaming response.LLMResultChunk
A single chunk in a streaming response.LLMUsage
TextEmbeddingResult
EmbeddingUsage
RerankResult
RerankDocument
Related Resources
- Model Design Rules: standards for model configuration.
- Model Plugin Introduction: core concepts of model plugins.
- Quickly Integrate a New Model: add new models to existing providers.
- Create a New Model Provider: develop a new model provider from scratch.