メインコンテンツへスキップ
⚠️ このドキュメントはAIによって自動翻訳されています。不正確な部分がある場合は、英語版を参照してください。

はじめに

このドキュメントでは、Difyモデルプラグインを実装するために必要なインターフェースとデータ構造について詳しく説明します。AIモデルをDifyプラットフォームと統合する開発者向けの技術リファレンスとして機能します。
このAPIリファレンスに入る前に、概念的な理解のためにモデル設計ルールモデルプラグイン入門を先に読むことをお勧めします。

モデルプロバイダー

すべてのモデルプロバイダーは__base.model_provider.ModelProvider基底クラスを継承し、認証情報検証インターフェースを実装する必要があります。

プロバイダー認証情報検証

def validate_provider_credentials(self, credentials: dict) -> None:
    """
    Validate provider credentials by making a test API call
    
    Parameters:
        credentials: Provider credentials as defined in `provider_credential_schema`
        
    Raises:
        CredentialsValidateFailedError: If validation fails
    """
    try:
        # Example implementation - validate using an LLM model instance
        model_instance = self.get_model_instance(ModelType.LLM)
        model_instance.validate_credentials(
            model="example-model", 
            credentials=credentials
        )
    except Exception as ex:
        logger.exception(f"Credential validation failed")
        raise CredentialsValidateFailedError(f"Invalid credentials: {str(ex)}")
credentials
dict
プロバイダーのYAML設定のprovider_credential_schemaで定義された認証情報。 通常、api_keyorganization_idなどのフィールドを含みます。
検証が失敗した場合、実装はCredentialsValidateFailedError例外をスローする必要があります。これにより、Dify UIで適切なエラーハンドリングが保証されます。
事前定義されたモデルプロバイダーの場合、認証情報がAPIで機能することを検証する徹底的な検証メソッドを実装する必要があります。カスタムモデルプロバイダー(各モデルが独自の認証情報を持つ場合)では、簡略化された実装で十分です。

モデル

Difyは5つの異なるモデルタイプをサポートしており、それぞれ特定のインターフェースの実装が必要です。ただし、すべてのモデルタイプにはいくつかの共通要件があります。

共通インターフェース

タイプに関係なく、すべてのモデル実装はこれら2つの基本メソッドを実装する必要があります:

1. モデル認証情報検証

def validate_credentials(self, model: str, credentials: dict) -> None:
    """
    Validate that the provided credentials work with the specified model
    
    Parameters:
        model: The specific model identifier (e.g., "gpt-4")
        credentials: Authentication details for the model
        
    Raises:
        CredentialsValidateFailedError: If validation fails
    """
    try:
        # Make a lightweight API call to verify credentials
        # Example: List available models or check account status
        response = self._api_client.validate_api_key(credentials["api_key"])
        
        # Verify the specific model is available if applicable
        if model not in response.get("available_models", []):
            raise CredentialsValidateFailedError(f"Model {model} is not available")
            
    except ApiException as e:
        raise CredentialsValidateFailedError(str(e))
model
string
required
検証する特定のモデル識別子(例:「gpt-4」、「claude-3-opus」)
credentials
dict
required
プロバイダーの設定で定義された認証情報

2. エラーマッピング

@property
def _invoke_error_mapping(self) -> dict[type[InvokeError], list[type[Exception]]]:
    """
    Map provider-specific exceptions to standardized Dify error types
    
    Returns:
        Dictionary mapping Dify error types to lists of provider exception types
    """
    return {
        InvokeConnectionError: [
            requests.exceptions.ConnectionError,
            requests.exceptions.Timeout,
            ConnectionRefusedError
        ],
        InvokeServerUnavailableError: [
            ServiceUnavailableError,
            HTTPStatusError
        ],
        InvokeRateLimitError: [
            RateLimitExceededError,
            QuotaExceededError
        ],
        InvokeAuthorizationError: [
            AuthenticationError,
            InvalidAPIKeyError,
            PermissionDeniedError
        ],
        InvokeBadRequestError: [
            InvalidRequestError,
            ValidationError
        ]
    }
