Generic AI model integration for P4 Code Review

Use a generic AI model with P4 Code Review to generate AI-based explanations for code diffs using a compatible external or internal AI service.

A generic AI model allows you to integrate AI providers that are not explicitly supported by default, as long as they expose a compatible API endpoint.

To review the terms for using your own API keys, download the API Key Usage Agreement for Perforce P4 Code Review.

When to use a generic AI model

Use this option if:

  • Your AI provider is not listed (for example, OpenAI, Claude, Gemini).

  • You are using a custom-hosted or third-party AI service.

  • Your AI service exposes a REST API compatible with P4 Code Review.

To integrate a generic AI model with P4 Code Review

Complete the following steps:

  • Obtain API access to your AI service

  • Configure AI in P4 Code Review

Obtain API access

Create an account with your AI provider or access your internal AI service.

  • Generate an API key (if required).

  • Identify the API endpoint URL for the model.

  • Note the model name required for requests.

Configure AI in P4 Code Review

There are two ways to configure AI in P4 Code Review:

  • Use AI configuration in System Information (Recommended)

  • Use ai_review block config.php (Not recommended)

Use AI configuration in System Information (Recommended)

This is the easiest way to set up a generic AI model.

  1. In the top right corner of P4 Code Review, click System Information from the User ID dropdown menu.

  2. Click Configuration.

  3. Click on AI Configuration to expand the section.

  4. Turn on Enable AI.

  5. At the bottom of the page, in the AI Vendor section, click the Edit vendor configuration icon.

  6. Configure the following settings:

    • AI Vendor: Select Generic AI from the dropdown.

    • AI Package Value: (optional) A display value for the AI package.

    • AI Model: Enter the model name required by your AI service.

    • AI Package Type: Enter a value to identify the prompt type used in the AI response.

    • API key: Enter your API key (if required).

    • Character Limits: Enter the minimum and maximum characters required for AI processing.

    • API Endpoint: Enter the API URL for your AI service.

    • Prompts: (Optional) Configure prompts used by the AI Assistant for comments. You can update the following:

      • Improve Comment

      • Summarize Text

      • Fix Spelling and Grammar

      • Custom Prompt

  7. Click Update AI Vendor.

Use config.php (Not recommended)

To configure a generic AI model using the config.php file, you must be a super user.

  1. To configure AI review integration for P4 Code Review, add the ai_review block configuration in SWARM_ROOT/data/config.php file, as in the following example:

    <?php 
        'ai_review' => array(
             // Please read Perforce's Generative AI policy before enabling this feature. 
             // See https://www.perforce.com/generative-ai-policy 
             'enabled' => false, // set to true to enable the AI review feature
             'data_retention_lifetime' => '30 days',  // Delete AI summary records that are older than the
    					  	  // value provided. By default, this value is 30 days.
    						  // Enter a value in 'days' or 'months'.
    						  // For example, '30 days' or '2 months'.
    						  // A cron job is required to remove the
    						  // AI summaries on a schedule.
    						  // See Set up a cron job to delete AI summaries.	
            'timeout' => 30, // Setting timeout for the request sent from p4 code review to AI vendor 
                             //  Timeout set in seconds
            'ai_vendors' => array(
                'ai_model1' => array(
                    'ai_vendor'        => genericAI', // Name of the AI provider being used
                    'ai_package_id'    => '1', // Ensure this remains as '1'.
                                               // Do not modify the ai_package_id.
                    'ai_package_key'   => 'GenericAIPackage', // This is intended for future  
                                                                         // use when we will support
                                                                         // multiple models and have an 
                                                                         // AI configuration page in the UI.
                    'ai_package_value' => 'Generic AI with explain code on custom AI model', // This is used to
                                                                               // display the model type
                                                                               // type in the summary of
                                                                               // the AI vendor's response
                    'ai_model'         => 'GenericAIModel',
                    'ai_package_type'  => "Explain the following code:", // This is the prompt for the
                                                                         // AI. You can modify the prompt
                                                                         // for purposes other than
                                                                         // explaining the code, or to
                                                                         // request the output in a
                                                                         // specific language.
                    'api_key'          => $SECRET_KEY,    // Add in the API-key for your AI vendors
                    'api_end_point'    => 'https://apitoconnectaimodel.com/dummyAnalyzeCode', // Replace with
                                                                                              // your AI vendor
                                                                                              // end point
                    'ai_min_char_limit'=> 4, // Minimum number of characters required in the content
                                             // submitted to the AI vendor for analysis.
                                             // Defaults to 4 characters.
                    'ai_max_char_limit'=> 31000, // The maximum number of characters
                                                 // that can be submitted to the AI vendor for analysis
                                                 // Defaults to 31000 characters.
                ),
            ),
        ),
  2. Replace the placeholders with values for your AI service.

  3. Ensure that your AI service is accessible from P4 Code Review.

