Skip to content
site logo mobile

Code Snippets Library >

AI Agent on WordPress With a PHP Snippet

🔑 ID:

42642

👨‍💻

PHP

🕒

24/04/2024
Free

Description:

I’ve crafted a prototype that demonstrates how to build AI agents directly in WordPress using PHP. This prototype serves as a foundational example for those looking to integrate advanced AI functionalities into their WordPress sites.

Code Snippet Overview:

The provided PHP functions enable you to add an AI Agent through the WordPress API.  Here’s a brief explanation of the functions and their roles:

  • get_response_time($url): This function checks the response time of specified URLs, demonstrating how to add an additional function to the AI agent.
  • generate_text_with_conversation($messages, $model): This function interacts with OpenAI’s API, sending conversational prompts and handling responses. It’s configured to handle different models and adjust parameters like creativity (temperature).
  • extract_json($textResponse) and extend_search_new($text, $match): These functions parse and extract JSON from text responses, which is crucial for processing the actions that the AI Agent should perform.
  • process_ai_agent(WP_REST_Request $request): This endpoint function orchestrates the AI’s decision-making process based on user queries, demonstrating a loop of thought and action as defined in a system prompt.

 

This code snippet is directly related to the video provided in our AI Agents series. For a more comprehensive understanding and step-by-step guide, refer to the video in our premium video library.

To fully understand this code snippet, we assume you already know what AI agents are and how they operate. If you need a refresher or a more foundational understanding, you can check out the full course here.

Code:

//Availabe Functions
// Function to get response time based on the URL
function get_response_time($url) {
    if ($url === "learnwithhasan.com") {
        return 0.5;
    }
    if ($url === "google.com") {
        return 0.3;
    }
    if ($url === "openai.com") {
        return 0.4;
    }
    return "Unknown URL";
}
//Function To Generate With OpenAI
function generate_text_with_conversation( $messages, $model = "gpt-3.5-turbo" ) {

// OpenAI API URL and key
$api_url = 'https://api.openai.com/v1/chat/completions';
$api_key = 'sk-XXX'; // Replace with your actual API key

// Headers for the OpenAI API
$headers = [
    'Content-Type' => 'application/json',
    'Authorization' => 'Bearer ' . $api_key
];


// Body for the OpenAI API
$body = [
    'model' => $model, // You can change the model if needed
    'messages' => $messages,
    'temperature' => 0.7 // You can adjust this value based on desired creativity
];

// Args for the WordPress HTTP API
$args = [
    'method' => 'POST',
    'headers' => $headers,
    'body' => json_encode($body),
    'timeout' => 120
];

// Send the request
$response = wp_remote_request($api_url, $args);

// Handle the response
if (is_wp_error($response)) {
    return $response->get_error_message();
} else {
    $response_body = wp_remote_retrieve_body($response);
    $data = json_decode($response_body, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        return [
            'success' => false,
            'message' => 'Invalid JSON in API response',
            'result' => ''
        ];
    } elseif (!isset($data['choices'])) {
         return [
            'success' => false,
            'message' => 'API request failed. Response: ' . $response_body,
            'result' => ''
        ];
    } else {
        $content = $data['choices'][0]['message']['content'];
        return [
            'success' => true,
            'message' => 'Response Generated',
            'result' => $content
        ];
    }
}
}

function extract_json($textResponse) {
    $pattern = '/\{.*?\}/s';  // 's' modifier for DOTALL in PHP
    preg_match_all($pattern, $textResponse, $matches);

    $jsonObjects = [];
    foreach ($matches[0] as $match) {
        $jsonStr = extend_search_new($textResponse, $match);
        $jsonObj = json_decode($jsonStr, true);
        if ($jsonObj !== null) {
            $jsonObjects[] = $jsonObj;
        }
    }

    return !empty($jsonObjects) ? $jsonObjects : null;
}

function extend_search_new($text, $match) {
    $start = strpos($text, $match);
    $end = $start + strlen($match);
    $nestCount = 1; // Starts with 1 since we know '{' is at the start position

    for ($i = $end; $i < strlen($text); $i++) {
        if ($text[$i] === '{') {
            $nestCount++;
        } elseif ($text[$i] === '}') {
            $nestCount--;
            if ($nestCount === 0) {
                return substr($text, $start, $i - $start + 1);
            }
        }
    }

    return substr($text, $start, $end - $start);
}