InvokeConnectionError
class
ネットワーク接続の失敗、タイムアウト
InvokeServerUnavailableError
class
サービスプロバイダーがダウンまたは利用不可
InvokeRateLimitError
class
レート制限またはクォータ制限に到達
InvokeAuthorizationError
class
認証または権限の問題
InvokeBadRequestError
class
無効なパラメータまたはリクエスト
エラーマッピングに依存する代わりに、コード内でこれらの標準化されたエラータイプを直接スローすることもできます。このアプローチにより、エラーメッセージをより細かく制御できます。

LLM実装

大規模言語モデルプロバイダーを実装するには、__base.large_language_model.LargeLanguageModel基底クラスを継承し、これらのメソッドを実装します:

1. モデル呼び出し

このコアメソッドは、言語モデルへのストリーミングおよび非ストリーミングAPI呼び出しの両方を処理します。
def _invoke(
    self, 
    model: str, 
    credentials: dict,
    prompt_messages: list[PromptMessage], 
    model_parameters: dict,
    tools: Optional[list[PromptMessageTool]] = None, 
    stop: Optional[list[str]] = None,
    stream: bool = True, 
    user: Optional[str] = None
) -> Union[LLMResult, Generator[LLMResultChunk, None, None]]:
    """
    Invoke the language model
    """
    # Prepare API parameters
    api_params = self._prepare_api_parameters(
        model, 
        credentials, 
        prompt_messages, 
        model_parameters,
        tools, 
        stop
    )
    
    try:
        # Choose between streaming and non-streaming implementation
        if stream:
            return self._invoke_stream(model, api_params, user)
        else:
            return self._invoke_sync(model, api_params, user)
            
    except Exception as e:
        # Map errors using the error mapping property
        self._handle_api_error(e)

# Helper methods for streaming and non-streaming calls
def _invoke_stream(self, model, api_params, user):
    # Implement streaming call and yield chunks
    pass
    
def _invoke_sync(self, model, api_params, user):
    # Implement synchronous call and return complete result
    pass
model
string
required
モデル識別子(例:「gpt-4」、「claude-3」)
credentials
dict
required
API用の認証情報
prompt_messages
list[PromptMessage]
required
Difyの標準化されたフォーマットのメッセージリスト:
  • completionモデルの場合:単一のUserPromptMessageを含める
  • chatモデルの場合:必要に応じてSystemPromptMessageUserPromptMessageAssistantPromptMessageToolPromptMessageを含める
model_parameters
dict
required
モデルのYAML設定で定義されたモデル固有のパラメータ(temperature、top_pなど)
tools
list[PromptMessageTool]
関数呼び出し機能のためのツール定義
stop
list[string]
遭遇時にモデル生成を停止するストップシーケンス
stream
boolean
default:true
ストリーミングレスポンスを返すかどうか
user
string
API監視用のユーザー識別子
stream=True
Generator[LLMResultChunk, None, None]
利用可能になったレスポンスのチャンクをyieldするジェネレータ
stream=False
LLMResult
完全な生成テキストを含む完全なレスポンスオブジェクト
コードを整理して保守しやすくするために、ストリーミングと非ストリーミング呼び出し用に別々のヘルパーメソッドを実装することをお勧めします。

2. トークンカウント

def get_num_tokens(
    self, 
    model: str, 
    credentials: dict, 
    prompt_messages: list[PromptMessage],
    tools: Optional[list[PromptMessageTool]] = None
) -> int:
    """
    Calculate the number of tokens in the prompt
    """
    # Convert prompt_messages to the format expected by the tokenizer
    text = self._convert_messages_to_text(prompt_messages)
    
    try:
        # Use the appropriate tokenizer for this model
        tokenizer = self._get_tokenizer(model)
        return len(tokenizer.encode(text))
    except Exception:
        # Fall back to a generic tokenizer
        return self._get_num_tokens_by_gpt2(text)
