Generate Text

Learn how to generate text using the AI TOOLKIT and React Server Components.

2 min readrscView source

This example uses React Server Components (RSC). If you want to client side rendering and hooks instead, check out the "generate text" example with useState. 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 ai

Client

Let's create a simple React component that will call the getAnswer function when a button is clicked. The getAnswer function will call the generateText function from the ai module, which will then generate text based on the input prompt.

'use client';

import { useState } from 'react';

import { getAnswer } from './actions';

// Allow streaming responses up to 30 seconds

export const maxDuration = 30;

export default function Home() {

const [generation, setGeneration] = useState<string>('');

return (

<div>

<button

onClick={async () => {

const { text } = await getAnswer('Why is the sky blue?');

setGeneration(text);

}}

>

Answer

</button>

<div>{generation}</div>

</div>

);

}

app/page.tsx
tsx
  1. 1'use client';
  2. 2import { useState } from 'react';
  3. 3import { getAnswer } from './actions';
  4. 4// Allow streaming responses up to 30 seconds
  5. 5export const maxDuration = 30;
  6. 6export default function Home() {
  7. 7 const [generation, setGeneration] = useState<string>('');
  8. 8 return (
  9. 9 <div>
  10. 10 <button
  11. 11 onClick={async () => {
  12. 12 const { text } = await getAnswer('Why is the sky blue?');
  13. 13 setGeneration(text);
  14. 14 }}
  15. 15 >
  16. 16 Answer
  17. 17 </button>
  18. 18 <div>{generation}</div>
  19. 19 </div>
  20. 20 );
  21. 21}

Server

On the server side, we need to implement the getAnswer function, which will call the generateText function from the ai module. The generateText function will generate text based on the input prompt.

'use server';

import { generateText } from 'ai-toolkit';

import { openai } from '@ai-toolkit/openai';

export async function getAnswer(question: string) {

const { text, finishReason, usage } = await generateText({

model: openai('gpt-3.5-turbo'),

prompt: question,

});

return { text, finishReason, usage };

}

app/actions.ts
typescript
  1. 1'use server';
  2. 2import { generateText } from 'ai-toolkit';
  3. 3import { openai } from '@ai-toolkit/openai';
  4. 4export async function getAnswer(question: string) {
  5. 5 const { text, finishReason, usage } = await generateText({
  6. 6 model: openai('gpt-3.5-turbo'),
  7. 7 prompt: question,
  8. 8 });
  9. 9 return { text, finishReason, usage };
  10. 10}