I created a Chatbot for a fun side project using the OpenAI API.
The prompt I’m testing is, “With Laravel, create a custom attribute in the User Model to get the users full name and explain it to me.”
The Json from the API gives me sentences and code.
- I want to convert the sentences to
<p>
tags - Convert code section into code blocks
<pre><code>
- Then render in the view using Tailwind CSS prose class.
Pretty much like the Markdown you are currently reading on this question.
I’m using the package: spatie/commonmark-highlighter as it seems like it should be able to handle this, but it’s falling short.
Code to get Json to Html:
//API Stuff Above here...
$responseBody = json_decode($response->getBody(), true);
$textForMarkdown = $responseBody['choices'][0]['text'];
dd($textForMarkdown);
Outputs:
"""
\n
\n
In your User model, you can create a custom attribute for the fullname by adding the following code:
\n
public function getFullNameAttribute()
{\n
return $this->first_name . ' ' . $this->last_name;\n
}
"""
Then I pass through CommonMark:
$environment = new Environment();
$environment->addExtension(new CommonMarkCoreExtension());
$environment->addRenderer(FencedCode::class, new FencedCodeRenderer(['html', 'php', 'js']));
$environment->addRenderer(IndentedCode::class, new IndentedCodeRenderer(['html', 'php', 'js']));
$markdownConverter = new MarkdownConverter($environment);
$this->generatedText = (string) $markdownConverter->convert($textForMarkdown);
dd($this->generatedText);
Outputs:
"""
<p>In your User model, you can create a custom attribute for the fullname by adding the following code:</p>
<p>public function getFullNameAttribute()\n
{\n
return $this->first_name . ' ' . $this->last_name;\n
}</p>\n
"""
How could I get it to output like this? Note the <pre><code>
tags:
<p>In your User model, you can create a custom attribute for the fullname by adding the following code:</p>
<pre><code>public function getFullNameAttribute()\n
{\n
return $this->first_name . ' ' . $this->last_name;\n
}</code</pre>\n
Would I need to use another package to recognize the php code?
If so what package would do the trick?
I wish the API would output the three back tics ```
. Would make things so much easier. If this was the case I wouldn’t need to do any of the above.