モデルがトークナイザーを提供していない場合、基底クラスの_get_num_tokens_by_gpt2(text)メソッドを使用して妥当な近似値を得ることができます。

3. カスタムモデルスキーマ(オプション)

def get_customizable_model_schema(
    self, 
    model: str, 
    credentials: dict
) -> Optional[AIModelEntity]:
    """
    Get parameter schema for custom models
    """
    # For fine-tuned models, you might return the base model's schema
    if model.startswith("ft:"):
        base_model = self._extract_base_model(model)
        return self._get_predefined_model_schema(base_model)
    
    # For standard models, return None to use the predefined schema
    return None
このメソッドは、カスタムモデルをサポートするプロバイダーにのみ必要です。カスタムモデルが基本モデルからパラメータルールを継承できるようにします。

TextEmbedding実装

テキスト埋め込みモデルは、テキストを意味的な意味を捉える高次元ベクトルに変換し、検索、類似性検索、分類に役立ちます。
Text Embeddingプロバイダーを実装するには、__base.text_embedding_model.TextEmbeddingModel基底クラスを継承します:

1. コア埋め込みメソッド

def _invoke(
    self, 
    model: str, 
    credentials: dict,
    texts: list[str], 
    user: Optional[str] = None
) -> TextEmbeddingResult:
    """
    Generate embedding vectors for multiple texts
    """
    # Set up API client with credentials
    client = self._get_client(credentials)
    
    # Handle batching if needed
    batch_size = self._get_batch_size(model)
    all_embeddings = []
    total_tokens = 0
    start_time = time.time()
    
    # Process in batches to avoid API limits
    for i in range(0, len(texts), batch_size):
        batch = texts[i:i+batch_size]
        
        # Make API call to the embeddings endpoint
        response = client.embeddings.create(
            model=model,
            input=batch,
            user=user
        )
        
        # Extract embeddings from response
        batch_embeddings = [item.embedding for item in response.data]
        all_embeddings.extend(batch_embeddings)
        
        # Track token usage
        total_tokens += response.usage.total_tokens
    
    # Calculate usage metrics
    elapsed_time = time.time() - start_time
    usage = self._create_embedding_usage(
        model=model,
        tokens=total_tokens,
        latency=elapsed_time
    )
    
    return TextEmbeddingResult(
        model=model,
        embeddings=all_embeddings,
        usage=usage
    )
model
string
required
埋め込みモデル識別子
credentials
dict
required
埋め込みサービス用の認証情報
texts
list[string]
required
埋め込むテキスト入力のリスト
user
string
API監視用のユーザー識別子
TextEmbeddingResult
object
required
以下を含む構造化されたレスポンス:
  • model:埋め込みに使用されたモデル
  • embeddings:入力テキストに対応する埋め込みベクトルのリスト
  • usage:トークン使用量とコストに関するメタデータ

2. トークンカウントメソッド

def get_num_tokens(
    self, 
    model: str, 
    credentials: dict, 
    texts: list[str]
) -> int:
    """
    Calculate the number of tokens in the texts to be embedded
    """
    # Join all texts to estimate token count
    combined_text = " ".join(texts)
    
    try:
        # Use the appropriate tokenizer for this model
        tokenizer = self._get_tokenizer(model)
        return len(tokenizer.encode(combined_text))
    except Exception:
        # Fall back to a generic tokenizer
        return self._get_num_tokens_by_gpt2(combined_text)
埋め込みモデルでは、正確なトークンカウントはコスト見積もりに重要ですが、機能性には重要ではありません。_get_num_tokens_by_gpt2メソッドはほとんどのモデルに対して妥当な近似値を提供します。

Rerank実装