function process_ai_agent(WP_REST_Request $request) {
    $prompt = $request->get_param('prompt');
    $model = $request->get_param('model') ?: 'gpt-3.5-turbo';  // Default to gpt-3.5-turbo if not provided

    $availableActions = [
        "get_response_time" => "get_response_time"
    ];

    // ReAct System prompt
    $systemPrompt = <<<EOD
You run in a loop of Thought, Action, PAUSE, Action_Response.
At the end of the loop you output an Answer.

Use Thought to understand the question you have been asked.
Use Action to run one of the actions available to you - then return PAUSE.
Action_Response will be the result of running those actions.

Your available actions are:

get_response_time:
e.g. get_response_time: learnwithhasan.com
Returns the response time of a website

Example session:

Question: what is the response time for learnwithhasan.com?
Thought: I should check the response time for the web page first.
Action: 

{
  "function_name": "get_response_time",
  "function_parms": {
    "url": "learnwithhasan.com"
  }
}

PAUSE

You will be called again with this:

Action_Response: 0.5

You then output:

Answer: The response time for learnwithhasan.com is 0.5 seconds.
EOD;

    $messages = [
        ["role" => "system", "content" => $systemPrompt],
        ["role" => "user", "content" => $prompt]
    ];

    $lastResult = "";
    $turnCount = 1;
    $maxTurns = 5;

    while ($turnCount <= $maxTurns) {
        $response = generate_text_with_conversation($messages, $model);
        $lastResult = $response['result'];

        $jsonFunction = extract_json($response['result']);

        if ($jsonFunction) {
            $functionName = $jsonFunction[0]['function_name'];
            $functionParams = $jsonFunction[0]['function_parms'];

            if (!array_key_exists($functionName, $availableActions)) {
                return new WP_REST_Response("Error: Unknown action '{$functionName}'", 400);
            }

            $actionFunction = $availableActions[$functionName];
            $result = call_user_func($actionFunction, $functionParams['url']);
            $functionResultMessage = "Action_Response: $result";
            $lastResult = $response['result'];  // Capture the entire last response from the model

            $messages[] = ["role" => "system", "content" => $functionResultMessage];
        } else {
            break;
        }
        $turnCount++;
    }

    return new WP_REST_Response($lastResult, 200);  // Return the raw last result from the model
}

// Define the endpoint callback function
function process_ai_agent_full(WP_REST_Request $request) {
    $prompt = $request->get_param('prompt');
    $model = $request->get_param('model') ?: 'gpt-3.5-turbo';  // Default to gpt-3.5-turbo if not provided
    
    
$availableActions = [
    "get_response_time" => "get_response_time"
];

//ReAct System prompt
$systemPrompt = <<<EOD
You run in a loop of Thought, Action, PAUSE, Action_Response.
At the end of the loop you output an Answer.

Use Thought to understand the question you have been asked.
Use Action to run one of the actions available to you - then return PAUSE.
Action_Response will be the result of running those actions.

Your available actions are:

get_response_time:
e.g. get_response_time: learnwithhasan.com
Returns the response time of a website

Example session:

Question: what is the response time for learnwithhasan.com?
Thought: I should check the response time for the web page first.
Action: 

{
  "function_name": "get_response_time",
  "function_parms": {
    "url": "learnwithhasan.com"
  }
}

PAUSE

You will be called again with this:

Action_Response: 0.5

You then output:

Answer: The response time for learnwithhasan.com is 0.5 seconds.
EOD;

    
    
    $messages = [
    	["role" => "system", "content" => $systemPrompt],
    	["role" => "user", "content" => $prompt]
    ];
    
    
    

    // Assumed code integration from your existing logic
    $turnCount = 1;
    $maxTurns = 5;
    $responseCollection = [];
    $responseCollection[] = "Starting API interaction...";

    while ($turnCount <= $maxTurns) {
        $responseCollection[] = "Turn $turnCount: System processing...";
        $response = generate_text_with_conversation($messages, $model);
        $responseCollection[] = $response;

        $jsonFunction = extract_json($response['result']);

        if ($jsonFunction) {
            $functionName = $jsonFunction[0]['function_name'];
            $functionParams = $jsonFunction[0]['function_parms'];

            if (!array_key_exists($functionName, $availableActions)) {
                $responseCollection[] = "Error: Unknown action '{$functionName}'";
                break;
            }

            $responseCollection[] = "Executing action: $functionName with parameters " . json_encode($functionParams);
            $actionFunction = $availableActions[$functionName];
            $result = call_user_func($actionFunction, $functionParams['url']);
            $functionResultMessage = "Action_Response: $result";

            $messages[] = ["role" => "system", "content" => $functionResultMessage];
            $responseCollection[] = $functionResultMessage;  // Log action response
        } else {
            //$responseCollection[] = "No actionable input found or AI model did not return expected data structure. Ending loop.";
            break;
        }
        $turnCount++;
    }

    $responseCollection[] = "API interaction completed.";
    return new WP_REST_Response($responseCollection, 200);
}

// Register the REST API endpoint
add_action('rest_api_init', function () {
    register_rest_route('myapi/v1', '/process-agent', array(
        'methods' => 'POST',
        'callback' => 'process_ai_agent',
        'permission_callback' => '__return_true'  // Open access, change as necessary for security
    ));
    
    register_rest_route('myapi/v1', '/process-agent-full', array(
        'methods' => 'POST',
        'callback' => 'process_ai_agent_full',
        'permission_callback' => '__return_true'  // Open access, change as necessary for security
    ));
});

 

Untitled design (82)

GitHub Link

✖️ Not Available

Untitled design (83)

Download File

✖️ Not Available

If you’re encountering any problems or need further assistance with this code, we’re here to help! Join our community on the forum or Discord for support, tips, and discussion.