Skip to the main content

Text

Rewrite, create, edit and modify text content in multiple formats.

<Text> Server Component

Handles a text string or a React tree with content to rewrite or use for creating new content. Returns plain text, markdown or HTML.

Rewriting text

Live Example

Quantum formalism and the uncertainty principle

One consequence of the basic quantum formalism is the uncertainty principle. This principle states that no preparation of a quantum particle can imply simultaneously precise predictions both for a measurement of its position and for a measurement of its momentum. Both position and momentum are observables, represented by Hermitian operators. The position operator X and momentum operator P do not commute, but rather satisfy the canonical commutation relation.

Text rewrite example
<Text
  prompt="Summarize to one or two short paragraphs"
  grade={5}
  type="HTML"
  as="div"
  className="prose dark:prose-invert"
>
  <h2>Quantum formalism and the uncertainty principle</h2>
  <p>
    One consequence of the basic quantum formalism is the
    uncertainty principle. In its most familiar form, this states
    that no preparation of a quantum particle can imply
    simultaneously precise predictions both for a measurement of
    its position and for a measurement of its momentum.
  </p>
  <p>
    Both position and momentum are observables, meaning that they
    are represented by Hermitian operators. The position operator
    X and momentum operator P do not commute, but rather satisfy
    the canonical commutation relation.
  </p>
  <p>
    Given a quantum state, the Born rule lets us compute
    expectation values for both X and P, and moreover for powers
    of them.
  </p>
</Text>

Creating text

Live Example

A lizard so jolly and bright Bringing joy in the sun's warm light His scales shimmer with pure delight Bringing happiness, oh what a sight
Text creation example
<Text
  prompt="Write a poem"
  grade={5}
  type="HTML"
  as="div"
  className="prose dark:prose-invert"
>
  happy lizard
</Text>

useText hook

'use client'
 
import { useText } from '@trikinco/fullstack-components/client'
 
export default function Page() {
  const { isLoading, data } = useText({
    prompt:
      'Simplify and shorten this text, only return plain text',
    grade: 5,
    max: 250,
    content: `
        One consequence of the basic quantum formalism is the uncertainty 
        principle. In its most familiar form, this states that no 
        preparation of a quantum particle can imply simultaneously 
        precise predictions both for a measurement of its position 
        and for a measurement of its momentum.
        `,
  })
 
  if (isLoading) {
    return 'Loading text...'
  }
 
  // The content can also be rendered with next-mdx-remote or similar
  return <div className="mt-6">{data?.content}</div>
}

useText also accepts a tree of React components in content. Note that only static HTML is returned.

useText with HTML
const { isLoading, data } = useText({
  prompt: 'Simplify and shorten this text',
  content: (
    <>
      <h3>Quantum formalism and the uncertainty principle</h3>
      <p>
        One consequence of the basic quantum formalism is the
        uncertainty principle. In its most familiar form, this
        states that no preparation of a quantum particle can imply
        simultaneously precise predictions both for a measurement
        of its position and for a measurement of its momentum.
      </p>
    </>
  ),
})

Custom Server Component with getText

Server Component
import { getText } from '@trikinco/fullstack-components'
 
export default async function Page() {
  const response = await getText({
    tone: 'Ominous',
    content: 'Welcome to fullstack components',
    type: 'text',
  })
 
  // The content can also be rendered with next-mdx-remote or similar
  return <div className="mt-6">{response?.content}</div>
}

Setup

Add text: handleTextRequest() to the API route handler.

app/api/fsutils/[...fscomponents]/route.ts
import {
  handleFSComponents,
  handleTextRequest,
  type FSCOptions,
} from '@trikinco/fullstack-components'
 
const fscOptions: FSCOptions = {
  text: handleTextRequest({
    openAiApiKey: process.env.OPENAI_API_KEY || '',
  }),
  // Additional options and handlers...
}
 
const fscHandler = handleFSComponents(fscOptions)
 
export { fscHandler as GET, fscHandler as POST }

API Reference

Types

TextOptions

Text API route handler options.
Properties

openAiApiKeystring

  • default`process.env.OPENAI_API_KEY`.

TextRequestBodyinterface

Text request body.
Properties

contentstring

A text string, stringified HTML or a stringified React tree of the content to re/write.
  • example'Quantum formalism and the uncertainty principle'
  • noteIf a React tree is provided, use `fetchText`, `useText` or manually transform the tree to a HTML string.

promptstring

A text description of how to re/write the `content`.
  • example'Summarize the following text in a single, simple sentence.'

typetext | markdown | HTML

Enforce a content type for the output. Can be used to transform from one type to another. If not defined, the content type should match the input.
  • example'markdown'

tonestring

A text description defining the tone of voice of the content. If not defined, the tone of the input content is matched as closely as possible.
  • example'friendly and whimsical'

strengthRange<number, number>