リランキングモデルは、通常初期検索フェーズの後、クエリとの関連性に基づいて候補ドキュメントのセットを再順序付けすることで検索品質を向上させます。
Rerankingプロバイダーを実装するには、__base.rerank_model.RerankModel基底クラスを継承します:
def _invoke(
    self, 
    model: str, 
    credentials: dict,
    query: str, 
    docs: list[str], 
    score_threshold: Optional[float] = None, 
    top_n: Optional[int] = None,
    user: Optional[str] = None
) -> RerankResult:
    """
    Rerank documents based on relevance to the query
    """
    # Set up API client with credentials
    client = self._get_client(credentials)
    
    # Prepare request data
    request_data = {
        "query": query,
        "documents": docs,
    }
    
    # Call reranking API endpoint
    response = client.rerank(
        model=model,
        **request_data,
        user=user
    )
    
    # Process results
    ranked_results = []
    for i, result in enumerate(response.results):
        # Create RerankDocument for each result
        doc = RerankDocument(
            index=result.document_index,  # Original index in docs list
            text=docs[result.document_index],  # Original text
            score=result.relevance_score  # Relevance score
        )
        ranked_results.append(doc)
    
    # Sort by score in descending order
    ranked_results.sort(key=lambda x: x.score, reverse=True)
    
    # Apply score threshold filtering if specified
    if score_threshold is not None:
        ranked_results = [doc for doc in ranked_results if doc.score >= score_threshold]
    
    # Apply top_n limit if specified
    if top_n is not None and top_n > 0:
        ranked_results = ranked_results[:top_n]
    
    return RerankResult(
        model=model,
        docs=ranked_results
    )
model
string
required
リランキングモデル識別子
credentials
dict
required
API用の認証情報
query
string
required
検索クエリテキスト
docs
list[string]
required
リランキングされるドキュメントテキストのリスト
score_threshold
float
結果をフィルタリングするためのオプションの最小スコア閾値
top_n
int
返す結果数のオプションの制限
user
string
API監視用のユーザー識別子
RerankResult
object
required
以下を含む構造化されたレスポンス:
  • model:リランキングに使用されたモデル
  • docs:index、text、scoreを持つRerankDocumentオブジェクトのリスト
リランキングは計算コストが高くなる可能性があり、特に大きなドキュメントセットでは顕著です。タイムアウトや過度のリソース消費を避けるために、大きなドキュメントコレクションにはバッチ処理を実装してください。

Speech2Text実装

音声テキスト変換モデルは、音声ファイルから話された言語を書かれたテキストに変換し、文字起こしサービス、音声コマンド、アクセシビリティ機能などのアプリケーションを可能にします。
Speech-to-Textプロバイダーを実装するには、__base.speech2text_model.Speech2TextModel基底クラスを継承します:
def _invoke(
    self, 
    model: str, 
    credentials: dict,
    file: IO[bytes], 
    user: Optional[str] = None
) -> str:
    """
    Convert speech audio to text
    """
    # Set up API client with credentials
    client = self._get_client(credentials)
    
    try:
        # Determine the file format
        file_format = self._detect_audio_format(file)
        
        # Prepare the file for API submission
        # Most APIs require either a file path or binary data
        audio_data = file.read()
        
        # Call the speech-to-text API
        response = client.audio.transcriptions.create(
            model=model,
            file=("audio.mp3", audio_data),  # Adjust filename based on actual format
            user=user
        )
        
        # Extract and return the transcribed text
        return response.text
        
    except Exception as e:
        # Map to appropriate error type
        self._handle_api_error(e)
        
    finally:
        # Reset file pointer for potential reuse
        file.seek(0)
model
string
required
音声テキスト変換モデル識別子
credentials
dict
required
API用の認証情報
file
IO[bytes]
required
文字起こしする音声を含むバイナリファイルオブジェクト
user
string
API監視用のユーザー識別子
text
string
required
音声ファイルから文字起こしされたテキスト
異なるファイルタイプを適切に処理するためには、音声フォーマットの検出が重要です。例に示すように、ファイルヘッダーからフォーマットを検出するヘルパーメソッドの実装を検討してください。
一部の音声テキスト変換APIにはファイルサイズの制限があります。必要に応じて、大きな音声ファイル用にチャンク処理を実装することを検討してください。

