### Submit content for moderation using PHP SDK Source: https://github.com/moderation-api/sdk-php/blob/main/README.md This example demonstrates how to initialize the Moderation API client and submit content for moderation. It uses environment variables for the secret key and shows how to access the recommendation from the response. ```php content->submit( content: ['text' => 'x', 'type' => 'text'] ); var_dump($response->recommendation); ``` -------------------------------- ### Install Moderation API PHP SDK using Composer Source: https://github.com/moderation-api/sdk-php/blob/main/README.md This snippet shows how to install the Moderation API PHP SDK using the Composer package manager. Ensure you have Composer installed and configured for your PHP project. ```bash composer require "moderation-api/sdk-php 0.3.0" ``` -------------------------------- ### Configure API retries with PHP SDK Source: https://github.com/moderation-api/sdk-php/blob/main/README.md This example shows how to configure the number of automatic retries for API requests using the Moderation API PHP SDK. Retries can be set globally when initializing the client or on a per-request basis using RequestOptions. ```php content->submit( content: ['text' => 'x', 'type' => 'text'], requestOptions: RequestOptions::with(maxRetries: 5) ); ``` -------------------------------- ### Initialize Moderation API Client in PHP Source: https://context7.com/moderation-api/sdk-php/llms.txt Demonstrates how to initialize the Moderation API client using a secret key, environment variable, or custom base URL. The client provides access to various moderation services. ```php ``` ### Response #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### PHP: Configure Request Options and Retries Source: https://context7.com/moderation-api/sdk-php/llms.txt Shows how to configure custom request options, including retry behavior and additional parameters for API calls. This allows for fine-grained control over request execution, such as setting maximum retries, adding query parameters, custom headers, or body parameters. It also demonstrates making direct, custom requests to specific API endpoints. ```php content->submit( content: ['text' => 'Test content', 'type' => 'text'], requestOptions: RequestOptions::with( maxRetries: 5, extraQueryParams: ['debug' => 'true'], extraHeaders: [ 'X-Custom-Header' => 'custom-value', 'X-Request-ID' => 'req_' . uniqid() ], extraBodyParams: [ 'custom_field' => 'custom_value' ] ) ); // Make undocumented API requests $customResponse = $client->request( method: 'post', path: '/custom/endpoint', query: ['param1' => 'value1', 'param2' => 'value2'], headers: ['X-Custom-Header' => 'value'], body: ['data' => 'payload'] ); echo "Custom request completed\n"; ``` -------------------------------- ### Manage Moderation Actions (PHP) Source: https://context7.com/moderation-api/sdk-php/llms.txt This snippet demonstrates how to manage moderation actions using the Moderation API's PHP SDK. It covers creating custom actions, listing all available actions, retrieving specific action details, updating existing actions, executing actions on content or authors, and deleting actions. Dependencies include the ModerationAPI Client class. Inputs and outputs vary based on the specific action performed. ```php actions->create( name: 'Issue Warning', description: 'Send a warning to the user about policy violations', type: 'AUTHOR_WARN', position: 'ALL_QUEUES', queueBehaviour: 'NO_CHANGE', key: 'issue_warning', valueRequired: true, freeText: true, possibleValues: [ ['value' => 'First warning - minor violation'], ['value' => 'Second warning - serious violation'], ['value' => 'Final warning - next violation results in ban'] ], webhooks: [ [ 'name' => 'Warning Notification', 'url' => 'https://api.example.com/webhooks/user-warning', 'description' => 'Notify user service when warning is issued' ] ] ); echo "Created action ID: {$newAction->id}\n"; // List all available actions $actions = $client->actions->list(queueID: 'default_queue'); foreach ($actions as $action) { echo "Action: {$action->name} ({$action->type})\n"; } // Retrieve specific action $action = $client->actions->retrieve(id: $newAction->id); echo "Action name: {$action->name}\n"; echo "Queue behavior: {$action->queueBehaviour}\n"; // Update action $updatedAction = $client->actions->update( id: $newAction->id, name: 'Issue User Warning', description: 'Updated description for warning action' ); // Execute action on content $executionResult = $client->actions->execute->execute( actionKey: 'issue_warning', contentIDs: ['comment_67890', 'post_11223'], value: 'First warning - minor violation', queueID: 'default_queue' ); // Execute action on authors $authorActionResult = $client->actions->execute->execute( actionKey: 'author_block', authorIDs: ['user_12345'], duration: 86400000, // 24 hours in milliseconds queueID: 'default_queue' ); // Delete action $deleteResult = $client->actions->delete(id: $newAction->id); echo "Action deleted: " . ($deleteResult->success ? 'Yes' : 'No') . "\n"; ``` -------------------------------- ### Submit Content for Moderation Analysis in PHP Source: https://context7.com/moderation-api/sdk-php/llms.txt Shows how to submit text content for AI-powered moderation analysis using the PHP SDK. It includes handling potential API exceptions like rate limits and general API errors, and processing the moderation response including flagged policies and recommended actions. ```php content->submit( content: ['text' => 'Check this user comment for policy violations', 'type' => 'text'], authorID: 'user_12345', contentID: 'comment_67890', channel: 'community_forum', metaType: 'comment', metadata: ['post_id' => '98765', 'thread_title' => 'Product Discussion' ] ); // Access moderation results echo "Flagged: " . ($response->evaluation->flagged ? 'Yes' : 'No') . "\n"; echo "Flag Probability: " . $response->evaluation->flagProbability . "\n"; echo "Severity Score: " . $response->evaluation->severityScore . "\n"; echo "Recommendation: " . $response->recommendation->action . "\n"; // Check specific policy violations foreach ($response->policies as $policy) { if ($policy->flagged) { echo "Policy '{$policy->id}' triggered (probability: {$policy->probability})\n"; } } // Get insights (sentiment, language) foreach ($response->insights as $insight) { echo "Insight: {$insight->id} = {$insight->value} (confidence: {$insight->probability})\n"; } // Handle content based on recommendation switch ($response->recommendation->action) { case 'ALLOW': echo "Content approved for publishing\n"; break; case 'REVIEW': echo "Content requires manual review\n"; break; case 'REJECT': echo "Content should be blocked\n"; break; } } catch (RateLimitException $e) { echo "Rate limit exceeded, retry after: " . $e->getMessage() . "\n"; } catch (APIException $e) { echo "API error: " . $e->getMessage() . "\n"; } // Submit without storing (for testing policies) $testResponse = $client->content->submit( content: ['text' => 'Test content', 'type' => 'text'], doNotStore: true ); ``` -------------------------------- ### Manage Moderation Queues (PHP) Source: https://context7.com/moderation-api/sdk-php/llms.txt This snippet illustrates how to manage moderation queues using the Moderation API's PHP SDK. It covers retrieving queue details and statistics, listing items within a queue with various filtering and sorting options, and resolving or unresolving queue items. Dependencies include the ModerationAPI Client class. Inputs include queue IDs, item IDs, and filtering parameters. ```php queue->retrieve(id: 'default_queue'); echo "Queue name: {$queue->name}\n"; echo "Queue ID: {$queue->id}\n"; // Get queue statistics $stats = $client->queue->getStats( id: 'default_queue', withinDays: '30' ); echo "Total items in last 30 days: {$stats->totalItems}\n"; echo "Average review time: {$stats->averageReviewTime}s\n"; echo "Items pending: {$stats->pendingCount}\n"; // List items in queue with filtering $items = $client->queue->items->list( id: 'default_queue', pageNumber: 1, pageSize: 20, sortField: 'severity', sortDirection: 'desc', includeResolved: 'false', afterDate: '2025-01-01T00:00:00Z', labels: 'hate_speech,harassment' ); foreach ($items->items as $item) { echo "Item ID: {$item->id}\n"; echo "Content: {$item->content->text}\n"; echo "Severity: {$item->severityScore}\n"; echo "Created: {$item->createdAt}\n"; } echo "Total pages: {$items->totalPages}\n"; echo "Current page: {$items->currentPage}\n"; // Filter by author $authorItems = $client->queue->items->list( id: 'default_queue', authorID: 'user_12345', pageNumber: 1, pageSize: 10 ); // Resolve a queue item $resolveResult = $client->queue->items->resolve( itemID: 'item_98765', id: 'default_queue', comment: 'Reviewed and approved by moderator' ); echo "Item resolved: " . ($resolveResult->success ? 'Yes' : 'No') . "\n"; // Unresolve an item (return to queue) $unresolveResult = $client->queue->items->unresolve( itemID: 'item_98765', id: 'default_queue', comment: 'Needs additional review' ); echo "Item returned to queue: " . ($unresolveResult->success ? 'Yes' : 'No') . "\n"; ``` -------------------------------- ### Making Requests to Undocumented Endpoints Source: https://github.com/moderation-api/sdk-php/blob/main/README.md This section explains how to make requests to endpoints that are not explicitly documented in the SDK. It leverages the `client.request` method to allow for custom requests while still benefiting from the SDK's built-in features like authentication and retries. ```APIDOC ## POST /undocumented/endpoint ### Description Allows making requests to any endpoint, including those not explicitly defined by the SDK, while retaining benefits like authentication and retries. ### Method POST ### Endpoint /undocumented/endpoint ### Parameters #### Query Parameters - **dog** (string) - Optional - Example query parameter. #### Headers - **useful-header** (string) - Optional - Example header. #### Request Body - **hello** (string) - Optional - Example request body field. ### Request Example ```php request( method: "post", path: '/undocumented/endpoint', query: ['dog' => 'woof'], headers: ['useful-header' => 'interesting-value'], body: ['hello' => 'world'] ); ``` ### Response #### Success Response (200) - **Example Response** (any) - The response from the requested endpoint. #### Response Example ```json { "message": "Successfully processed" } ``` ``` -------------------------------- ### Manage Authors using Moderation API PHP SDK Source: https://context7.com/moderation-api/sdk-php/llms.txt This snippet demonstrates how to use the Moderation API PHP SDK to perform author management operations. It covers creating, retrieving, updating, listing, and deleting authors. Dependencies include the ModerationAPI Client and environment variables for the secret key. Inputs and outputs vary per operation, involving author details and identifiers. ```php authors->create( externalID: 'user_12345', name: 'John Doe', email: 'john.doe@example.com', profilePicture: 'https://example.com/avatars/user_12345.jpg', externalLink: 'https://example.com/users/user_12345', firstSeen: time(), lastSeen: time(), metadata: [ 'emailVerified' => true, 'phoneVerified' => false, 'identityVerified' => true, 'isPayingCustomer' => true ] ); echo "Author created: {$author->id}\n"; echo "Trust level: {$author->trustLevel}\n"; // Retrieve author information $authorInfo = $client->authors->retrieve(id: 'user_12345'); echo "Author name: {$authorInfo->name}\n"; echo "Trust level: {$authorInfo->trustLevel}\n"; echo "Total content count: {$authorInfo->contentCount}\n"; echo "Flagged content ratio: {$authorInfo->flaggedContentRatio}\n"; echo "Violation count: {$authorInfo->violationCount}\n"; // Check if author is blocked if ($authorInfo->block !== null) { echo "Author is blocked until: {$authorInfo->block->until}\n"; echo "Block reason: {$authorInfo->block->reason}\n"; } // Update author information $updatedAuthor = $client->authors->update( id: 'user_12345', email: 'john.newemail@example.com', lastSeen: time(), manualTrustLevel: 0.8, metadata: [ 'emailVerified' => true, 'phoneVerified' => true, 'identityVerified' => true, 'isPayingCustomer' => true ] ); // List authors with filtering and sorting $authors = $client->authors->list( pageNumber: 1, pageSize: 50, sortBy: 'trustLevel', sortDirection: 'asc', lastActiveDate: '2025-01-01', memberSinceDate: '2024-01-01' ); foreach ($authors->items as $authorItem) { echo "Author: {$authorItem->name} (Trust: {$authorItem->trustLevel})\n"; echo " Content count: {$authorItem->contentCount}\n"; echo " Violations: {$authorItem->violationCount}\n"; } echo "Total authors: {$authors->totalCount}\n"; echo "Page {$authors->currentPage} of {$authors->totalPages}\n"; // Delete an author $deleteResult = $client->authors->delete(id: 'user_12345'); echo "Author deleted: " . ($deleteResult->success ? 'Yes' : 'No') . "\n"; ``` -------------------------------- ### PHP: Handle API Errors with Specific Exceptions Source: https://context7.com/moderation-api/sdk-php/llms.txt Demonstrates how to catch and handle various API exceptions thrown by the Moderation API client. This allows for specific error management based on the type of API issue encountered, such as authentication failures, rate limits, or server errors. It utilizes a try-catch block to gracefully manage potential problems during API interactions. ```php content->submit( content: ['text' => 'Content to moderate', 'type' => 'text'], authorID: 'user_12345' ); echo "Content moderation successful\n"; } catch (AuthenticationException $e) { echo "Authentication failed: Invalid API key\n"; echo "Status code: {$e->getCode()}\n"; } catch (RateLimitException $e) { echo "Rate limit exceeded, please retry after backoff\n"; echo "Retry after: " . $e->getMessage() . "\n"; sleep(60); // Wait before retry } catch (BadRequestException $e) { echo "Invalid request parameters\n"; echo "Error: {$e->getMessage()}\n"; } catch (NotFoundException $e) { echo "Resource not found: {$e->getMessage()}\n"; } catch (InternalServerException $e) { echo "Server error, please try again later\n"; echo "Status: {$e->getCode()}\n"; } catch (APIConnectionException $e) { echo "Network error: Could not reach API server\n"; if ($e->getPrevious()) { echo "Underlying error: " . $e->getPrevious()->getMessage() . "\n"; } } catch (APIException $e) { echo "General API error occurred\n"; echo "Message: {$e->getMessage()}\n"; echo "Code: {$e->getCode()}\n"; } ``` -------------------------------- ### Content Submission and Moderation Source: https://context7.com/moderation-api/sdk-php/llms.txt Submit content for AI-powered moderation analysis and receive recommendations for automated or manual review. Handles text content and supports various metadata for context. ```APIDOC ## POST /content/submit ### Description Submit content for AI-powered moderation analysis and receive recommendations for automated or manual review. ### Method POST ### Endpoint /content/submit ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **content** (array) - Required - The content to be moderated. Expected to have 'text' and 'type' keys. - **authorID** (string) - Optional - Identifier for the author of the content. - **contentID** (string) - Optional - Unique identifier for the content being submitted. - **channel** (string) - Optional - The channel or context where the content was posted. - **metaType** (string) - Optional - The type of metadata associated with the content (e.g., 'comment', 'post'). - **metadata** (array) - Optional - Additional metadata associated with the content. - **doNotStore** (boolean) - Optional - If true, the content will not be stored by the API. ### Request Example ```php content->submit( content: ['text' => 'Check this user comment for policy violations', 'type' => 'text'], authorID: 'user_12345', contentID: 'comment_67890', channel: 'community_forum', metaType: 'comment', metadata: [ 'post_id' => '98765', 'thread_title' => 'Product Discussion' ] ); // Access moderation results echo "Flagged: " . ($response->evaluation->flagged ? 'Yes' : 'No') . "\n"; echo "Flag Probability: " . $response->evaluation->flagProbability . "\n"; echo "Severity Score: " . $response->evaluation->severityScore . "\n"; echo "Recommendation: " . $response->recommendation->action . "\n"; // Check specific policy violations foreach ($response->policies as $policy) { if ($policy->flagged) { echo "Policy '{$policy->id}' triggered (probability: {$policy->probability})\n"; } } // Get insights (sentiment, language) foreach ($response->insights as $insight) { echo "Insight: {$insight->id} = {$insight->value} (confidence: {$insight->probability})\n"; } // Handle content based on recommendation switch ($response->recommendation->action) { case 'ALLOW': echo "Content approved for publishing\n"; break; case 'REVIEW': echo "Content requires manual review\n"; break; case 'REJECT': echo "Content should be blocked\n"; break; } } catch (RateLimitException $e) { echo "Rate limit exceeded, retry after: " . $e->getMessage() . "\n"; } catch (APIException $e) { echo "API error: " . $e->getMessage() . "\n"; } // Submit without storing (for testing policies) $testResponse = $client->content->submit( content: ['text' => 'Test content', 'type' => 'text'], doNotStore: true ); ?> ``` ### Response #### Success Response (200) - **evaluation** (object) - Moderation evaluation results. - **flagged** (boolean) - Indicates if the content was flagged. - **flagProbability** (float) - The probability of the content being flagged. - **severityScore** (float) - The severity score of the flagged content. - **recommendation** (object) - Recommended action for the content. - **action** (string) - The recommended action (e.g., 'ALLOW', 'REVIEW', 'REJECT'). - **policies** (array) - List of policies evaluated. - **id** (string) - The ID of the policy. - **flagged** (boolean) - Whether the policy was triggered. - **probability** (float) - The probability associated with the policy. - **insights** (array) - Additional insights about the content. - **id** (string) - The ID of the insight (e.g., 'sentiment', 'language'). - **value** (string) - The value of the insight. - **probability** (float) - The confidence probability of the insight. #### Response Example ```json { "evaluation": { "flagged": true, "flagProbability": 0.95, "severityScore": 8.5 }, "recommendation": { "action": "REJECT" }, "policies": [ { "id": "hate_speech", "flagged": true, "probability": 0.98 }, { "id": "spam", "flagged": false, "probability": 0.05 } ], "insights": [ { "id": "sentiment", "value": "negative", "probability": 0.90 }, { "id": "language", "value": "en", "probability": 0.99 } ] } ``` ``` -------------------------------- ### Handle API errors with PHP SDK Source: https://github.com/moderation-api/sdk-php/blob/main/README.md This PHP code illustrates how to handle potential exceptions thrown by the Moderation API SDK, such as connection errors, rate limit errors, and other API status errors. It provides specific catch blocks for different exception types. ```php content->submit( content: ['text' => 'x', 'type' => 'text'] ); } catch (APIConnectionException $e) { echo "The server could not be reached", PHP_EOL; var_dump($e->getPrevious()); } catch (RateLimitError $e) { echo "A 429 status code was received; we should back off a bit.", PHP_EOL; } catch (APIStatusError $e) { echo "Another non-200-range status code was received", PHP_EOL; echo $e->getMessage(); } ``` -------------------------------- ### Send undocumented parameters in PHP SDK requests Source: https://github.com/moderation-api/sdk-php/blob/main/README.md This PHP snippet demonstrates how to send undocumented query parameters, body parameters, and headers with a Moderation API request using the SDK. This is useful for testing or utilizing features not yet formally documented. ```php content->submit( content: ['text' => 'x', 'type' => 'text'], requestOptions: RequestOptions::with( extraQueryParams: ['my_query_parameter' => 'value'], extraBodyParams: ['my_body_parameter' => 'value'], extraHeaders: ['my-header' => 'value'] ) ); ``` -------------------------------- ### Manage Wordlists using Moderation API PHP SDK Source: https://context7.com/moderation-api/sdk-php/llms.txt This snippet shows how to manage wordlists with the Moderation API PHP SDK, including listing, retrieving, updating, and checking embedding status. It requires the ModerationAPI Client and environment variables for authentication. Operations involve wordlist identifiers, names, descriptions, keys, and word arrays. ```php wordlist->list(); foreach ($wordlists as $list) { echo "Wordlist: {$list->name} (ID: {$list->id})\n"; echo " Key: {$list->key}\n"; echo " Description: {$list->description}\n"; echo " Word count: {$list->wordCount}\n"; } // Retrieve specific wordlist $wordlist = $client->wordlist->retrieve(id: 'wordlist_12345'); echo "Wordlist name: {$wordlist->name}\n"; echo "Words: " . implode(', ', $wordlist->words) . "\n"; // Update wordlist $updatedWordlist = $client->wordlist->update( id: 'wordlist_12345', name: 'Prohibited Terms', description: 'List of terms that violate community guidelines', key: 'prohibited_terms', words: [ 'spam_term_1', 'inappropriate_word_2', 'banned_phrase_3', 'offensive_term_4' ], strict: false ); echo "Wordlist updated: {$updatedWordlist->name}\n"; echo "New word count: {$updatedWordlist->wordCount}\n"; // Check embedding status (for semantic matching) $embeddingStatus = $client->wordlist->getEmbeddingStatus(id: 'wordlist_12345'); echo "Embedding status: {$embeddingStatus->status}\n"; echo "Progress: {$embeddingStatus->progress}%\n"; if ($embeddingStatus->status === 'completed') { echo "Wordlist is ready for semantic similarity matching\n"; } elseif ($embeddingStatus->status === 'processing') { echo "Embeddings are being generated, please wait...\n"; } // Add words to existing wordlist $existingWordlist = $client->wordlist->retrieve(id: 'wordlist_12345'); $currentWords = $existingWordlist->words; $newWords = array_merge($currentWords, ['new_term_1', 'new_term_2']); $client->wordlist->update( id: 'wordlist_12345', words: array_unique($newWords) // Remove duplicates ); // Manage wordlist words via words subservice $wordlist->words; // Access to word-specific operations ``` -------------------------------- ### Make Request to Undocumented Endpoint - PHP Source: https://github.com/moderation-api/sdk-php/blob/main/README.md This snippet demonstrates how to make a POST request to an undocumented endpoint using the Moderation API PHP SDK's `client.request` method. It shows how to specify the HTTP method, path, query parameters, headers, and request body. This method retains benefits like authentication and retries. ```php request( method: "post", path: '/undocumented/endpoint', query: ['dog' => 'woof'], headers: ['useful-header' => 'interesting-value'], body: ['hello' => 'world'] ); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.