Skip to main content

A package for interacting with the Dify Service-API

Project description

Dify-OAPI

PyPI version Python 3.10+ License: 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

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

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

  • Interactive conversations with AI assistants
  • File upload support (images, documents)
  • Conversation and message history management
  • Streaming and blocking response modes

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 (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:

Chat Examples

Completion Examples

Knowledge Base Examples

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_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

๐Ÿค 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 file for details.

๐Ÿ”— Links

๐Ÿ“„ License

MIT License - see LICENSE file for details.


Keywords: dify, nlp, ai, language-processing

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

dify_oapi2-0.3.0.tar.gz (60.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

dify_oapi2-0.3.0-py3-none-any.whl (187.3 kB view details)

Uploaded Python 3

File details

Details for the file dify_oapi2-0.3.0.tar.gz.

File metadata

  • Download URL: dify_oapi2-0.3.0.tar.gz
  • Upload date:
  • Size: 60.6 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

Hashes for dify_oapi2-0.3.0.tar.gz
Algorithm Hash digest
SHA256 e34662f88dc6e08019bd4fdc415e630c509e554adb9c00afe23ac7ed992eca2f
MD5 236bf689d8c2ddcbda784e5b69ea8a92
BLAKE2b-256 1a6e0f52121c88dc55d9b6669fc17f6d967a4418a3519569664476a2aa86b5cf

See more details on using hashes here.

File details

Details for the file dify_oapi2-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: dify_oapi2-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 187.3 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

Hashes for dify_oapi2-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 81f0128d75abb145d7b7f79dbb14280674a32b1a5113cb092e0f0a62fc24f807
MD5 751996e8c401d3fa53d7c5443f749ca2
BLAKE2b-256 84004e4dab9f0a457c9e32cd856ceec2a2b3d3aa62b8f62aa6e8cc812aae950e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page