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.

Note

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?#

If your model is a…Implement
Chat/completion LLMLargeLanguageModel._invoke, _get_num_tokens
Embedding modelTextEmbeddingModel._invoke, _get_num_tokens
Rerank modelRerankModel._invoke
Speech-to-textSpeech2TextModel._invoke
Text-to-speechText2SpeechModel._invoke
ModerationModerationModel._invoke

Every provider also implements validate_provider_credentials (provider-level auth) and, if the model is user-configurable, validate_credentials per model type.

Model Provider#

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

Provider Credential Validation#

credentialsdict#

Credential information as defined in the provider’s YAML configuration under provider_credential_schema, typically fields such as api_key and organization_id.

Warning

If validation fails, your implementation must raise a CredentialsValidateFailedError exception. This ensures proper error handling in the Dify UI.

Tip

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#

modelstringrequired#

The specific model identifier to validate (e.g., “gpt-4”, “claude-3-opus”)

credentialsdictrequired#

Credential information as defined in the provider’s configuration

2. Error Mapping#

Available Error Types
InvokeConnectionErrorclass#

Network connection failures, timeouts

InvokeServerUnavailableErrorclass#

Service provider is down or unavailable

InvokeRateLimitErrorclass#

Rate limits or quota limits reached

InvokeAuthorizationErrorclass#

Authentication or permission issues

InvokeBadRequestErrorclass#

Invalid parameters or requests

Tip

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.

Parameters
modelstringrequired#

Model identifier (e.g., “gpt-4”, “claude-3”)

credentialsdictrequired#

Authentication credentials for the API

prompt_messageslist[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.
model_parametersdictrequired#

Model-specific parameters (temperature, top_p, etc.) as defined in the model’s YAML configuration

toolslist[PromptMessageTool]#

Tool definitions for function calling capabilities

stoplist[string]#

Stop sequences that will halt model generation when encountered

streamboolean#

Whether to return a streaming response

Default: true

userstring#

User identifier for API monitoring

Return Values
stream=TrueGenerator[LLMResultChunk, None, None]#

A generator yielding chunks of the response as they become available

stream=FalseLLMResult#

A complete response object with the full generated text

Tip

We recommend implementing separate helper methods for streaming and non-streaming calls to keep your code organized and maintainable.

2. Token Counting#

Info

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)#

Info

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

TextEmbedding Implementation#

Info

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#

Parameters
modelstringrequired#

Embedding model identifier

credentialsdictrequired#

Authentication credentials for the embedding service

textslist[string]required#

List of text inputs to embed

userstring#

User identifier for API monitoring

Return Value
TextEmbeddingResultobjectrequired#

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#

Tip

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#

Info

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:

Parameters
modelstringrequired#

Reranking model identifier

credentialsdictrequired#

Authentication credentials for the API

querystringrequired#

The search query text

docslist[string]required#

List of document texts to be reranked

score_thresholdfloat#

Minimum score a document must reach to be included in the results

top_nint#

Maximum number of results to return

userstring#

User identifier for API monitoring

Return Value
RerankResultobjectrequired#

A structured response containing:

  • model: The model used for reranking.
  • docs: List of RerankDocument objects with index, text, and score.
Warning

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#

Info

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:

Parameters
modelstringrequired#

Speech-to-text model identifier

credentialsdictrequired#

Authentication credentials for the API

fileIO[bytes]required#

Binary file object containing the audio to transcribe

userstring#

User identifier for API monitoring

Return Value
textstringrequired#

The transcribed text from the audio file

Tip

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.

Warning

Some speech-to-text APIs have file size limitations. Consider implementing chunking for large audio files if necessary.

Text2Speech Implementation#

Info

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:

Parameters
modelstringrequired#

Text-to-speech model identifier

credentialsdictrequired#

Authentication credentials for the API

content_textstringrequired#

Text content to be converted to speech

streamingbooleanrequired#

Whether to return streaming audio or complete file

userstring#

User identifier for API monitoring

Return Value
streaming=TrueGenerator[bytes, None, None]#

A generator yielding audio chunks as they become available

streaming=Falsebytes#

Complete audio data as bytes

Tip

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.

Warning

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#

Info

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:

Parameters
modelstringrequired#

Moderation model identifier

credentialsdictrequired#

Authentication credentials for the API

textstringrequired#

Text content to be analyzed

userstring#

User identifier for API monitoring

Return Value
resultbooleanrequired#

Boolean indicating content safety:

  • False: The content is safe.
  • True: The content contains harmful material.
Warning

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.

Tip

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#