Help me to use API in the PHP code

@dewolfe001 hi Shawn, definitely worth a chat over the subject. I’m working in a similar direction and we might help each other. PM me to schedule something.

BTW just finished the PHP-based client that can use parallel requests to openAI with a backoff strategy (I know guzzle does it, but this one was done on purpose like that). You can also check some of my wp code here: sergeliatko (Serge Liatko) · GitHub and here TechSpokes, Inc. · GitHub and in the wild.

1 Like

I was just reading through this thread and laughing to myself. How could you all not see how powerful this connection between OpenAI and a WP website could be? I only discovered openAI and prompting in Jan and within a week I knew that anyone who could create a plugin to leverage the power of GPT3 to automate a WP site against all the worlds knowledge and skillset would make a killing, but yet it seems that most people in here thought it could maybe be a good idea?

Right now I’ve got people throwing money at me to turn their website into an AI-powered website to automate their own personal site data.

From what I can see there are only 2 plugins right now that allow me to setup a ChatGPT bot on my site that knows my site’s data and allows people to question it to get answers to the sites data or the immediate page’s post data. The same plugin automates fine-tuning without any code input from me.

A second plugin connects with openAI and Pinecone to facilitate embeddings and QA against those embeddings, I can even embed the whole website to Pinecone through the plugin and it will add any new page automatically using a cron job. These are free plugins but I would have happily paid around $50 each for them. One of them is $39 for the pro version for 5 sites licenses for me to connect it to a form to get the web visitor’s data and use that to formulate a prompt and bring back a result for the visitor.

People are paying me to implement this into their website ASAP!!

If I had known about openAI and GPT3 and prompting back in Nov, my life would be very different now, I would have paid a dev to write me these plugins and would have dominated the market by now, and I still might.

1 Like

Hi Sim2K,

Still looking for a team? Let me know

1 Like

Can you share the name of the plugins? I completely agree with you re building an OpenAI plugin for wordpress. It’s a massive market. Different plugins could do different things since there are so many use cases. The biggest I think would be enabling embeddings plus site search plus question answering. And also, allowing the user to upload documents (in bulk) for search and question answering. Josef is doing this for documents but I think the user has to upload them one at a time, the formats are limited, and I am not sure if the question answering can span multiple documents at once. On this forum I’ve lobbied for a wp plugin but I don’t think it’s been done yet -but it looks like your knowledge is more up to date than mine.

I’ll join the team on the subject matter side :grinning: since my site has implemented this already in a custom manner which could help plugin development. All wp posts of certain post types have been embedded, so the user can input a question on the front end and get an answer plus the most relevant posts. I just got access to the GPT-4 API so I need to change my code from “promt-completion” style to “system-user” style.

1 Like

@Sim2K I have no doubt you got it right.
This thing is bigger than the internet.

Have 3 good Ideas: like yours. (Easy to enter the market. Easy to communicate value. Easy to monetize). (The 2 are B2B. Started last week talking to target customers).

If you are open to a private exchange, would love to talk.

Here are the 2 WP plugins:

They both allow embeddings and then have a chatbot to work with the embeddings as its memory. Works quite well. Been working more with gpt3-ai-content-generator plugin.

Yes, would love to have a chat. Are you on Telegram? Im there under Sim2K.

I know I’m pretty late to this conversation, but as someone who is working with OpenAI and Weaviate using only PHP, I can answer this question for you. I am working in Drupal, and really don’t want to have to learn a bunch of new languages just to use the APIs.

So, for anyone wanting to build and implement your OpenAI-based applications using PHP:

All you have to do is submit the sample code in question (no matter the language) to an OpenAI code model in either Chat or Playground and ask it to translate to PHP. Super easy.

if anyone is looking for a Pinecone PHP library please try this one out

where you can use it from Composer as
composer require islambaraka90/pinecone-php-client

I’ve created this since there is no PHP client yet for Pinecone, if you have any suggestions for this library please reach out through the github repo
Wish you all a good day

