I prepare integration openAI API with Codeigniter 4, for this I use library:
https://github.com/orhanerday/open-ai
I write controller CI4:
public function openAIPost()
{
$response = array();
if ($this->request->getMethod() === 'post'){
question = $this->request->getPost('question');
$open_ai_key = getenv('OPENAI_API_KEY');
$open_ai = new OpenAi($open_ai_key);
$complete = $open_ai->chat([
'model' => 'gpt-3.5-turbo',
'messages' => [
[
"role" => "user",
"content" => $question
]
],
'temperature' => 1.0,
'max_tokens' => 10,
'frequency_penalty' => 0,
'presence_penalty' => 0,
]);
$response['complete'] = $complete;
}
echo json_encode($response);
}
But I get in output:
{
"id": "chatcmpl-6xxhQ2FLm08VhE8KKHsTpilkvpMTS",
"object": "chat.completion",
"created": 1679748856,
"model": "gpt-3.5-turbo-0301",
"usage": {
"prompt_tokens": 9,
"completion_tokens": 10,
"total_tokens": 19
},
"choices": [{
"message": {
"role": "assistant",
"content": "This is a test of the AI language model."
},
"finish_reason": "length",
"index": 0
}]
}
How to get only content from response?
You should all you need in the JSON response returned by the OpenAI API you have.
You should navigate the JSON object and extract the message content using the following line.
$content = $complete.choices[0].message.content
it should give you "This is a test of the AI language model."