PHP code example of happyphper / dify

1. Go to this page and download the library: Download happyphper/dify library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

happyphper / dify example snippets




declare(strict_types=1);

use function Hyperf\Support\env;

return [
    // Base URL for Open API
    'base_url' => env('DIFY_BASE_URL', 'https://api.dify.ai/v1'),

    // Dataset API key
    'dataset_key' => env('DIFY_DATASET_KEY', ''),

    // Workflow API keys (for future releases)
    'workflow_keys' => [
        // Default key
        'default' => env('DIFY_WORKFLOW_API_KEY')

        // You can add more keys with custom names if needed
    ],

    // Enable debug mode
    'debug' => (bool)env('DIFY_DEBUG', false),

    // Text splitter configuration
    'text_splitter' => [
        'type' => env('DIFY_TEXT_SPLITTER_TYPE', 'chunk'),
        'chunk_size' => (int)env('DIFY_TEXT_SPLITTER_CHUNK_SIZE', 1000),
        'chunk_overlap' => (int)env('DIFY_TEXT_SPLITTER_CHUNK_OVERLAP', 200),
    ],

    // Indexing technique
    'indexing_technique' => env('DIFY_INDEXING_TECHNIQUE', 'high_quality'),

    /**
     * Console credentials for non-public API endpoints
     */
    'console' => [
        'enable' => env('DIFY_CONSOLE_ENABLE', false),
        'email' => env('DIFY_CONSOLE_EMAIL', '[email protected]'),
        'password' => env('DIFY_CONSOLE_PASSWORD', '!Qq123123'),
    ],

    /**
     * Cache configuration
     */
    'cache' => [
        // Cache driver: file, redis
        'driver' => env('DIFY_CACHE_DRIVER', 'file'),

        // Cache prefix
        'prefix' => env('DIFY_CACHE_PREFIX', 'dify_'),

        // Default cache TTL (seconds)
        'ttl' => (int)env('DIFY_CACHE_TTL', 86400), // Default 24 hours

        // File cache configuration
        'file' => [
            // Cache directory, defaults to dify_cache in the system temp directory
            'directory' => env('DIFY_CACHE_FILE_DIRECTORY', sys_get_temp_dir() . '/dify_cache'),
        ],

        // Redis cache configuration
        'redis' => [
            'host' => env('DIFY_CACHE_REDIS_HOST', '127.0.0.1'),
            'port' => (int)env('DIFY_CACHE_REDIS_PORT', 6379),
            'password' => env('DIFY_CACHE_REDIS_PASSWORD', null),
            'database' => (int)env('DIFY_CACHE_REDIS_DATABASE', 0),
            'timeout' => (float)env('DIFY_CACHE_REDIS_TIMEOUT', 0.0),
        ],
    ],
];



use Happyphper\Dify\DifyClient;use Happyphper\Dify\Public\PublicClient;

class YourController
{
    /**
     * @var PublicClient
     */
    private $dify;

    public function __construct(PublicClient $dify)
    {
        $this->dify = $dify;
    }

    public function index()
    {
        // Get dataset list
        $datasets = $this->dify->datasets()->list();
        
        // Create dataset
        $dataset = $this->dify->datasets()->create('Test Dataset', 'This is a test dataset');
        
        // Upload document
        $document = $this->dify->documents()->createByFile(
            $dataset['id'], 
            '/path/to/file.txt', 
            [
                'name' => 'test.txt',
                'text_splitter' => [
                    'type' => 'chunk',
                    'chunk_size' => 1000,
                    'chunk_overlap' => 200
                ],
                'indexing_technique' => 'high_quality'
            ]
        );
        
        // Get document list
        $documents = $this->dify->documents()->list($dataset['id']);
        
        // Delete document
        $this->dify->documents()->delete($dataset['id'], $document['id']);
        
        // Delete dataset
        $this->dify->datasets()->delete($dataset['id']);
        
        return [
            'datasets' => $datasets,
            'dataset' => $dataset,
            'document' => $document,
            'documents' => $documents
        ];
    }
}



use Happyphper\Dify\DifyClient;use Happyphper\Dify\Public\PublicClient;use Monolog\Handler\StreamHandler;use Monolog\Logger;

// Create logger
$logger = new Logger('dify');
$logger->pushHandler(new StreamHandler('path/to/your.log', Logger::DEBUG));

// Create Dify client
$client = new PublicClient(
    'your_api_key_here',
    'https://api.dify.ai/v1',
    true, // Enable debug mode
    $logger
);

