Skip to main content

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

dict
Credential information as defined in the provider’s YAML configuration under provider_credential_schema, typically fields such as api_key and organization_id.
If validation fails, your implementation must raise a CredentialsValidateFailedError exception. This ensures proper error handling in the Dify UI.
For predefined model providers, implement a thorough validation method that verifies the credentials against 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 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

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, and 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: Embedding vectors in the same order as the 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
Minimum score a document must reach to be included in the results
int
Maximum 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

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.
Content currently supports two types, text and image, and a single message can combine text with multiple images. Instantiate TextPromptMessageContent and ImagePromptMessageContent instead.

TextPromptMessageContent

When a message combines text and images, wrap the text in this entity and add it to the content list.

ImagePromptMessageContent

When a message combines text and images, wrap each image in this entity and add it to the 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.
Pass the tool’s execution result through the inherited 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

Last modified on June 24, 2026