dify
This commit is contained in:
34
dify/sdks/python-client/dify_client/__init__.py
Normal file
34
dify/sdks/python-client/dify_client/__init__.py
Normal file
@@ -0,0 +1,34 @@
|
||||
from dify_client.client import (
|
||||
ChatClient,
|
||||
CompletionClient,
|
||||
DifyClient,
|
||||
KnowledgeBaseClient,
|
||||
WorkflowClient,
|
||||
WorkspaceClient,
|
||||
)
|
||||
|
||||
from dify_client.async_client import (
|
||||
AsyncChatClient,
|
||||
AsyncCompletionClient,
|
||||
AsyncDifyClient,
|
||||
AsyncKnowledgeBaseClient,
|
||||
AsyncWorkflowClient,
|
||||
AsyncWorkspaceClient,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
# Synchronous clients
|
||||
"ChatClient",
|
||||
"CompletionClient",
|
||||
"DifyClient",
|
||||
"KnowledgeBaseClient",
|
||||
"WorkflowClient",
|
||||
"WorkspaceClient",
|
||||
# Asynchronous clients
|
||||
"AsyncChatClient",
|
||||
"AsyncCompletionClient",
|
||||
"AsyncDifyClient",
|
||||
"AsyncKnowledgeBaseClient",
|
||||
"AsyncWorkflowClient",
|
||||
"AsyncWorkspaceClient",
|
||||
]
|
||||
2074
dify/sdks/python-client/dify_client/async_client.py
Normal file
2074
dify/sdks/python-client/dify_client/async_client.py
Normal file
File diff suppressed because it is too large
Load Diff
228
dify/sdks/python-client/dify_client/base_client.py
Normal file
228
dify/sdks/python-client/dify_client/base_client.py
Normal file
@@ -0,0 +1,228 @@
|
||||
"""Base client with common functionality for both sync and async clients."""
|
||||
|
||||
import json
|
||||
import time
|
||||
import logging
|
||||
from typing import Dict, Callable, Optional
|
||||
|
||||
try:
|
||||
# Python 3.10+
|
||||
from typing import ParamSpec
|
||||
except ImportError:
|
||||
# Python < 3.10
|
||||
from typing_extensions import ParamSpec
|
||||
|
||||
from urllib.parse import urljoin
|
||||
|
||||
import httpx
|
||||
|
||||
P = ParamSpec("P")
|
||||
|
||||
from .exceptions import (
|
||||
DifyClientError,
|
||||
APIError,
|
||||
AuthenticationError,
|
||||
RateLimitError,
|
||||
ValidationError,
|
||||
NetworkError,
|
||||
TimeoutError,
|
||||
)
|
||||
|
||||
|
||||
class BaseClientMixin:
|
||||
"""Mixin class providing common functionality for Dify clients."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
api_key: str,
|
||||
base_url: str = "https://api.dify.ai/v1",
|
||||
timeout: float = 60.0,
|
||||
max_retries: int = 3,
|
||||
retry_delay: float = 1.0,
|
||||
enable_logging: bool = False,
|
||||
):
|
||||
"""Initialize the base client.
|
||||
|
||||
Args:
|
||||
api_key: Your Dify API key
|
||||
base_url: Base URL for the Dify API
|
||||
timeout: Request timeout in seconds
|
||||
max_retries: Maximum number of retry attempts
|
||||
retry_delay: Delay between retries in seconds
|
||||
enable_logging: Enable detailed logging
|
||||
"""
|
||||
if not api_key:
|
||||
raise ValidationError("API key is required")
|
||||
|
||||
self.api_key = api_key
|
||||
self.base_url = base_url.rstrip("/")
|
||||
self.timeout = timeout
|
||||
self.max_retries = max_retries
|
||||
self.retry_delay = retry_delay
|
||||
self.enable_logging = enable_logging
|
||||
|
||||
# Setup logging
|
||||
self.logger = logging.getLogger(f"dify_client.{self.__class__.__name__.lower()}")
|
||||
if enable_logging and not self.logger.handlers:
|
||||
# Create console handler with formatter
|
||||
handler = logging.StreamHandler()
|
||||
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
|
||||
handler.setFormatter(formatter)
|
||||
self.logger.addHandler(handler)
|
||||
self.logger.setLevel(logging.INFO)
|
||||
self.enable_logging = True
|
||||
else:
|
||||
self.enable_logging = enable_logging
|
||||
|
||||
def _get_headers(self, content_type: str = "application/json") -> Dict[str, str]:
|
||||
"""Get common request headers."""
|
||||
return {
|
||||
"Authorization": f"Bearer {self.api_key}",
|
||||
"Content-Type": content_type,
|
||||
"User-Agent": "dify-client-python/0.1.12",
|
||||
}
|
||||
|
||||
def _build_url(self, endpoint: str) -> str:
|
||||
"""Build full URL from endpoint."""
|
||||
return urljoin(self.base_url + "/", endpoint.lstrip("/"))
|
||||
|
||||
def _handle_response(self, response: httpx.Response) -> httpx.Response:
|
||||
"""Handle HTTP response and raise appropriate exceptions."""
|
||||
try:
|
||||
if response.status_code == 401:
|
||||
raise AuthenticationError(
|
||||
"Authentication failed. Check your API key.",
|
||||
status_code=response.status_code,
|
||||
response=response.json() if response.content else None,
|
||||
)
|
||||
elif response.status_code == 429:
|
||||
retry_after = response.headers.get("Retry-After")
|
||||
raise RateLimitError(
|
||||
"Rate limit exceeded. Please try again later.",
|
||||
retry_after=int(retry_after) if retry_after else None,
|
||||
)
|
||||
elif response.status_code >= 400:
|
||||
try:
|
||||
error_data = response.json()
|
||||
message = error_data.get("message", f"HTTP {response.status_code}")
|
||||
except:
|
||||
message = f"HTTP {response.status_code}: {response.text}"
|
||||
|
||||
raise APIError(
|
||||
message,
|
||||
status_code=response.status_code,
|
||||
response=response.json() if response.content else None,
|
||||
)
|
||||
|
||||
return response
|
||||
|
||||
except json.JSONDecodeError:
|
||||
raise APIError(
|
||||
f"Invalid JSON response: {response.text}",
|
||||
status_code=response.status_code,
|
||||
)
|
||||
|
||||
def _retry_request(
|
||||
self,
|
||||
request_func: Callable[P, httpx.Response],
|
||||
request_context: str | None = None,
|
||||
*args: P.args,
|
||||
**kwargs: P.kwargs,
|
||||
) -> httpx.Response:
|
||||
"""Retry a request with exponential backoff.
|
||||
|
||||
Args:
|
||||
request_func: Function that performs the HTTP request
|
||||
request_context: Context description for logging (e.g., "GET /v1/messages")
|
||||
*args: Positional arguments to pass to request_func
|
||||
**kwargs: Keyword arguments to pass to request_func
|
||||
|
||||
Returns:
|
||||
httpx.Response: Successful response
|
||||
|
||||
Raises:
|
||||
NetworkError: On network failures after retries
|
||||
TimeoutError: On timeout failures after retries
|
||||
APIError: On API errors (4xx/5xx responses)
|
||||
DifyClientError: On unexpected failures
|
||||
"""
|
||||
last_exception = None
|
||||
|
||||
for attempt in range(self.max_retries + 1):
|
||||
try:
|
||||
response = request_func(*args, **kwargs)
|
||||
return response # Let caller handle response processing
|
||||
|
||||
except (httpx.NetworkError, httpx.TimeoutException) as e:
|
||||
last_exception = e
|
||||
context_msg = f" {request_context}" if request_context else ""
|
||||
|
||||
if attempt < self.max_retries:
|
||||
delay = self.retry_delay * (2**attempt) # Exponential backoff
|
||||
self.logger.warning(
|
||||
f"Request failed{context_msg} (attempt {attempt + 1}/{self.max_retries + 1}): {e}. "
|
||||
f"Retrying in {delay:.2f} seconds..."
|
||||
)
|
||||
time.sleep(delay)
|
||||
else:
|
||||
self.logger.error(f"Request failed{context_msg} after {self.max_retries + 1} attempts: {e}")
|
||||
# Convert to custom exceptions
|
||||
if isinstance(e, httpx.TimeoutException):
|
||||
from .exceptions import TimeoutError
|
||||
|
||||
raise TimeoutError(f"Request timed out after {self.max_retries} retries{context_msg}") from e
|
||||
else:
|
||||
from .exceptions import NetworkError
|
||||
|
||||
raise NetworkError(
|
||||
f"Network error after {self.max_retries} retries{context_msg}: {str(e)}"
|
||||
) from e
|
||||
|
||||
if last_exception:
|
||||
raise last_exception
|
||||
raise DifyClientError("Request failed after retries")
|
||||
|
||||
def _validate_params(self, **params) -> None:
|
||||
"""Validate request parameters."""
|
||||
for key, value in params.items():
|
||||
if value is None:
|
||||
continue
|
||||
|
||||
# String validations
|
||||
if isinstance(value, str):
|
||||
if not value.strip():
|
||||
raise ValidationError(f"Parameter '{key}' cannot be empty or whitespace only")
|
||||
if len(value) > 10000:
|
||||
raise ValidationError(f"Parameter '{key}' exceeds maximum length of 10000 characters")
|
||||
|
||||
# List validations
|
||||
elif isinstance(value, list):
|
||||
if len(value) > 1000:
|
||||
raise ValidationError(f"Parameter '{key}' exceeds maximum size of 1000 items")
|
||||
|
||||
# Dictionary validations
|
||||
elif isinstance(value, dict):
|
||||
if len(value) > 100:
|
||||
raise ValidationError(f"Parameter '{key}' exceeds maximum size of 100 items")
|
||||
|
||||
# Type-specific validations
|
||||
if key == "user" and not isinstance(value, str):
|
||||
raise ValidationError(f"Parameter '{key}' must be a string")
|
||||
elif key in ["page", "limit", "page_size"] and not isinstance(value, int):
|
||||
raise ValidationError(f"Parameter '{key}' must be an integer")
|
||||
elif key == "files" and not isinstance(value, (list, dict)):
|
||||
raise ValidationError(f"Parameter '{key}' must be a list or dict")
|
||||
elif key == "rating" and value not in ["like", "dislike"]:
|
||||
raise ValidationError(f"Parameter '{key}' must be 'like' or 'dislike'")
|
||||
|
||||
def _log_request(self, method: str, url: str, **kwargs) -> None:
|
||||
"""Log request details."""
|
||||
self.logger.info(f"Making {method} request to {url}")
|
||||
if kwargs.get("json"):
|
||||
self.logger.debug(f"Request body: {kwargs['json']}")
|
||||
if kwargs.get("params"):
|
||||
self.logger.debug(f"Query params: {kwargs['params']}")
|
||||
|
||||
def _log_response(self, response: httpx.Response) -> None:
|
||||
"""Log response details."""
|
||||
self.logger.info(f"Received response: {response.status_code} ({len(response.content)} bytes)")
|
||||
1267
dify/sdks/python-client/dify_client/client.py
Normal file
1267
dify/sdks/python-client/dify_client/client.py
Normal file
File diff suppressed because it is too large
Load Diff
71
dify/sdks/python-client/dify_client/exceptions.py
Normal file
71
dify/sdks/python-client/dify_client/exceptions.py
Normal file
@@ -0,0 +1,71 @@
|
||||
"""Custom exceptions for the Dify client."""
|
||||
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
|
||||
class DifyClientError(Exception):
|
||||
"""Base exception for all Dify client errors."""
|
||||
|
||||
def __init__(self, message: str, status_code: int | None = None, response: Dict[str, Any] | None = None):
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
self.status_code = status_code
|
||||
self.response = response
|
||||
|
||||
|
||||
class APIError(DifyClientError):
|
||||
"""Raised when the API returns an error response."""
|
||||
|
||||
def __init__(self, message: str, status_code: int, response: Dict[str, Any] | None = None):
|
||||
super().__init__(message, status_code, response)
|
||||
self.status_code = status_code
|
||||
|
||||
|
||||
class AuthenticationError(DifyClientError):
|
||||
"""Raised when authentication fails."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class RateLimitError(DifyClientError):
|
||||
"""Raised when rate limit is exceeded."""
|
||||
|
||||
def __init__(self, message: str = "Rate limit exceeded", retry_after: int | None = None):
|
||||
super().__init__(message)
|
||||
self.retry_after = retry_after
|
||||
|
||||
|
||||
class ValidationError(DifyClientError):
|
||||
"""Raised when request validation fails."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class NetworkError(DifyClientError):
|
||||
"""Raised when network-related errors occur."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class TimeoutError(DifyClientError):
|
||||
"""Raised when request times out."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class FileUploadError(DifyClientError):
|
||||
"""Raised when file upload fails."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class DatasetError(DifyClientError):
|
||||
"""Raised when dataset operations fail."""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class WorkflowError(DifyClientError):
|
||||
"""Raised when workflow operations fail."""
|
||||
|
||||
pass
|
||||
396
dify/sdks/python-client/dify_client/models.py
Normal file
396
dify/sdks/python-client/dify_client/models.py
Normal file
@@ -0,0 +1,396 @@
|
||||
"""Response models for the Dify client with proper type hints."""
|
||||
|
||||
from typing import Optional, List, Dict, Any, Literal, Union
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
@dataclass
|
||||
class BaseResponse:
|
||||
"""Base response model."""
|
||||
|
||||
success: bool = True
|
||||
message: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class ErrorResponse(BaseResponse):
|
||||
"""Error response model."""
|
||||
|
||||
error_code: str | None = None
|
||||
details: Dict[str, Any] | None = None
|
||||
success: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class FileInfo:
|
||||
"""File information model."""
|
||||
|
||||
id: str
|
||||
name: str
|
||||
size: int
|
||||
mime_type: str
|
||||
url: str | None = None
|
||||
created_at: datetime | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class MessageResponse(BaseResponse):
|
||||
"""Message response model."""
|
||||
|
||||
id: str = ""
|
||||
answer: str = ""
|
||||
conversation_id: str | None = None
|
||||
created_at: int | None = None
|
||||
metadata: Dict[str, Any] | None = None
|
||||
files: List[Dict[str, Any]] | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class ConversationResponse(BaseResponse):
|
||||
"""Conversation response model."""
|
||||
|
||||
id: str = ""
|
||||
name: str = ""
|
||||
inputs: Dict[str, Any] | None = None
|
||||
status: str | None = None
|
||||
created_at: int | None = None
|
||||
updated_at: int | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class DatasetResponse(BaseResponse):
|
||||
"""Dataset response model."""
|
||||
|
||||
id: str = ""
|
||||
name: str = ""
|
||||
description: str | None = None
|
||||
permission: str | None = None
|
||||
indexing_technique: str | None = None
|
||||
embedding_model: str | None = None
|
||||
embedding_model_provider: str | None = None
|
||||
retrieval_model: Dict[str, Any] | None = None
|
||||
document_count: int | None = None
|
||||
word_count: int | None = None
|
||||
app_count: int | None = None
|
||||
created_at: int | None = None
|
||||
updated_at: int | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class DocumentResponse(BaseResponse):
|
||||
"""Document response model."""
|
||||
|
||||
id: str = ""
|
||||
name: str = ""
|
||||
data_source_type: str | None = None
|
||||
data_source_info: Dict[str, Any] | None = None
|
||||
dataset_process_rule_id: str | None = None
|
||||
batch: str | None = None
|
||||
position: int | None = None
|
||||
enabled: bool | None = None
|
||||
disabled_at: float | None = None
|
||||
disabled_by: str | None = None
|
||||
archived: bool | None = None
|
||||
archived_reason: str | None = None
|
||||
archived_at: float | None = None
|
||||
archived_by: str | None = None
|
||||
word_count: int | None = None
|
||||
hit_count: int | None = None
|
||||
doc_form: str | None = None
|
||||
doc_metadata: Dict[str, Any] | None = None
|
||||
created_at: float | None = None
|
||||
updated_at: float | None = None
|
||||
indexing_status: str | None = None
|
||||
completed_at: float | None = None
|
||||
paused_at: float | None = None
|
||||
error: str | None = None
|
||||
stopped_at: float | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class DocumentSegmentResponse(BaseResponse):
|
||||
"""Document segment response model."""
|
||||
|
||||
id: str = ""
|
||||
position: int | None = None
|
||||
document_id: str | None = None
|
||||
content: str | None = None
|
||||
answer: str | None = None
|
||||
word_count: int | None = None
|
||||
tokens: int | None = None
|
||||
keywords: List[str] | None = None
|
||||
index_node_id: str | None = None
|
||||
index_node_hash: str | None = None
|
||||
hit_count: int | None = None
|
||||
enabled: bool | None = None
|
||||
disabled_at: float | None = None
|
||||
disabled_by: str | None = None
|
||||
status: str | None = None
|
||||
created_by: str | None = None
|
||||
created_at: float | None = None
|
||||
indexing_at: float | None = None
|
||||
completed_at: float | None = None
|
||||
error: str | None = None
|
||||
stopped_at: float | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class WorkflowRunResponse(BaseResponse):
|
||||
"""Workflow run response model."""
|
||||
|
||||
id: str = ""
|
||||
workflow_id: str | None = None
|
||||
status: Literal["running", "succeeded", "failed", "stopped"] | None = None
|
||||
inputs: Dict[str, Any] | None = None
|
||||
outputs: Dict[str, Any] | None = None
|
||||
error: str | None = None
|
||||
elapsed_time: float | None = None
|
||||
total_tokens: int | None = None
|
||||
total_steps: int | None = None
|
||||
created_at: float | None = None
|
||||
finished_at: float | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class ApplicationParametersResponse(BaseResponse):
|
||||
"""Application parameters response model."""
|
||||
|
||||
opening_statement: str | None = None
|
||||
suggested_questions: List[str] | None = None
|
||||
speech_to_text: Dict[str, Any] | None = None
|
||||
text_to_speech: Dict[str, Any] | None = None
|
||||
retriever_resource: Dict[str, Any] | None = None
|
||||
sensitive_word_avoidance: Dict[str, Any] | None = None
|
||||
file_upload: Dict[str, Any] | None = None
|
||||
system_parameters: Dict[str, Any] | None = None
|
||||
user_input_form: List[Dict[str, Any]] | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class AnnotationResponse(BaseResponse):
|
||||
"""Annotation response model."""
|
||||
|
||||
id: str = ""
|
||||
question: str = ""
|
||||
answer: str = ""
|
||||
content: str | None = None
|
||||
created_at: float | None = None
|
||||
updated_at: float | None = None
|
||||
created_by: str | None = None
|
||||
updated_by: str | None = None
|
||||
hit_count: int | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class PaginatedResponse(BaseResponse):
|
||||
"""Paginated response model."""
|
||||
|
||||
data: List[Any] = field(default_factory=list)
|
||||
has_more: bool = False
|
||||
limit: int = 0
|
||||
total: int = 0
|
||||
page: int | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class ConversationVariableResponse(BaseResponse):
|
||||
"""Conversation variable response model."""
|
||||
|
||||
conversation_id: str = ""
|
||||
variables: List[Dict[str, Any]] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class FileUploadResponse(BaseResponse):
|
||||
"""File upload response model."""
|
||||
|
||||
id: str = ""
|
||||
name: str = ""
|
||||
size: int = 0
|
||||
mime_type: str = ""
|
||||
url: str | None = None
|
||||
created_at: float | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class AudioResponse(BaseResponse):
|
||||
"""Audio generation/response model."""
|
||||
|
||||
audio: str | None = None # Base64 encoded audio data or URL
|
||||
audio_url: str | None = None
|
||||
duration: float | None = None
|
||||
sample_rate: int | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class SuggestedQuestionsResponse(BaseResponse):
|
||||
"""Suggested questions response model."""
|
||||
|
||||
message_id: str = ""
|
||||
questions: List[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class AppInfoResponse(BaseResponse):
|
||||
"""App info response model."""
|
||||
|
||||
id: str = ""
|
||||
name: str = ""
|
||||
description: str | None = None
|
||||
icon: str | None = None
|
||||
icon_background: str | None = None
|
||||
mode: str | None = None
|
||||
tags: List[str] | None = None
|
||||
enable_site: bool | None = None
|
||||
enable_api: bool | None = None
|
||||
api_token: str | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class WorkspaceModelsResponse(BaseResponse):
|
||||
"""Workspace models response model."""
|
||||
|
||||
models: List[Dict[str, Any]] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class HitTestingResponse(BaseResponse):
|
||||
"""Hit testing response model."""
|
||||
|
||||
query: str = ""
|
||||
records: List[Dict[str, Any]] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class DatasetTagsResponse(BaseResponse):
|
||||
"""Dataset tags response model."""
|
||||
|
||||
tags: List[Dict[str, Any]] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class WorkflowLogsResponse(BaseResponse):
|
||||
"""Workflow logs response model."""
|
||||
|
||||
logs: List[Dict[str, Any]] = field(default_factory=list)
|
||||
total: int = 0
|
||||
page: int = 0
|
||||
limit: int = 0
|
||||
has_more: bool = False
|
||||
|
||||
|
||||
@dataclass
|
||||
class ModelProviderResponse(BaseResponse):
|
||||
"""Model provider response model."""
|
||||
|
||||
provider_name: str = ""
|
||||
provider_type: str = ""
|
||||
models: List[Dict[str, Any]] = field(default_factory=list)
|
||||
is_enabled: bool = False
|
||||
credentials: Dict[str, Any] | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class FileInfoResponse(BaseResponse):
|
||||
"""File info response model."""
|
||||
|
||||
id: str = ""
|
||||
name: str = ""
|
||||
size: int = 0
|
||||
mime_type: str = ""
|
||||
url: str | None = None
|
||||
created_at: int | None = None
|
||||
metadata: Dict[str, Any] | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class WorkflowDraftResponse(BaseResponse):
|
||||
"""Workflow draft response model."""
|
||||
|
||||
id: str = ""
|
||||
app_id: str = ""
|
||||
draft_data: Dict[str, Any] = field(default_factory=dict)
|
||||
version: int = 0
|
||||
created_at: int | None = None
|
||||
updated_at: int | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class ApiTokenResponse(BaseResponse):
|
||||
"""API token response model."""
|
||||
|
||||
id: str = ""
|
||||
name: str = ""
|
||||
token: str = ""
|
||||
description: str | None = None
|
||||
created_at: int | None = None
|
||||
last_used_at: int | None = None
|
||||
is_active: bool = True
|
||||
|
||||
|
||||
@dataclass
|
||||
class JobStatusResponse(BaseResponse):
|
||||
"""Job status response model."""
|
||||
|
||||
job_id: str = ""
|
||||
job_status: str = ""
|
||||
error_msg: str | None = None
|
||||
progress: float | None = None
|
||||
created_at: int | None = None
|
||||
updated_at: int | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class DatasetQueryResponse(BaseResponse):
|
||||
"""Dataset query response model."""
|
||||
|
||||
query: str = ""
|
||||
records: List[Dict[str, Any]] = field(default_factory=list)
|
||||
total: int = 0
|
||||
search_time: float | None = None
|
||||
retrieval_model: Dict[str, Any] | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class DatasetTemplateResponse(BaseResponse):
|
||||
"""Dataset template response model."""
|
||||
|
||||
template_name: str = ""
|
||||
display_name: str = ""
|
||||
description: str = ""
|
||||
category: str = ""
|
||||
icon: str | None = None
|
||||
config_schema: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
# Type aliases for common response types
|
||||
ResponseType = Union[
|
||||
BaseResponse,
|
||||
ErrorResponse,
|
||||
MessageResponse,
|
||||
ConversationResponse,
|
||||
DatasetResponse,
|
||||
DocumentResponse,
|
||||
DocumentSegmentResponse,
|
||||
WorkflowRunResponse,
|
||||
ApplicationParametersResponse,
|
||||
AnnotationResponse,
|
||||
PaginatedResponse,
|
||||
ConversationVariableResponse,
|
||||
FileUploadResponse,
|
||||
AudioResponse,
|
||||
SuggestedQuestionsResponse,
|
||||
AppInfoResponse,
|
||||
WorkspaceModelsResponse,
|
||||
HitTestingResponse,
|
||||
DatasetTagsResponse,
|
||||
WorkflowLogsResponse,
|
||||
ModelProviderResponse,
|
||||
FileInfoResponse,
|
||||
WorkflowDraftResponse,
|
||||
ApiTokenResponse,
|
||||
JobStatusResponse,
|
||||
DatasetQueryResponse,
|
||||
DatasetTemplateResponse,
|
||||
]
|
||||
Reference in New Issue
Block a user