# dify2anthropic **Repository Path**: pengfr/dify2anthropic ## Basic Information - **Project Name**: dify2anthropic - **Description**: No description available - **Primary Language**: Unknown - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-01-12 - **Last Updated**: 2026-01-24 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # dify2anthropic A Claude-to-Dify API adapter that translates Anthropic Claude API requests to Dify chat completion API calls. Acts as a proxy/adapter between Claude-compatible clients and Dify's OpenAI-compatible API. ## Features - **Claude API Compatibility**: Implements the Anthropic Claude `/v1/messages` endpoint - **Streaming Support**: Full Server-Sent Events (SSE) streaming support for real-time responses - **Authentication Bridging**: Extracts credentials from requests and forwards to Dify - **Thought Extraction**: Handles `` tags for reasoning/thought extraction - **Error Formatting**: Converts errors to Anthropic standard error format - **Chat Logging**: Optional conversation logging for debugging and analysis ## Installation ### From Gitee (Recommended) Install directly from the Gitee repository: ```bash pip install git+https://gitee.com/pengfr/dify2anthropic.git ``` ### From Source (Development Mode) Clone the repository and install in development mode: ```bash git clone https://gitee.com/pengfr/dify2anthropic.git cd dify2anthropic pip install -e . ``` ## Quick Start 1. **Install the package**: ```bash pip install git+https://gitee.com/pengfr/dify2anthropic.git ``` 2. **Configure the adapter**: ```bash # Create configuration file (recommended) cp .env.example ~/.dify2anthropic # Edit ~/.dify2anthropic with your Dify instance URL and credentials # Or set environment variables export DIFY_BASE_URL="https://your-dify-instance.com" export DIFY_CHAT_PATH="/api/chat/completions" export UPSTREAM_MODEL="DeepSeek-R1" export EXTRA_HEADERS_JSON='{"Origin":"https://your-dify-instance.com","Referer":"https://your-dify-instance.com/"}' ``` 3. **Start the adapter service**: ```bash # Using the command-line tool (recommended) dify2anthropic_service # With custom options: dify2anthropic_service --host 127.0.0.1 --port 8080 --reload # Show current configuration: dify2anthropic_service --show-config # Using uvicorn directly: uvicorn dify2anthropic.app:app --host 0.0.0.0 --port 8000 --reload ``` 4. **Configure your Claude client**: ```bash # Example using Claude client environment variables export ANTHROPIC_BASE_URL="http://127.0.0.1:8000" export ANTHROPIC_AUTH_TOKEN="your_cookie_string_here" # Your Dify cookie/token export ANTHROPIC_API_KEY="$ANTHROPIC_AUTH_TOKEN" # Compatible with official Anthropic SDK export ANTHROPIC_MODEL="claude-3-5-sonnet-20241022" ``` **For Claude Code CLI users**: Create `~/.claude/settings.json` as described in the Configuration section below for seamless integration. ## Configuration **Configuration Hierarchy Overview**: | Component | Configuration Files | Purpose | Example Variables | |-----------|---------------------|---------|-------------------| | **Adapter Server** | `~/.dify2anthropic`, `.env`, or environment variables | Configure the adapter server to connect to Dify | `DIFY_BASE_URL`, `DIFY_CHAT_PATH`, `UPSTREAM_MODEL` | | **Claude Clients** | `~/.claude/settings.json`, `claude.sh`, or environment variables | Configure Claude clients to connect to the adapter | `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_BASE_URL`, `ANTHROPIC_MODEL` | **Key Separation**: Adapter configuration (how the adapter connects to Dify) is separate from client configuration (how Claude clients connect to the adapter). ### Adapter Environment Variables Create a `.env` file or export variables directly: | Variable | Description | Default | |----------|-------------|---------| | `DIFY_BASE_URL` | Dify service URL (no trailing slash) | *Required* | | `DIFY_CHAT_PATH` | Dify chat completion path | `/api/chat/completions` | | `UPSTREAM_MODEL` | Model name for upstream requests | `DeepSeek-R1` | | `EXTRA_HEADERS_JSON` | Extra headers for upstream (JSON) | `{}` | | `EXTRA_COOKIES_JSON` | Extra cookies for upstream (JSON) | `{}` | | `FORCE_MODEL` | Output model name for clients | `claude-3-5-sonnet-20241022` | | `ANTHROPIC_VERSION_DEFAULT` | Anthropic API version | `2023-06-01` | | `DEFAULT_DIFY_USER` | Default Dify "user" field | `anthropic-adapter` | | `UPSTREAM_TIMEOUT` | Upstream timeout in seconds | `120` | | `LOG_DIR` | Chat logging directory (empty to disable) | `""` | | `DIFY_STOP_PATH_TMPL` | Dify stop task endpoint template | `/api/chat-messages/{task_id}/stop` | ### Example `.env` File ```env DIFY_BASE_URL=https://your-dify-instance.com DIFY_CHAT_PATH=/api/chat/completions UPSTREAM_MODEL=DeepSeek-R1 EXTRA_HEADERS_JSON='{"Origin":"https://your-dify-instance.com","Referer":"https://your-dify-instance.com/"}' FORCE_MODEL=claude-3-5-sonnet-20241022 ``` ### Claude Code CLI Configuration For seamless integration with Claude Code CLI, create a configuration file at `~/.claude/settings.json`: ```json { "env": { "ANTHROPIC_AUTH_TOKEN": "your_cookie_string_here", "ANTHROPIC_BASE_URL": "http://127.0.0.1:8000", "API_TIMEOUT_MS": "3000000", "ANTHROPIC_MODEL": "DeepSeek-reasoner", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": 1, "CLAUDE_AUTOCOMPACT_PCT_OVERRIDE": 90 } } ``` **Note**: - Replace `"your_cookie_string_here"` with your actual Dify cookie/token string - `ANTHROPIC_MODEL` can be set to either `"DeepSeek-reasoner"` or `"claude-3-5-sonnet-20241022"` based on your preference - The `claude.sh` file in the repository provides an alternative shell script configuration approach ### Debugging and Troubleshooting The adapter provides detailed debugging output to help diagnose configuration and connectivity issues: | Environment Variable | Purpose | Example | |---------------------|---------|---------| | `DIFY2ANTHROPIC_DEBUG` | Enable detailed debug output for configuration parsing | `DIFY2ANTHROPIC_DEBUG=1 dify2anthropic_service --show-config` | | `LOG_DIR` | Directory for chat conversation logs | `LOG_DIR=/path/to/logs` | **Debugging Configuration Issues**: ```bash # Enable debug output to see configuration parsing details DIFY2ANTHROPIC_DEBUG=1 dify2anthropic_service --show-config # This will display: # - Raw configuration file content # - Processed content after export keyword removal # - Parsed environment variables # - Any parsing errors or warnings ``` **Common Issues and Solutions**: 1. **Configuration Parsing Errors**: - **Symptom**: "Python-dotenv could not parse statement starting at line 1" - **Solution**: The adapter now supports shell-style `export` keywords and common typos like `exprt`. Debug output will show the parsing process. 2. **500 Internal Server Errors**: - **Symptom**: `/v1/messages` endpoints return 500 errors - **Check**: Verify Dify service is accessible: `curl https://your-dify-instance.com/health` - **Check**: Ensure authentication token/cookie is valid and properly passed in `Authorization: Bearer` header - **Check**: Review server logs for detailed error messages 3. **Streaming Connection Issues**: - **Symptom**: Streaming responses stop prematurely - **Check**: Ensure upstream timeout (`UPSTREAM_TIMEOUT`) is sufficient (default: 120 seconds) - **Check**: Verify network connectivity to Dify instance **Logging**: - Set `LOG_DIR` to enable conversation logging for debugging and analysis - Logs are stored as JSON files with timestamps and user identifiers ## API Endpoints The adapter provides the following endpoints: - `GET /healthz` - Health check endpoint - `GET /v1/models` - Model listing (returns hardcoded Claude model name) - `POST /v1/messages` - Main Claude-compatible endpoint (supports streaming and non-streaming) ### Example API Usage ```bash # Health check curl http://localhost:8000/healthz # List models curl http://localhost:8000/v1/models # Send a message (blocking) curl http://localhost:8000/v1/messages \ -H "Authorization: Bearer your_cookie_string" \ -H "Content-Type: application/json" \ -d '{ "model": "claude-3-5-sonnet-20241022", "messages": [{"role": "user", "content": "Hello, world!"}], "max_tokens": 1024 }' # Send a message (streaming) curl http://localhost:8000/v1/messages \ -H "Authorization: Bearer your_cookie_string" \ -H "Content-Type: application/json" \ -d '{ "model": "claude-3-5-sonnet-20241022", "messages": [{"role": "user", "content": "Hello, world!"}], "max_tokens": 1024, "stream": true }' \ -N ``` ## Module Architecture The application is modularized into focused modules: | Module | Responsibility | |--------|----------------| | `main.py` | FastAPI app entry point (routes only) | | `dify2anthropic/app.py` | FastAPI application instance for CLI | | `dify2anthropic/cli.py` | Command-line interface for service management | | `dify2anthropic/config.py` | Configuration and environment variables | | `dify2anthropic/logging_utils.py` | Logging setup and sensitive data redaction | | `dify2anthropic/auth.py` | Cookie parsing and upstream headers/cookies | | `dify2anthropic/claude_parser.py` | Claude message format conversion | | `dify2anthropic/dify_client.py` | Dify API client (SSE, streaming/blocking chat) | | `dify2anthropic/handlers.py` | Main `/v1/messages` endpoint handler | | `dify2anthropic/chat_logger.py` | Conversation logging for debugging and analysis | | `dify2anthropic/thought_extraction.py` | Thought content extraction utilities | | `dify2anthropic/sse_helpers.py` | Anthropic SSE helper functions | ## Development ### Setting Up Development Environment ```bash git clone https://gitee.com/pengfr/dify2anthropic.git cd dify2anthropic python -m venv .venv source .venv/bin/activate pip install -e .[dev] ``` ### Running Tests Two test suites are available: 1. **Python-based comprehensive test**: ```bash python adapter_smoketest.py ``` 2. **Bash-based curl test**: ```bash ./test_main.sh ``` ## License MIT License - see [LICENSE](LICENSE) file for details. ## Contributing Contributions are welcome! Please feel free to submit a Pull Request. 1. Fork the repository 2. Create a feature branch 3. Make your changes 4. Add tests if applicable 5. Ensure all tests pass 6. Submit a pull request