A number between 0-100 of how heavily the content is modified. 0 returns the original content, 100 completely rewrites the content.
  • example50

gradenumber | string

A number or string that sets the readability level based on school grades. Higher numbers creates more complex and harder to read text. Lower numbers creates more readable text with simpler words.
  • example'5th-grade'

maxnumber

A number or the *desired* max amount of output text characters, not counting HTML markup if present.
  • example1000
  • noteResults vary and may subceed or exceed the desired amount of characters.

minnumber

A number of the *desired* minimum amount of output text characters, not counting HTML markup if present.
  • example100
  • noteResults vary and may subceed or exceed the desired amount of characters.

TextResponseinterface

Text response body.
Properties

typetext | markdown | HTML

The content type of the re/written content.
  • example'HTML'

contentstring

The re/written content.
  • example'<h1>Quantum formalism and the uncertainty principle</h1>'

ChatGptCompletionResponse

The response body for `getText`.
Properties

responseTextstring

The response text extracted from the completion message content.

tokensUsednumber

Total number of tokens used in the request (prompt + completion).

finishReasonstring

The reason the chat stopped. This will be `stop` if the model hit a natural stop point or a provided stop sequence, `length` if the maximum number of tokens specified in the request was reached, `content_filter` if content was omitted due to a flag from our content filters, `tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function.

errorMessagestring

The error message if there was an error.

Components

TextPropsinterface

Props to pass to the `<Text>` Server Component.
Properties

contentReactNode

A text string or a React tree with content to re/write. `children` takes precedence over `content` and accepts the same types.
  • example`<Title>Quantum formalism and the uncertainty principle</Title>`

promptstring

A text description of how to re/write the `content`.
  • example'Summarize the following text in a single, simple sentence.'

typetext | markdown | HTML

Enforce a content type for the output. Can be used to transform from one type to another. If not defined, the content type should match the input.
  • example'markdown'

tonestring

A text description defining the tone of voice of the content. If not defined, the tone of the input content is matched as closely as possible.
  • example'friendly and whimsical'

strengthRange<number, number>

A number between 0-100 of how heavily the content is modified. 0 returns the original content, 100 completely rewrites the content.
  • example50

gradenumber | string

A number or string that sets the readability level based on school grades. Higher numbers creates more complex and harder to read text. Lower numbers creates more readable text with simpler words.
  • example'5th-grade'

maxnumber

A number or the *desired* max amount of output text characters, not counting HTML markup if present.
  • example1000
  • noteResults vary and may subceed or exceed the desired amount of characters.

minnumber

A number of the *desired* minimum amount of output text characters, not counting HTML markup if present.
  • example100
  • noteResults vary and may subceed or exceed the desired amount of characters.

Textfunction

import { Text } from '@trikinco/fullstack-components'
Text Server Component that rewrites its children or `content` prop.
Parameters

propsAsComponent<C, TextProps>required

  • example`as` usage `<Text tone="Ominous" type="HTML" as="div" className="mb-3">Hello friend</Text>`
  • linkTextProps
returnsPromise<JSX.Element>

Hooks

useTextfunction

import { useText } from '@trikinco/fullstack-components/client'
A client-side fetch handler hook that generates text. Handles plain text `content` or transforms React trees to a HTML string.
Parameters

bodyTextParametersrequired

TextParameters extends TextRequestBody to allow for `content` to be a React tree.

configUseRequestConsumerConfig<TextRequestBody>

Fetch utility hook request options without the `fetcher`. Allows for overriding the default `request` config.
Returns

isLoadingboolean

Fetch loading state. `true` if the fetch is in progress.

isErrorboolean

Fetch error state. `true` if an error occurred.

errorunknown

Fetch error object if `isError` is `true`

dataTextResponse | undefined

Fetch response data if the fetch was successful.

refetchfunction

Refetches the data.
returnsundefined

Utilities

getTextfunction

import { getText } from '@trikinco/fullstack-components'
Rewrites, creates, edits and modifies text content for the web provided by the user. Server Action that calls the third-party API directly on the server. This avoids calling the Next.js API route handler allowing for performant Server Components.
Parameters

requestTextRequestBodyrequired

optionsTextOptions

returnsPromise<ChatGptCompletionResponse>

fetchTextfunction

import { fetchText } from '@trikinco/fullstack-components/client'
Rewrites, creates, edits and modifies text content for the web provided by the user. Handles plain text `content` or transforms React trees to a HTML string. Transforms numeric `grade` values to a string ordinal, e.g. `1` to `1st-grade`. Client-side fetch handler that calls the internal Next.js API route handler, then the third-party API. Best used for Client Components and functionality.
Parameters

bodyTextParametersrequired

TextParameters extends TextRequestBody to allow for `content` to be a React tree.

configRequestConfigOnly

Fetch utility request options without the `body`
returnsPromise<TextResponse>