Text2Speech実装

テキスト音声変換モデルは、書かれたテキストを自然な音声に変換し、音声アシスタント、スクリーンリーダー、音声コンテンツ生成などのアプリケーションを可能にします。
Text-to-Speechプロバイダーを実装するには、__base.text2speech_model.Text2SpeechModel基底クラスを継承します:
def _invoke(
    self, 
    model: str, 
    credentials: dict, 
    content_text: str, 
    streaming: bool,
    user: Optional[str] = None
) -> Union[bytes, Generator[bytes, None, None]]:
    """
    Convert text to speech audio
    """
    # Set up API client with credentials
    client = self._get_client(credentials)
    
    # Get voice settings based on model
    voice = self._get_voice_for_model(model)
    
    try:
        # Choose implementation based on streaming preference
        if streaming:
            return self._stream_audio(
                client=client,
                model=model,
                text=content_text,
                voice=voice,
                user=user
            )
        else:
            return self._generate_complete_audio(
                client=client,
                model=model,
                text=content_text,
                voice=voice,
                user=user
            )
    except Exception as e:
        self._handle_api_error(e)
model
string
required
テキスト音声変換モデル識別子
credentials
dict
required
API用の認証情報
content_text
string
required
音声に変換するテキストコンテンツ
streaming
boolean
required
ストリーミング音声を返すか完全なファイルを返すか
user
string
API監視用のユーザー識別子
streaming=True
Generator[bytes, None, None]
利用可能になった音声チャンクをyieldするジェネレータ
streaming=False
bytes
バイトとしての完全な音声データ
ほとんどのテキスト音声変換APIでは、モデルと一緒に音声を指定する必要があります。Difyのモデル識別子とプロバイダーの音声オプション間のマッピングを実装することを検討してください。
長いテキスト入力は、より良い音声合成品質のためにチャンク処理が必要な場合があります。句読点、数字、特殊文字を適切に処理するためのテキスト前処理の実装を検討してください。

Moderation実装

モデレーションモデルは、潜在的に有害、不適切、または安全でないコンテンツについてコンテンツを分析し、プラットフォームの安全性とコンテンツポリシーの維持を支援します。
Moderationプロバイダーを実装するには、__base.moderation_model.ModerationModel基底クラスを継承します:
def _invoke(
    self, 
    model: str, 
    credentials: dict,
    text: str, 
    user: Optional[str] = None
) -> bool:
    """
    Analyze text for harmful content
    
    Returns:
        bool: False if the text is safe, True if it contains harmful content
    """
    # Set up API client with credentials
    client = self._get_client(credentials)
    
    try:
        # Call moderation API
        response = client.moderations.create(
            model=model,
            input=text,
            user=user
        )
        
        # Check if any categories were flagged
        result = response.results[0]
        
        # Return True if flagged in any category, False if safe
        return result.flagged
        
    except Exception as e:
        # Log the error but default to safe if there's an API issue
        # This is a conservative approach - production systems might want
        # different fallback behavior
        logger.error(f"Moderation API error: {str(e)}")
        return False
model
string
required
モデレーションモデル識別子
credentials
dict
required
API用の認証情報
text
string
required
分析するテキストコンテンツ
user
string
API監視用のユーザー識別子
result
boolean
required
コンテンツの安全性を示すブール値:
  • False:コンテンツは安全
  • True:コンテンツに有害な素材が含まれている
モデレーションは安全機構として使用されることが多いです。ソリューションを実装する際は、偽陰性(有害なコンテンツを通過させる)と偽陽性(安全なコンテンツをブロックする)の影響を考慮してください。
多くのモデレーションAPIは、単なるバイナリ結果ではなく、詳細なカテゴリスコアを提供します。アプリケーションで必要な場合は、有害なコンテンツの特定のカテゴリに関するより詳細な情報を返すようにこの実装を拡張することを検討してください。

