Generate Text
Learn how to generate text using the AI TOOLKIT and Next.js.
A situation may arise when you need to generate text based on a prompt. For example, you may want to generate a response to a question or summarize a body of text. The generateText function can be used to generate text based on the input prompt.
Run it locally
$ npm install aiClient
Let's create a simple React component that will make a POST request to the /api/completion endpoint when a button is clicked. The endpoint will generate text based on the input prompt.
'use client';
import { useState } from 'react';
export default function Page() {
const [generation, setGeneration] = useState('');
const [isLoading, setIsLoading] = useState(false);
return (
<div>
<div
onClick={async () => {
setIsLoading(true);
await fetch('/api/completion', {
method: 'POST',
body: JSON.stringify({
prompt: 'Why is the sky blue?',
}),
}).then(response => {
response.json().then(json => {
setGeneration(json.text);
setIsLoading(false);
});
});
}}
>
Generate
</div>
{isLoading ? 'Loading...' : generation}
</div>
);
}
- 1'use client';
- 2import { useState } from 'react';
- 3export default function Page() {
- 4 const [generation, setGeneration] = useState('');
- 5 const [isLoading, setIsLoading] = useState(false);
- 6 return (
- 7 <div>
- 8 <div
- 9 onClick={async () => {
- 10 setIsLoading(true);
- 11 await fetch('/api/completion', {
- 12 method: 'POST',
- 13 body: JSON.stringify({
- 14 prompt: 'Why is the sky blue?',
- 15 }),
- 16 }).then(response => {
- 17 response.json().then(json => {
- 18 setGeneration(json.text);
- 19 setIsLoading(false);
- 20 });
- 21 });
- 22 }}
- 23 >
- 24 Generate
- 25 </div>
- 26 {isLoading ? 'Loading...' : generation}
- 27 </div>
- 28 );
- 29}
Server
Let's create a route handler for /api/completion that will generate text based on the input prompt. The route will call the generateText function from the ai module, which will then generate text based on the input prompt and return it.
import { generateText } from 'ai-toolkit';
export async function POST(req: Request) {
const { prompt }: { prompt: string } = await req.json();
const { text } = await generateText({
model: 'openai/gpt-4o',
system: 'You are a helpful assistant.',
prompt,
});
return Response.json({ text });
}
---
<GithubLink link="https://github.com/khulnasoft/ai-toolkit/blob/main/examples/next-openai-pages/pages/basics/generate-text/index.tsx" />
- 1import { generateText } from 'ai-toolkit';
- 2export async function POST(req: Request) {
- 3 const { prompt }: { prompt: string } = await req.json();
- 4 const { text } = await generateText({
- 5 model: 'openai/gpt-4o',
- 6 system: 'You are a helpful assistant.',
- 7 prompt,
- 8 });
- 9 return Response.json({ text });
- 10}