// Get dataset list
$datasets = $client->datasets()->list();

// Create dataset
$dataset = $client->datasets()->create('Test Dataset', 'This is a test dataset');

// Upload document
$document = $client->documents()->createByFile(
    $dataset['id'], 
    '/path/to/file.txt', 
    [
        'name' => 'test.txt',
        'text_splitter' => [
            'type' => 'chunk',
            'chunk_size' => 1000,
            'chunk_overlap' => 200
        ],
        'indexing_technique' => 'high_quality'
    ]
);

// Get document list
$documents = $client->documents()->list($dataset['id']);

// Delete document
$client->documents()->delete($dataset['id'], $document['id']);

// Delete dataset
$client->datasets()->delete($dataset['id']);

// Create workflow chat request (blocking mode)
$inputs = [
    'query' => 'Tell me about Dify platform'
];
$response = $client->workflows()->run($inputs, 'user-123');

// Get response content
echo "Workflow Run ID: " . $response->getWorkflowRunId() . "\n";
echo "Task ID: " . $response->getTaskId() . "\n";
echo "Status: " . $response->getStatus() . "\n";
echo "Outputs: " . json_encode($response->getOutputs()) . "\n";

// Create workflow chat request (streaming mode)
$streamResponse = $client->workflows()->runStream($inputs, 'user-123');

// Set event callbacks
$streamResponse->onWorkflowStarted(function ($data) {
    echo "Workflow started: " . $data['workflow_run_id'] . "\n";
});

$streamResponse->onNodeStarted(function ($data) {
    echo "Node started: " . $data['data']['node_id'] . "\n";
});

$streamResponse->onNodeFinished(function ($data) {
    echo "Node finished: " . $data['data']['node_id'] . "\n";
});

$streamResponse->onWorkflowFinished(function ($data) {
    echo "Workflow finished: " . $data['data']['status'] . "\n";
});

$streamResponse->onMessage(function ($data) {
    echo "Message received: " . ($data['answer'] ?? '') . "\n";
});

// Start processing the stream
$streamResponse->stream();

// Stop workflow execution
$client->workflows()->stop($taskId);

// Get conversation list
$conversations = $client->workflows()->getConversations('user-123');

// Get conversation message history
$messages = $client->workflows()->getMessages($conversationId, 'user-123');

// Delete conversation
$client->workflows()->deleteConversation($conversationId, 'user-123');

// Rename conversation
$client->workflows()->renameConversation($conversationId, 'New Conversation Name', 'user-123');

// Like a message
$client->workflows()->messageFeedback($messageId, 'like', 'user-123');

// Dislike a message
$client->workflows()->messageFeedback($messageId, 'dislike', 'user-123');

// Revoke feedback
$client->workflows()->revokeFeedback($messageId, 'user-123');

// Upload a file
$fileInfo = $client->workflows()->uploadFile('/path/to/file.pdf', 'user-123', 'document');

// Send a message with a file
$inputs = [
    'query' => 'Analyze this file',
    'file' => [
        'transfer_method' => 'local_file',
        'upload_file_id' => $fileInfo['id'],
        'type' => 'document'
    ]
];
$response = $client->workflows()->run($inputs, 'user-123');

// Convert audio to text
$result = $client->workflows()->audioToText('/path/to/audio.mp3', 'user-123');

// Convert text to audio
$result = $client->workflows()->textToAudio('Convert this text to speech', 'user-123', 'default');

// Get application basic info
$appInfo = $client->workflows()->getAppInfo();

// Get application parameters
$parameters = $client->workflows()->getParameters();

use Happyphper\Dify\Console\ConsoleClient;use Happyphper\Dify\Exceptions\ApiException;

// Create console client
$consoleClient = new ConsoleClient(
    'http://localhost:8080',  // Dify console URL
    '[email protected]', // Login email
    'your-password',          // Login password
    true                      // Enable debug mode
);