エンティティ

PromptMessageRole

メッセージロール
class PromptMessageRole(Enum):
    """
    Enum class for prompt message.
    """
    SYSTEM = "system"
    USER = "user"
    ASSISTANT = "assistant"
    TOOL = "tool"

PromptMessageContentType

メッセージコンテンツタイプ、プレーンテキストと画像に分かれます。
class PromptMessageContentType(Enum):
    """
    Enum class for prompt message content type.
    """
    TEXT = 'text'
    IMAGE = 'image'

PromptMessageContent

メッセージコンテンツ基底クラス、パラメータ宣言のみに使用され、初期化できません。
class PromptMessageContent(BaseModel):
    """
    Model class for prompt message content.
    """
    type: PromptMessageContentType
    data: str  # Content data
現在、テキストと画像の2種類をサポートしており、テキストと複数の画像を同時にサポートできます。 TextPromptMessageContentImagePromptMessageContentを別々に初期化する必要があります。

TextPromptMessageContent

class TextPromptMessageContent(PromptMessageContent):
    """
    Model class for text prompt message content.
    """
    type: PromptMessageContentType = PromptMessageContentType.TEXT
テキストと画像を渡す場合、テキストはcontentリストの一部としてこのエンティティとして構築する必要があります。

ImagePromptMessageContent

class ImagePromptMessageContent(PromptMessageContent):
    """
    Model class for image prompt message content.
    """
    class DETAIL(Enum):
        LOW = 'low'
        HIGH = 'high'

    type: PromptMessageContentType = PromptMessageContentType.IMAGE
    detail: DETAIL = DETAIL.LOW  # Resolution
テキストと画像を渡す場合、画像はcontentリストの一部としてこのエンティティとして構築する必要があります。 dataurlまたは画像のbase64エンコードされた文字列にすることができます。

PromptMessage

すべてのロールメッセージボディの基底クラス、パラメータ宣言のみに使用され、初期化できません。
class PromptMessage(ABC, BaseModel):
    """
    Model class for prompt message.
    """
    role: PromptMessageRole  # Message role
    content: Optional[str | list[PromptMessageContent]] = None  # Supports two types: string and content list. The content list is for multimodal needs, see PromptMessageContent for details.
    name: Optional[str] = None  # Name, optional.

UserPromptMessage

UserMessageメッセージボディ、ユーザーメッセージを表します。
class UserPromptMessage(PromptMessage):
    """
    Model class for user prompt message.
    """
    role: PromptMessageRole = PromptMessageRole.USER

AssistantPromptMessage

モデル応答メッセージを表し、通常few-shotsまたはチャット履歴入力に使用されます。
class AssistantPromptMessage(PromptMessage):
    """
    Model class for assistant prompt message.
    """
    class ToolCall(BaseModel):
        """
        Model class for assistant prompt message tool call.
        """
        class ToolCallFunction(BaseModel):
            """
            Model class for assistant prompt message tool call function.
            """
            name: str  # Tool name
            arguments: str  # Tool parameters

        id: str  # Tool ID, only effective for OpenAI tool call, a unique ID for tool invocation, the same tool can be called multiple times
        type: str  # Default is function
        function: ToolCallFunction  # Tool call information

    role: PromptMessageRole = PromptMessageRole.ASSISTANT
    tool_calls: list[ToolCall] = []  # Model's tool call results (only returned when tools are passed in and the model decides to call them)
ここでtool_callsは、モデルにtoolsを渡した後にモデルが返すtool callのリストです。

SystemPromptMessage

システムメッセージを表し、通常モデルのシステム指示を設定するために使用されます。
class SystemPromptMessage(PromptMessage):
    """
    Model class for system prompt message.
    """
    role: PromptMessageRole = PromptMessageRole.SYSTEM