use this api wrapper for openai’s api GitHub - orhanerday/open-ai: OpenAI PHP SDK : Most downloaded, forked, contributed, huge community supported, and used PHP (Laravel , Symfony, Yii, Cake PHP or any PHP framework) SDK for OpenAI GPT-3 and DALL-E. It also supports chatGPT-like streaming. (ChatGPT AI is supported)
alternatively you can make curling easy for any api with a library called guzzle GitHub - guzzle/guzzle: Guzzle, an extensible PHP HTTP client

alternatively, literally ask chatgpt to do this for you lol

I do this for all of my OpenAI api calls:

		// Define the OpenAI API endpoint and parameters
		$url = $this->urlOpenAI;

		// Initialize the $messages array with the system message
		$message = array(
			array("role" => "system", "content" => $systemMessage)
		);

		// Define the new user message 
		$userMessage = array("role" => "user", "content" => $text);
		
		// Append the new user message to the end of the $messages array
		$message[] = $userMessage;

		// Define the data for the API request
		$data = array(
			'messages' => $message,  // No need to wrap $message in an array if it is set as array above
			'model' => $model,
			'temperature' => $temperature
		);
		
		// Define the request headers and data
		$headers = [
			'Authorization: Bearer ' . $this->apiOpenAI,
			'Content-Type: application/json'
		];

		// Call the GPT API
		$responseBody = $this->solrai_executeCurlRequest($url, $headers, $data);

Then call this curl method:

	/**
	 * Executes a cURL request.
	 *
	 * @param string $url
	 *   The URL to make the request to.
	 * @param array $headers
	 *   An array of HTTP headers.
	 * @param array $data
	 *   The data to send in the request body.
	 *
	 * @return array
	 *   The response from the server, decoded from JSON to an array.
	 */
	public function solrai_executeCurlRequest($url, $headers, $data) {
	  $curl = curl_init();

	  curl_setopt($curl, CURLOPT_URL, $url);
	  curl_setopt($curl, CURLOPT_POST, true);
	  curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
	  curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
	  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	  curl_setopt($curl, CURLOPT_ENCODING, '');
	  curl_setopt($curl, CURLOPT_MAXREDIRS, 10); // Was set to 10.  Set to 0

	  $startTime = microtime(true);

		# Debug
		# Generate a unique identifier for this request
		$uniqueId = uniqid();

		# Debug
		# Log the request details
		# $this->loggerFactory->get('solrai')->info("(solrai_executeCurlRequest) Unique ID: $uniqueId | Request Details: " . print_r([
		#  'url' => $url,
		  # 'headers' => $headers,
		#  'body' => $data,
		# ], true));

	  $response = curl_exec($curl);

		# Debug
		# Log the raw response details
		# $this->loggerFactory->get('solrai')->info("(solrai_executeCurlRequest) Unique ID: $uniqueId | Raw Response: " . $response);

		# Debug
		# Log the decoded response details
		# $decodedResponse = json_decode($response, true);
		# $this->loggerFactory->get('solrai')->info("(solrai_executeCurlRequest) Unique ID: $uniqueId | Decoded Response: " . print_r($decodedResponse, true));

		# Debug
		# Get and log detailed cURL info
		# $curlInfo = curl_getinfo($curl);
		# $this->loggerFactory->get('solrai')->info("(solrai_executeCurlRequest) Unique ID: $uniqueId | cURL Info: " . print_r($curlInfo, true));

	  $endTime = microtime(true);
	  $elapsedTime = $endTime - $startTime;
	  // Add to global variable
	  $this->elapsedTime = $elapsedTime;

	  $error_msg = null;
	  try {
		if (curl_errno($curl)) {
		  $error_msg = curl_error($curl);
		  throw new \Exception('cURL error: ' . $error_msg);
		}
	  } catch (\Exception $e) {
		$this->loggerFactory->get('solrai')->error($e->getMessage());
	  }

	  curl_close($curl);

		if ($this->logElapsedTime === true) {
			// Extract the base domain from the URL
			$host = parse_url($url, PHP_URL_HOST);
			$baseDomain = implode('.', array_slice(explode('.', $host), -2));
			// Extract the model from the data array
			$model = isset($data['model']) ? $data['model'] : 'Not provided';
			// Log the information
			$this->loggerFactory->get('solrai')->info('API: ' . $baseDomain . ' | Elapsed time: ' . $elapsedTime . ' seconds' . ' | Model: ' . $model . ' | Method: ' . __FUNCTION__ . ' | Endpoint: ' . $url);
		}
	  
	  if ($error_msg) {
		return ['error' => $error_msg];
	  }

	  $responseBody = json_decode($response, true);
	  
	  // Append elapsed time to the response body
	  $responseBody['_elapsed_time'][$url] = $elapsedTime;

	  return $responseBody;
	}

