# Dify-OAPI
[](https://badge.fury.io/py/dify-oapi2)
[](https://www.python.org/downloads/)
[](https://opensource.org/licenses/MIT)
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, Completion, Knowledge Base (39 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
## 📦 Installation
```bash
pip install dify-oapi2
```
**Requirements**: Python 3.10+
**Dependencies**:
- `pydantic` (>=1.10,<3.0.0) - Data validation and settings management
- `httpx` (>=0.24,<1.0) - Modern HTTP client
## 🚀 Quick Start
### Basic Chat Example
```python
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
```python
# 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
```python
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
- Interactive conversations with AI assistants
- File upload support (images, documents)
- Conversation and message history management
- Streaming and blocking response modes
### Completion API
- Text generation and completion
- Custom input parameters
- Streaming support
### Knowledge Base API (39 APIs)
- **Dataset Management**: CRUD operations for datasets
- **Document Management**: Upload, process, and manage documents
- **Segment Management**: Fine-grained content segmentation
- **Metadata & Tags**: Custom metadata and knowledge type tags
- **Retrieval**: Advanced search and retrieval functionality
### Workflow API
- Automated workflow execution
- Parameter configuration
- Status monitoring
### Dify Core API
- Essential Dify service functionality
## 💡 Examples
Explore comprehensive examples in the [examples directory](./examples):
### Chat Examples
- [**Blocking Response**](./examples/chat/blocking_response.py) - Standard chat interactions
- [**Streaming Response**](./examples/chat/streaming_response.py) - Real-time streaming chat
- [**Conversation Management**](./examples/chat/conversation_management.py) - Managing chat history
### Completion Examples
- [**Basic Completion**](./examples/completion/basic_completion.py) - Text generation
### Knowledge Base Examples
- [**List Datasets**](./examples/knowledge_base/list_datasets.py) - Dataset management
For detailed examples and usage patterns, see the [examples README](./examples/README.md).
## 🛠️ Development
### Prerequisites
- Python 3.10+
- Poetry
### Setup
```bash
# 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
```bash
# 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
```bash
# 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
```bash
# 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_base/ # Knowledge Base API (39 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**](./docs/overview.md) - Architecture and technical details
- [**Knowledge Base APIs**](./docs/datasets/apis.md) - Complete dataset API documentation
- [**Examples**](./examples/README.md) - Usage examples and patterns
## 🤝 Contributing
Contributions are welcome! Please:
1. Fork the repository
2. Create a feature branch
3. Make your changes with tests
4. Ensure code quality (`ruff format`, `ruff check`, `mypy`)
5. Submit a pull request
## 📄 License
This project is licensed under the MIT License - see the [LICENSE](./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](./LICENSE) file for details.
---
**Keywords**: dify, nlp, ai, language-processing
Raw data
{
"_id": null,
"home_page": "https://github.com/nodite/dify-oapi2",
"name": "dify-oapi2",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.10",
"maintainer_email": null,
"keywords": "dify, nlp, ai, language-processing",
"author": "Oscaner Miao",
"author_email": "oscaner1997@163.com",
"download_url": "https://files.pythonhosted.org/packages/9a/06/7d55831f1cabbda48dfee23c583ddff637cdefe1f5e4560e596c73b07164/dify_oapi2-0.1.1.tar.gz",
"platform": null,
"description": "# Dify-OAPI\n\n[](https://badge.fury.io/py/dify-oapi2)\n[](https://www.python.org/downloads/)\n[](https://opensource.org/licenses/MIT)\n\nA 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.\n\n> This project is based on https://github.com/QiMington/dify-oapi, with refactoring and support for the latest Dify API.\n\n## \u2728 Features\n\n- **Multiple API Services**: Chat, Completion, Knowledge Base (39 APIs), Workflow, and Core Dify APIs\n- **Builder Pattern**: Fluent, chainable interface for constructing requests\n- **Sync & Async Support**: Both synchronous and asynchronous operations\n- **Streaming Responses**: Real-time streaming for chat and completion\n- **Type Safety**: Comprehensive type hints with Pydantic validation\n- **File Upload**: Support for images and documents\n- **Modern HTTP Client**: Built on httpx for reliable API communication\n\n## \ud83d\udce6 Installation\n\n```bash\npip install dify-oapi2\n```\n\n**Requirements**: Python 3.10+\n\n**Dependencies**:\n- `pydantic` (>=1.10,<3.0.0) - Data validation and settings management\n- `httpx` (>=0.24,<1.0) - Modern HTTP client\n\n## \ud83d\ude80 Quick Start\n\n### Basic Chat Example\n\n```python\nfrom dify_oapi.api.chat.v1.model.chat_request import ChatRequest\nfrom dify_oapi.api.chat.v1.model.chat_request_body import ChatRequestBody\nfrom dify_oapi.client import Client\nfrom dify_oapi.core.model.request_option import RequestOption\n\n# Initialize client\nclient = Client.builder().domain(\"https://api.dify.ai\").build()\n\n# Build request\nreq_body = (\n ChatRequestBody.builder()\n .inputs({})\n .query(\"What can Dify API do?\")\n .response_mode(\"blocking\")\n .user(\"user-123\")\n .build()\n)\n\nreq = ChatRequest.builder().request_body(req_body).build()\nreq_option = RequestOption.builder().api_key(\"your-api-key\").build()\n\n# Execute request\nresponse = client.chat.v1.chat.chat(req, req_option, False)\nprint(response.answer)\n```\n\n### Streaming Chat Example\n\n```python\n# Enable streaming for real-time responses\nreq_body = (\n ChatRequestBody.builder()\n .query(\"Tell me a story\")\n .response_mode(\"streaming\")\n .user(\"user-123\")\n .build()\n)\n\nreq = ChatRequest.builder().request_body(req_body).build()\nresponse = client.chat.v1.chat.chat(req, req_option, True)\n\n# Process streaming response\nfor chunk in response:\n print(chunk, end=\"\", flush=True)\n```\n\n### Async Support\n\n```python\nimport asyncio\n\nasync def async_chat():\n response = await client.chat.v1.chat.achat(req, req_option, False)\n print(response.answer)\n\nasyncio.run(async_chat())\n```\n\n## \ud83d\udd27 API Services\n\n### Chat API\n- Interactive conversations with AI assistants\n- File upload support (images, documents)\n- Conversation and message history management\n- Streaming and blocking response modes\n\n### Completion API\n- Text generation and completion\n- Custom input parameters\n- Streaming support\n\n### Knowledge Base API (39 APIs)\n- **Dataset Management**: CRUD operations for datasets\n- **Document Management**: Upload, process, and manage documents\n- **Segment Management**: Fine-grained content segmentation\n- **Metadata & Tags**: Custom metadata and knowledge type tags\n- **Retrieval**: Advanced search and retrieval functionality\n\n### Workflow API\n- Automated workflow execution\n- Parameter configuration\n- Status monitoring\n\n### Dify Core API\n- Essential Dify service functionality\n\n## \ud83d\udca1 Examples\n\nExplore comprehensive examples in the [examples directory](./examples):\n\n### Chat Examples\n- [**Blocking Response**](./examples/chat/blocking_response.py) - Standard chat interactions\n- [**Streaming Response**](./examples/chat/streaming_response.py) - Real-time streaming chat\n- [**Conversation Management**](./examples/chat/conversation_management.py) - Managing chat history\n\n### Completion Examples\n- [**Basic Completion**](./examples/completion/basic_completion.py) - Text generation\n\n### Knowledge Base Examples\n- [**List Datasets**](./examples/knowledge_base/list_datasets.py) - Dataset management\n\nFor detailed examples and usage patterns, see the [examples README](./examples/README.md).\n\n## \ud83d\udee0\ufe0f Development\n\n### Prerequisites\n- Python 3.10+\n- Poetry\n\n### Setup\n\n```bash\n# Clone repository\ngit clone https://github.com/nodite/dify-oapi2.git\ncd dify-oapi\n\n# Setup development environment (installs dependencies and pre-commit hooks)\nmake dev-setup\n```\n\n### Code Quality Tools\n\nThis project uses modern Python tooling:\n\n- **Ruff**: Fast Python linter and formatter\n- **MyPy**: Static type checking\n- **Pre-commit**: Git hooks for code quality\n- **Pylint**: Additional code analysis\n\n```bash\n# Format code\nmake format\n\n# Lint code\nmake lint\n\n# Fix linting issues\nmake fix\n\n# Run all checks (lint + type check)\nmake check\n\n# Install pre-commit hooks\nmake install-hooks\n\n# Run pre-commit hooks manually\nmake pre-commit\n```\n\n### Testing\n\n```bash\n# Set environment variables\nexport DOMAIN=\"https://api.dify.ai\"\nexport CHAT_KEY=\"your-api-key\"\n\n# Run tests\nmake test\n\n# Run tests with coverage\nmake test-cov\n```\n\n### Build & Publish\n\n```bash\n# Configure PyPI tokens (one-time setup)\npoetry config http-basic.testpypi __token__ <your-testpypi-token>\npoetry config http-basic.pypi __token__ <your-pypi-token>\n\n# Build package\nmake build\n\n# Publish to TestPyPI (for testing)\nmake publish-test\n\n# Publish to PyPI (maintainers only)\nmake publish\n```\n\n### Project Structure\n\n```\ndify-oapi/\n\u251c\u2500\u2500 dify_oapi/ # Main SDK package\n\u2502 \u251c\u2500\u2500 api/ # API service modules\n\u2502 \u2502 \u251c\u2500\u2500 chat/ # Chat API\n\u2502 \u2502 \u251c\u2500\u2500 completion/ # Completion API\n\u2502 \u2502 \u251c\u2500\u2500 dify/ # Core Dify API\n\u2502 \u2502 \u251c\u2500\u2500 knowledge_base/ # Knowledge Base API (39 APIs)\n\u2502 \u2502 \u2514\u2500\u2500 workflow/ # Workflow API\n\u2502 \u251c\u2500\u2500 core/ # Core functionality\n\u2502 \u2502 \u251c\u2500\u2500 http/ # HTTP transport layer\n\u2502 \u2502 \u251c\u2500\u2500 model/ # Base models\n\u2502 \u2502 \u2514\u2500\u2500 utils/ # Utilities\n\u2502 \u2514\u2500\u2500 client.py # Main client interface\n\u251c\u2500\u2500 docs/ # Documentation\n\u251c\u2500\u2500 examples/ # Usage examples\n\u251c\u2500\u2500 tests/ # Test suite\n\u2514\u2500\u2500 pyproject.toml # Project configuration\n```\n\n## \ud83d\udcd6 Documentation\n\n- [**Project Overview**](./docs/overview.md) - Architecture and technical details\n- [**Knowledge Base APIs**](./docs/datasets/apis.md) - Complete dataset API documentation\n- [**Examples**](./examples/README.md) - Usage examples and patterns\n\n## \ud83e\udd1d Contributing\n\nContributions are welcome! Please:\n\n1. Fork the repository\n2. Create a feature branch\n3. Make your changes with tests\n4. Ensure code quality (`ruff format`, `ruff check`, `mypy`)\n5. Submit a pull request\n\n## \ud83d\udcc4 License\n\nThis project is licensed under the MIT License - see the [LICENSE](./LICENSE) file for details.\n\n## \ud83d\udd17 Links\n\n- **PyPI Package**: https://pypi.org/project/dify-oapi2/\n- **Source Code**: https://github.com/nodite/dify-oapi2\n- **Dify Platform**: https://dify.ai/\n- **Dify API Docs**: https://docs.dify.ai/\n\n## \ud83d\udcc4 License\n\nMIT License - see [LICENSE](./LICENSE) file for details.\n\n---\n\n**Keywords**: dify, nlp, ai, language-processing\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "A package for interacting with the Dify Service-API",
"version": "0.1.1",
"project_urls": {
"Homepage": "https://github.com/nodite/dify-oapi2",
"Source": "https://github.com/nodite/dify-oapi2"
},
"split_keywords": [
"dify",
" nlp",
" ai",
" language-processing"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "8f82e91f11a3a0a4aae285143e1de4dd5a6187b9eca128c4eaae8f663452f592",
"md5": "7494d7973c6b8f76fa050b97745b8a01",
"sha256": "abafeb1c25f756e27b30f795b93176b35daead591e58a8a11eebd7c5377653e1"
},
"downloads": -1,
"filename": "dify_oapi2-0.1.1-py3-none-any.whl",
"has_sig": false,
"md5_digest": "7494d7973c6b8f76fa050b97745b8a01",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.10",
"size": 137001,
"upload_time": "2025-08-13T06:03:41",
"upload_time_iso_8601": "2025-08-13T06:03:41.086377Z",
"url": "https://files.pythonhosted.org/packages/8f/82/e91f11a3a0a4aae285143e1de4dd5a6187b9eca128c4eaae8f663452f592/dify_oapi2-0.1.1-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "9a067d55831f1cabbda48dfee23c583ddff637cdefe1f5e4560e596c73b07164",
"md5": "94d08dba58a409ff736e47e5549f6542",
"sha256": "166532297b4a3131cfb832adb992803577d958af5b685311b7badfac9f4db29b"
},
"downloads": -1,
"filename": "dify_oapi2-0.1.1.tar.gz",
"has_sig": false,
"md5_digest": "94d08dba58a409ff736e47e5549f6542",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.10",
"size": 45093,
"upload_time": "2025-08-13T06:03:42",
"upload_time_iso_8601": "2025-08-13T06:03:42.423968Z",
"url": "https://files.pythonhosted.org/packages/9a/06/7d55831f1cabbda48dfee23c583ddff637cdefe1f5e4560e596c73b07164/dify_oapi2-0.1.1.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-08-13 06:03:42",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "nodite",
"github_project": "dify-oapi2",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "dify-oapi2"
}