Phind Generated Refactored Python Code to Chat with Phind

This program serves as a versatile chatbot interface, capable of operating both as a command-line tool and a web service. Designed to facilitate interactive conversations, it leverages an external AI model hosted at https://https.extension.phind.com/agent/ to generate responses.

Users can engage with the chatbot either by typing commands directly into the terminal or by submitting messages through a web form. The program dynamically adapts to its execution environment, utilizing session management for web interactions to maintain conversational context across multiple exchanges. Whether accessed via the command line or embedded within a webpage, it offers a seamless experience for users seeking intelligent, context-aware responses.

 "",
        "allow_magic_buttons" => true,
        "is_vscode_extension" => true,
        "message_history" => [["content" => $inputMessage, "role" => "user"]],
        "requested_model" => "Phind Model",
        "user_input" => $inputMessage
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode == 200) {
        $lines = explode("\r\n\r\n", $response);
        $contentValues = [];
        foreach ($lines as $line) {
            if (strpos($line, "data: ")!== false) {
                $data = json_decode(substr($line, strpos($line, "data: ") + 6), true);
                $choices = isset($data['choices'])? $data['choices'] : [];
                foreach ($choices as $choice) {
                    $content = isset($choice['delta']['content'])? $choice['delta']['content'] : '';
                    if (!empty($content)) {
                        $contentValues[] = $content;
                    }
                }
            }
        }
        return implode('', $contentValues);
    } elseif ($httpCode == 401 || $httpCode == 429) {
        echo "Error: {$httpCode}, Trying again.\n";
        return prompt($inputMessage);
    } else {
        return "Error: {$httpCode}, {$response}";
    }
}

function promptWithContext($inputMessage, $conversationHistory) {
    $url = "https://https.extension.phind.com/agent/";
    $headers = [
        "Content-Type: application/json",
        "User-Agent: ",
        "Accept: */*",
        "Accept-Encoding: Identity"
    ];

    // Append the current user message to the conversation history
    $updatedConversationHistory = $conversationHistory;
    $updatedConversationHistory[] = ["content" => $inputMessage, "role" => "user"];

    $payload = [
        "additional_extension_context" => "",
        "allow_magic_buttons" => true,
        "is_vscode_extension" => true,
        "message_history" => $updatedConversationHistory,
        "requested_model" => "Phind Model",
        "user_input" => $inputMessage
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode == 200) {
        $lines = explode("\r\n\r\n", $response);
        $contentValues = [];
        foreach ($lines as $line) {
            if (strpos($line, "data: ")!== false) {
                $data = json_decode(substr($line, strpos($line, "data: ") + 6), true);
                $choices = isset($data['choices'])? $data['choices'] : [];
                foreach ($choices as $choice) {
                    $content = isset($choice['delta']['content'])? $choice['delta']['content'] : '';
                    if (!empty($content)) {
                        $contentValues[] = $content;
                    }
                }
            }
        }
        return implode('', $contentValues);
    } elseif ($httpCode == 401 || $httpCode == 429) {
        echo "Error: {$httpCode}, Trying again.\n";
        return promptWithContext($inputMessage, $conversationHistory);
    } else {
        return "Error: {$httpCode}, {$response}";
    }
}

function main() {
    global $argv;
    array_shift($argv); // Remove script name from args
    if (count($argv) == 0) {
        echo "Welcome to OpynGPT Chat Type 'exit' to quit.\n";
        $conversationHistory = [];
        while (true) {
            $inputMessage = readline("You: ");
            if (strtolower($inputMessage) == "exit") {
                echo "Thank you for using OpynGPT Chat Feel free to leave a star on GitHub: https://github.com/anxkhn/OpynGPT. Bye!\n";
                break;
            }
            $conversationHistory[] = ["content" => $inputMessage, "role" => "user"];
            $response = promptWithContext($inputMessage, $conversationHistory);
            $conversationHistory[] = ["content" => $response, "role" => "assistant"];
            echo "Assistant: {$response}\n";
        }
    } else {
        $inputMessage = implode(' ', $argv);
        $response = prompt($inputMessage);
        echo $response. "\n";
    }
}

function handleWebRequest() {
    session_start();
    // Check if the request method is POST
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        // Retrieve the user input from the POST data
        $inputMessage = $_GET['message'];
        
        // Initialize conversation history if not present in session
        if (!isset($_SESSION['conversationHistory'])) {
            $_SESSION['conversationHistory'] = [];
        }
        
        // Append the current user message to the conversation history
        $_SESSION['conversationHistory'][] = ["content" => $inputMessage, "role" => "user"];
        
        // Call the promptWithContext function with the user message and conversation history
        $response = promptWithContext($inputMessage, $_SESSION['conversationHistory']);
        
        // Append the assistant's response to the conversation history
        $_SESSION['conversationHistory'][] = ["content" => $response, "role" => "assistant"];
        
        // Output the assistant's response
        echo $response;
    } else {
        // Handle GET requests or other methods as needed
        echo "Please send a POST request with a 'message' parameter.";
    }
}

function determineExecutionEnvironmentAndRun() {
    // Check if the script is running in CLI mode
    if (php_sapi_name() === 'cli') {
        // Run the main function for CLI interactions
        main();
    } else {
        // Run the handleWebRequest function for web requests
        handleWebRequest();
    }
}
determineExecutionEnvironmentAndRun();
?>



Comments

One response to “Phind Generated Refactored Python Code to Chat with Phind”

  1. Right now this is a bare bones API endpoint because it only spits out plain text responses from the Phind API endpoint. I need to create one or more functions to determine the web context and output either HTML, xml, csv, or plain text.

    I also need to sanitize user inputs and do any special character escaping. Including some protections against common prompt injection attack methods.

Leave a Reply to Bob Cancel reply

Your email address will not be published. Required fields are marked *