So, I’m able to use this anywhere in my code whenever I want to call an OpenAI api (actually, use it for my Weaviate vector store calls as well).

1 Like

Personally ended up creating my own package for open AI API in PHP to allow mixed batches (various endpoints) run in parallel with back off strategy considering API rate limits…

Looking for skilled PHP devs to help clean the code and add unit tests (part time job)

<?php
// Replace $OPENAI_API_KEY with your actual OpenAI API key
$openaiApiKey = 'YOUR_OPENAI_API_KEY';

// API endpoint URL
$apiUrl = 'https://api.openai.com/v1/completions';

// Request data
$requestData = [
    "model" => "text-davinci-002",
    "prompt" => "Write an article about: hi\n",
    "temperature" => 0.7,
    "max_tokens" => 256,
    "top_p" => 1,
    "frequency_penalty" => 0,
    "presence_penalty" => 0
];

// Convert the data to JSON format
$jsonData = json_encode($requestData);

// cURL request
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    "Authorization: Bearer $openaiApiKey"
]);

// Execute cURL request
$response = curl_exec($ch);

// Check for errors
if (curl_errno($ch)) {
    echo 'Curl error: ' . curl_error($ch);
}

// Close cURL session
curl_close($ch);

// Output the API response
echo $response;
?>

davinci is depecrated, Use gpt-3.5-turbo instead of text-davinci-002

Hi Serge,
Sorry for the irrelevant question but while you were working on the PHP-based client, have you used PHP library Guzzle by any chance?

@stamatis.kourtis hi, yes. I finally ended up with 2 PHP clients (not all endpoints supported, only what I needed) :

  1. Based on WordPress wp_http class
  2. Wrapper for guzzle 7

Both supporting parallel requests

2 Likes

This question prompted me to look at my own code. I also have “guzzlehttp/guzzle” installed – but turns out I don’t need it. I do all of my endpoint calls using cURL. I think it is required by many API SDKs, but not necessary if you roll your own. I asked an LLM:

No, you don’t necessarily need Guzzle if you’re already using PHP cURL for your HTTP calls. Both cURL and Guzzle are capable of making HTTP requests, but they offer different features and approaches:

cURL:

  • Lower-level: cURL is a lower-level library that provides direct access to the underlying HTTP protocol. This gives you more control over the request and response, but it also requires more code and can be more complex to use.

  • Built-in: cURL is built into PHP, so you don’t need to install any additional libraries.

  • Widely supported: cURL is a very mature and widely supported library.

Guzzle:

  • Higher-level: Guzzle is a higher-level library that provides a more user-friendly interface for making HTTP requests. It handles many of the complexities of HTTP for you, such as setting headers, handling cookies, and parsing responses.

  • More features: Guzzle offers additional features such as request retries, middleware, and support for asynchronous requests.

  • Requires installation: Guzzle is not built into PHP, so you need to install it using Composer or another package manager.

Here’s a general guideline for choosing between cURL and Guzzle:

  • If you need fine-grained control over your HTTP requests or are working with a legacy codebase that already uses cURL, then cURL is a good choice.

  • If you want a more user-friendly interface and additional features, then Guzzle is a good choice.

Ultimately, the best choice depends on your specific needs and preferences.

Note: I have found this method extremely useful as my code now easily supports multiple models from multiple providers. I think AWS was the only one that gave me a hard time.

3 Likes

Thank you Serge for the confirmation.
I want to develop a real-time streaming text-to-speech plugin and Guzzle was recommended as a possible PHP solution. And hence I wanted to check with someone that had already used Guzzle.

1 Like

Thank you for the response. As a matter of fact I have used extensively cURL in my plugin which works great. However, I need to build a real-time streaming text-to-speech plugin and Guzzle was recommended (by ChatGPT of course) as a possible PHP solution.

1 Like