// Disable document
try {
    $result = $consoleClient->datasets()->disableDocuments(
        'dataset-id',
        'document-id'
    );
    
    if ($result) {
        echo "Document disabled successfully\n";
    } else {
        echo "Failed to disable document\n";
    }
} catch (ApiException $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

// Enable document
try {
    $result = $consoleClient->datasets()->enableDocuments(
        'dataset-id',
        'document-id'
    );
    
    if ($result) {
        echo "Document enabled successfully\n";
    } else {
        echo "Failed to enable document\n";
    }
} catch (ApiException $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

// Batch operations (passing an array)
$documentIds = ['doc-id-1', 'doc-id-2', 'doc-id-3'];
$consoleClient->datasets()->disableDocuments('dataset-id', $documentIds);

// The ConsoleClient handles token refresh automatically
// You don't need to write any additional code for token management

// Example of a long-running process where tokens might expire
$datasets = $consoleClient->datasets()->list();

// Even after token expiration, this will still work without any manual intervention
sleep(3600); // Simulate passage of time (1 hour)
$documents = $consoleClient->documents()->list($datasets[0]['id']);

// The SDK handles token refresh behind the scenes

// Create knowledge base
$dataset = $client->datasets()->create('Test Knowledge Base', 'This is a test knowledge base');

// Get knowledge base list
$datasets = $client->datasets()->list(1, 20);

// Delete knowledge base
$client->datasets()->delete('dataset-id');

// Knowledge base retrieval
$result = $client->datasets()->retrieve('dataset-id', 'search keywords', [
    'search_method' => 'semantic_search',
    'top_k' => 5
]);

// Create document from text
$document = $client->documents()->createByText(
    'dataset-id',
    'Document Name',
    'Document Content',
    'high_quality',
    ['mode' => 'automatic']
);

// Create document from file
$document = $client->documents()->createByFile(
    'dataset-id',
    '/path/to/file.pdf',
    [
        'indexing_technique' => 'high_quality',
        'process_rule' => [
            'mode' => 'custom',
            'rules' => [
                'pre_processing_rules' => [
                    ['id' => 'remove_extra_spaces', 'enabled' => true],
                    ['id' => 'remove_urls_emails', 'enabled' => true]
                ],
                'segmentation' => [
                    'separator' => '###',
                    'max_tokens' => 500
                ]
            ]
        ]
    ]
);

// Get document list
$documents = $client->documents()->list('dataset-id');

// Update document by text
$document = $client->documents()->updateByText(
    'dataset-id',
    'document-id',
    [
        'name' => 'New Document Name',
        'text' => 'New Document Content'
    ]
);

// Create segments
$segments = $client->segments()->create('dataset-id', 'document-id', [
    [
        'content' => 'Segment content',
        'answer' => 'Segment answer',
        'keywords' => ['keyword1', 'keyword2']
    ]
]);

// Get segment list
$segments = $client->segments()->list('dataset-id', 'document-id');

// Update segment
$segment = $client->segments()->update(
    'dataset-id',
    'document-id',
    'segment-id',
    [
        'content' => 'New segment content',
        'answer' => 'New segment answer',
        'regenerateChildChunks' => true // Regenerate child chunks
    ]
);

// Delete segment
try {
    $result = $client->segments()->delete('dataset-id', 'document-id', 'segment-id');
} catch (NotFoundException $e) {
    // Handle segment not found
    echo "Segment not found: " . $e->getMessage();
} catch (ApiException $e) {
    // Handle other API errors
    echo "API error: " . $e->getMessage();
}

use Happyphper\Dify\Exceptions\ApiException;
use Happyphper\Dify\Exceptions\ValidationException;
use Happyphper\Dify\Exceptions\AuthenticationException;
use Happyphper\Dify\Exceptions\AuthorizationException;
use Happyphper\Dify\Exceptions\NotFoundException;
use Happyphper\Dify\Exceptions\RateLimitException;
use Happyphper\Dify\Exceptions\ServerException;

try {
    // Your code
} catch (ValidationException $e) {
    // Handle validation errors
} catch (AuthenticationException $e) {
    // Handle authentication errors
} catch (AuthorizationException $e) {
    // Handle authorization errors
} catch (NotFoundException $e) {
    // Handle resource not found errors
} catch (RateLimitException $e) {
    // Handle rate limit errors
} catch (ServerException $e) {
    // Handle server errors
} catch (ApiException $e) {
    // Handle other API errors
    echo "API error: " . $e->getMessage();
}

$page = 1;
$limit = 20;
$allDocuments = [];

do {
    $response = $client->documents()->list('dataset-id', null, $page, $limit);
    $documents = $response['data'] ?? [];
    $allDocuments = array_merge($allDocuments, $documents);
    $page++;
} while (!empty($documents) && $response['has_more'] ?? false);
bash
php bin/hyperf.php vendor:publish happyphper/dify