A package for interacting with the Dify Service-API
Project description
Dify-OAPI
A Python SDK for interacting with the Dify Service-API. This library provides a fluent, type-safe interface for building AI-powered applications using Dify's API services including chat, completion, knowledge base, and workflow features.
This project is based on https://github.com/QiMington/dify-oapi, with refactoring and support for the latest Dify API.
โจ Features
- Multiple API Services: Chat (22 APIs), Completion (15 APIs), Knowledge Base (33 APIs), Chatflow (17 APIs), Workflow, and Core Dify APIs
- Builder Pattern: Fluent, chainable interface for constructing requests
- Sync & Async Support: Both synchronous and asynchronous operations
- Streaming Responses: Real-time streaming for chat and completion
- Type Safety: Comprehensive type hints with Pydantic validation
- File Upload: Support for images and documents
- Modern HTTP Client: Built on httpx for reliable API communication
- Connection Pool Optimization: Efficient TCP connection reuse to reduce resource overhead
๐ฆ Installation
pip install dify-oapi2
Requirements: Python 3.10+
Dependencies:
pydantic(>=1.10,<3.0.0) - Data validation and settings managementhttpx(>=0.24,<1.0) - Modern HTTP client
๐ Quick Start
Basic Chat Example
from dify_oapi.api.chat.v1.model.chat_request import ChatRequest
from dify_oapi.api.chat.v1.model.chat_request_body import ChatRequestBody
from dify_oapi.client import Client
from dify_oapi.core.model.request_option import RequestOption
# Initialize client
client = Client.builder().domain("https://api.dify.ai").build()
# Build request
req_body = (
ChatRequestBody.builder()
.inputs({})
.query("What can Dify API do?")
.response_mode("blocking")
.user("user-123")
.build()
)
req = ChatRequest.builder().request_body(req_body).build()
req_option = RequestOption.builder().api_key("your-api-key").build()
# Execute request
response = client.chat.v1.chat.chat(req, req_option, False)
print(response.answer)
Streaming Chat Example
# Enable streaming for real-time responses
req_body = (
ChatRequestBody.builder()
.query("Tell me a story")
.response_mode("streaming")
.user("user-123")
.build()
)
req = ChatRequest.builder().request_body(req_body).build()
response = client.chat.v1.chat.chat(req, req_option, True)
# Process streaming response
for chunk in response:
print(chunk, end="", flush=True)
Async Support
import asyncio
async def async_chat():
response = await client.chat.v1.chat.achat(req, req_option, False)
print(response.answer)
asyncio.run(async_chat())
๐ง API Services
Chat API (22 APIs)
- Chat Messages: Interactive conversations with AI assistants (3 APIs)
- File Management: Upload and manage images and documents (1 API)
- Feedback Management: Collect and analyze user feedback (2 APIs)
- Conversation Management: Complete conversation lifecycle management (5 APIs)
- Audio Processing: Speech-to-text and text-to-speech capabilities (2 APIs)
- Application Information: App configuration and metadata retrieval (4 APIs)
- Annotation Management: Create and manage annotations with reply settings (6 APIs)
- Streaming Support: Real-time streaming for chat and completion
- Type Safety: Comprehensive type hints with strict Literal types
Completion API (15 APIs)
- Message Processing: Send messages and control responses
- Annotation Management: Create, update, and manage annotations
- Audio Processing: Text-to-audio conversion
- Feedback System: Collect and analyze user feedback
- File Upload: Support for document and media files
- Application Info: Configuration and metadata retrieval
Knowledge Base API (33 APIs)
- Dataset Management: 6 APIs for dataset CRUD operations and content retrieval
- Document Management: 10 APIs for document upload, processing, and management
- Segment Management: 5 APIs for fine-grained content segmentation
- Child Chunks Management: 4 APIs for sub-segment management
- Tag Management: 7 APIs for metadata and knowledge type tags
- Model Management: 1 API for embedding model information
Chatflow API (17 APIs)
- Advanced Chat: 3 APIs for enhanced chat functionality with workflow events
- File Management: 1 API for multimodal file upload and processing
- Feedback System: 2 APIs for comprehensive feedback collection and analysis
- Conversation Management: 5 APIs for complete conversation lifecycle management
- TTS Integration: 2 APIs for speech-to-text and text-to-speech capabilities
- Application Configuration: 4 APIs for app settings and metadata management
- Annotation System: 6 APIs for annotation management and reply settings
- Streaming Support: Real-time streaming with comprehensive event handling
- Type Safety: Strict Literal types for all predefined values
Workflow API
- Automated workflow execution
- Parameter configuration
- Status monitoring
Dify Core API
- Essential Dify service functionality
๐ก Examples
Explore comprehensive examples in the examples directory:
Chat Examples
- Chat Messages - Send messages, stop generation, get suggestions
- File Management - Upload and manage files
- Feedback Management - Submit and retrieve feedback
- Conversation Management - Complete conversation operations
- Audio Processing - Speech-to-text and text-to-speech
- Application Information - App configuration and settings
- Annotation Management - Annotation CRUD and reply settings
Completion Examples
- Basic Completion - Text generation
Knowledge Base Examples
- Dataset Management - Complete dataset operations
- Document Processing - File upload and text processing
- Content Organization - Segment and chunk management
- Tag Management - Metadata and tagging system
Chatflow Examples
- Advanced Chat - Enhanced chat with streaming and workflow events
- File Operations - Multimodal file upload and processing
- Feedback Management - Comprehensive feedback collection
- Conversation Management - Complete conversation operations
- TTS Operations - Speech-to-text and text-to-speech
- Application Configuration - App settings and metadata
- Annotation Management - Annotation CRUD and reply settings
For detailed examples and usage patterns, see the examples README.
๐ ๏ธ Development
Prerequisites
- Python 3.10+
- Poetry
Setup
# Clone repository
git clone https://github.com/nodite/dify-oapi2.git
cd dify-oapi
# Setup development environment (installs dependencies and pre-commit hooks)
make dev-setup
Code Quality Tools
This project uses modern Python tooling:
- Ruff: Fast Python linter and formatter
- MyPy: Static type checking
- Pre-commit: Git hooks for code quality
- Pylint: Additional code analysis
# Format code
make format
# Lint code
make lint
# Fix linting issues
make fix
# Run all checks (lint + type check)
make check
# Install pre-commit hooks
make install-hooks
# Run pre-commit hooks manually
make pre-commit
Testing
# Set environment variables
export DOMAIN="https://api.dify.ai"
export CHAT_KEY="your-api-key"
# Run tests
make test
# Run tests with coverage
make test-cov
Build & Publish
# Configure PyPI tokens (one-time setup)
poetry config http-basic.testpypi __token__ <your-testpypi-token>
poetry config http-basic.pypi __token__ <your-pypi-token>
# Build package
make build
# Publish to TestPyPI (for testing)
make publish-test
# Publish to PyPI (maintainers only)
make publish
Project Structure
dify-oapi/
โโโ dify_oapi/ # Main SDK package
โ โโโ api/ # API service modules
โ โ โโโ chat/ # Chat API
โ โ โโโ completion/ # Completion API
โ โ โโโ dify/ # Core Dify API
โ โ โโโ knowledge/ # Knowledge Base API (33 APIs)
โ โ โโโ chatflow/ # Chatflow API (17 APIs)
โ โ โโโ workflow/ # Workflow API
โ โโโ core/ # Core functionality
โ โ โโโ http/ # HTTP transport layer
โ โ โโโ model/ # Base models
โ โ โโโ utils/ # Utilities
โ โโโ client.py # Main client interface
โโโ docs/ # Documentation
โโโ examples/ # Usage examples
โโโ tests/ # Test suite
โโโ pyproject.toml # Project configuration
๐ Documentation
- Project Overview - Architecture and technical details
- TCP Connection Optimization - Connection pool configuration and performance tuning
- Completion APIs - Complete completion API documentation
- Knowledge Base APIs - Complete knowledge base API documentation
- Examples - Usage examples and patterns
๐ค Contributing
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Make your changes with tests
- Ensure code quality (
ruff format,ruff check,mypy) - Submit a pull request
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Links
- PyPI Package: https://pypi.org/project/dify-oapi2/
- Source Code: https://github.com/nodite/dify-oapi2
- Dify Platform: https://dify.ai/
- Dify API Docs: https://docs.dify.ai/
๐ License
MIT License - see LICENSE file for details.
Keywords: dify, nlp, ai, language-processing
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file dify_oapi2-0.5.0.tar.gz.
File metadata
- Download URL: dify_oapi2-0.5.0.tar.gz
- Upload date:
- Size: 94.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.1.4 CPython/3.11.13 Linux/6.11.0-1018-azure
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
69a5ff391e10e44e915f0fc82c409b329bcb61bbae38ed70bdbe8483709ace66
|
|
| MD5 |
d20e1fb66f4a3c92521382cd6e937508
|
|
| BLAKE2b-256 |
03390fc87842ad1e078d30e76d0bed2e81dfd2e3b2f1d29cdddce49a304ce51c
|
File details
Details for the file dify_oapi2-0.5.0-py3-none-any.whl.
File metadata
- Download URL: dify_oapi2-0.5.0-py3-none-any.whl
- Upload date:
- Size: 269.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.1.4 CPython/3.11.13 Linux/6.11.0-1018-azure
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f39cac5d06f37779ec650ed2143f2361f1bf94601e3067fd5525f55510ca544f
|
|
| MD5 |
71ce2ced952d5536c81646ea2dfdc6b1
|
|
| BLAKE2b-256 |
1b52f228d916d3b52f9f10712bb7d018659a4c013c074d7a019ab926ceb97ae3
|