Example API endpoint request and response format

To review the terms for using your own API keys, download the API Key Usage Agreement for Perforce P4 Code Review.

Your AI service must support a compatible request and response format.

The following example uses the OpenAI format. Configure your API requests to match the request and response structure required by your AI service.

Note: If your AI service does not support a compatible request and response format, use a custom AI adapter instead.

Example API endpoint

POST /api/v11/AiAnalysis/dummyanalyzeCode

API endpoint request format

curl -X POST -H "Content-Type: application/json" -u "username:ticket" -d "@mybodyfilename.txt" "https://my-swarm-host/api/v11/AiAnalysis/dummyanalyzeCode"

The "mybodyfilename.txt" file contains:

{
  "content": "Explain the following code of file nodeofNotequal.c:  static void checkForLowerCase();"
}

API endpoint response format

{
  "data": {
    "id": "chatcmpl-Aqe3vInskpD30pkUMzBTJ9ONxou7l",
    "object": "chat.completion",
    "created": 1737110419,
    "model": "gpt-4o-2024-08-06",
    "choices": [
      {
        "index": 0,
        "message": {
          "role": "assistant",
          "content": "The line of code `static void checkForLowerCase();` in a C file named `nodeofNotequal.c` is a function
                      declaration. Here's what this line signifies:\n\n1. **`static` Keyword**: \n   - In the context of a 
                      function declaration, `static` means that the function has internal linkage. This means the function
                      can only be called within the same source file (in this case, `nodeofNotequal.c`). It is not visible
                      or accessible from other source files that might be linked together to form an executable.
                      \n\n2. **`void` Return Type**: \n   - `void` indicates that the function `checkForLowerCase` does not
                      return any value.\n\n3. **Function Name**: \n   - `checkForLowerCase` is the name of the function. 
                      It is customary to choose a name that indicates the purpose or action of the function. In this case,
                      it suggests that the function may be used to check for lowercase characters or strings, though the 
                      exact behavior would depend on the function’s implementation.\n\n4. **Parameter List**: \n   - 
                      The empty parentheses `()` indicate that the function does not take any arguments.\n\nThis is just a 
                      declaration, meaning it informs the compiler about the existence of the function `checkForLowerCase` 
                      and its signature (return type and parameters) before it is used in the code. The actual logic or body
                      of the function would appear later in the file, outside of the declaration.\n\nTo fully understand what
                      `checkForLowerCase` does, you would need to look at the function’s definition, which would specify the
                      code that executes when the function is called.",
          "refusal": null
        },
        "logprobs": null,
        "finish_reason": "stop"
      }
    ],
    "usage": {
      "prompt_tokens": 27,
      "completion_tokens": 338,
      "total_tokens": 365,
      "prompt_tokens_details": {
        "cached_tokens": 0,
        "audio_tokens": 0
      },
      "completion_tokens_details": {
        "reasoning_tokens": 0,
        "audio_tokens": 0,
        "accepted_prediction_tokens": 0,
        "rejected_prediction_tokens": 0
      }
    },
    "service_tier": "default",
    "system_fingerprint": "fp_50cad350e4"
  }
}