ToolPromptMessage

ツールメッセージを表し、ツールが実行された後に次のステップの計画のために結果をモデルに渡すために使用されます。
class ToolPromptMessage(PromptMessage):
    """
    Model class for tool prompt message.
    """
    role: PromptMessageRole = PromptMessageRole.TOOL
    tool_call_id: str  # Tool call ID, if OpenAI tool call is not supported, you can also pass in the tool name
基底クラスのcontentにツール実行結果を渡します。

PromptMessageTool

class PromptMessageTool(BaseModel):
    """
    Model class for prompt message tool.
    """
    name: str  # Tool name
    description: str  # Tool description
    parameters: dict  # Tool parameters dict


LLMResult

class LLMResult(BaseModel):
    """
    Model class for llm result.
    """
    model: str  # Actually used model
    prompt_messages: list[PromptMessage]  # Prompt message list
    message: AssistantPromptMessage  # Reply message
    usage: LLMUsage  # Tokens used and cost information
    system_fingerprint: Optional[str] = None  # Request fingerprint, refer to OpenAI parameter definition

LLMResultChunkDelta

ストリーミングレスポンスの各イテレーション内のDeltaエンティティ
class LLMResultChunkDelta(BaseModel):
    """
    Model class for llm result chunk delta.
    """
    index: int  # Sequence number
    message: AssistantPromptMessage  # Reply message
    usage: Optional[LLMUsage] = None  # Tokens used and cost information, only returned in the last message
    finish_reason: Optional[str] = None  # Completion reason, only returned in the last message

LLMResultChunk

ストリーミングレスポンスのイテレーションエンティティ
class LLMResultChunk(BaseModel):
    """
    Model class for llm result chunk.
    """
    model: str  # Actually used model
    prompt_messages: list[PromptMessage]  # Prompt message list
    system_fingerprint: Optional[str] = None  # Request fingerprint, refer to OpenAI parameter definition
    delta: LLMResultChunkDelta  # Changes in content for each iteration

LLMUsage

class LLMUsage(ModelUsage):
    """
    Model class for llm usage.
    """
    prompt_tokens: int  # Tokens used by prompt
    prompt_unit_price: Decimal  # Prompt unit price
    prompt_price_unit: Decimal  # Prompt price unit, i.e., unit price based on how many tokens
    prompt_price: Decimal  # Prompt cost
    completion_tokens: int  # Tokens used by completion
    completion_unit_price: Decimal  # Completion unit price
    completion_price_unit: Decimal  # Completion price unit, i.e., unit price based on how many tokens
    completion_price: Decimal  # Completion cost
    total_tokens: int  # Total tokens used
    total_price: Decimal  # Total cost
    currency: str  # Currency unit
    latency: float  # Request time (s)

TextEmbeddingResult

class TextEmbeddingResult(BaseModel):
    """
    Model class for text embedding result.
    """
    model: str  # Actually used model
    embeddings: list[list[float]]  # Embedding vector list, corresponding to the input texts list
    usage: EmbeddingUsage  # Usage information

EmbeddingUsage

class EmbeddingUsage(ModelUsage):
    """
    Model class for embedding usage.
    """
    tokens: int  # Tokens used
    total_tokens: int  # Total tokens used
    unit_price: Decimal  # Unit price
    price_unit: Decimal  # Price unit, i.e., unit price based on how many tokens
    total_price: Decimal  # Total cost
    currency: str  # Currency unit
    latency: float  # Request time (s)

RerankResult

class RerankResult(BaseModel):
    """
    Model class for rerank result.
    """
    model: str  # Actually used model
    docs: list[RerankDocument]  # List of reranked segments        

RerankDocument

class RerankDocument(BaseModel):
    """
    Model class for rerank document.
    """
    index: int  # Original sequence number
    text: str  # Segment text content
    score: float  # Score

関連リソース


Edit this page | Report an issue