Fency.ai

Structured chat completion

Extract structured JSON data from text using a Zod schema.

This example demonstrates structured output extraction where free-form text is converted to validated JSON that matches a Zod schema. The model returns a complete structured response with no intermediate text events.

Prerequisites

You need a publishable key for the React SDK and a secret key for your server routes. This example uses sessions and client tokens to authenticate the client.

The example uses Clerk for user authentication. That is part of the app shell and not specific to Fency.

Server session routes

The example defines two session routes: one for stream sessions and one for agent task sessions.

Create a shared helper api/createFencySession.ts:

import 'server-only'

import { NextResponse } from 'next/server'

export async function createFencySession(body: Record<string, unknown>) {
  const secretKey = process.env.FENCY_SECRET_KEY
  if (!secretKey) {
    throw new Error('FENCY_SECRET_KEY is not defined.')
  }

  try {
    const response = await fetch('https://api.fency.ai/v1/sessions', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${secretKey}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(body),
    })
    const data = await response.json()
    return NextResponse.json(data, { status: response.status })
  } catch (error) {
    console.error('Fency session API error:', error)
    return NextResponse.json(
      { error: 'Failed to create session' },
      { status: 502 },
    )
  }
}

Create the stream session route at api/stream-session/route.ts:

import { NextResponse } from 'next/server'
import { getAuthorizedUserId } from '../../../auth'
import { createFencySession } from '../createFencySession'

export async function POST() {
  const userId = await getAuthorizedUserId()
  if (!userId) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }
  return createFencySession({ createStream: {} })
}

Create the agent task session route at api/agent-task-session/route.ts:

import { NextResponse } from 'next/server'
import { getAuthorizedUserId } from '../../../auth'
import { createFencySession } from '../createFencySession'

export async function POST() {
  const userId = await getAuthorizedUserId()
  if (!userId) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
  }
  return createFencySession({
    createAgentTask: {
      taskType: 'STRUCTURED_CHAT_COMPLETION',
      metadata: { userId },
    },
  })
}

Extraction schema

Define the extraction schema using Zod in extractionSchema.ts:

import { z } from 'zod'

export const extractionSchema = z.object({
  name: z.string().describe('Full name of the person'),
  role: z.string().describe('Job title or role'),
  company: z.string().describe('Company or organization'),
  email: z
    .string()
    .describe('Email address if mentioned, otherwise an empty string'),
  summary: z.string().describe('One-sentence summary of the person'),
})

export type Extraction = z.infer<typeof extractionSchema>

export const extractionJsonSchema = JSON.stringify(
  z.toJSONSchema(extractionSchema),
)

The schema descriptions guide the model on what to extract for each field.

Client provider and hooks

Load the Fency client and wrap your component tree with FencyProvider in page.tsx:

'use client'

import { loadFency } from '@fencyai/js'
import { FencyProvider } from '@fencyai/react'
import { Extractor } from './components/Extractor'

const fency = loadFency({
  publishableKey: process.env.NEXT_PUBLIC_FENCY_PUBLISHABLE_KEY!,
})

async function fetchCreateStreamClientToken() {
  const res = await fetch('/structured-chat-completion/api/stream-session', {
    method: 'POST',
  })
  if (!res.ok) {
    throw new Error('Failed to create stream session')
  }
  const data = (await res.json()) as { clientToken?: string }
  if (!data.clientToken) {
    throw new Error('No clientToken in session response')
  }
  return { clientToken: data.clientToken }
}

export default function StructuredChatCompletionPage() {
  return (
    <FencyProvider
      fency={fency}
      fetchCreateStreamClientToken={fetchCreateStreamClientToken}
    >
      <Extractor />
    </FencyProvider>
  )
}

Use useAgentTasks and createAgentTask to extract structured data in components/Extractor.tsx:

import { AgentTaskProgress, useAgentTasks } from '@fencyai/react'
import { useState } from 'react'
import {
  extractionJsonSchema,
  extractionSchema,
  type Extraction,
} from '../extractionSchema'

export function Extractor() {
  const [input, setInput] = useState('')
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [latestResult, setLatestResult] = useState<Extraction | null>(null)

  const { latest, createAgentTask } = useAgentTasks({})

  async function handleSubmit(event: React.FormEvent) {
    event.preventDefault()
    const trimmed = input.trim()
    if (!trimmed || isSubmitting) {
      return
    }

    setIsSubmitting(true)
    setLatestResult(null)

    try {
      const response = await createAgentTask(
        {
          type: 'StructuredChatCompletion',
          messages: [
            {
              role: 'SYSTEM',
              content:
                'Extract a single person record from the user text. Use empty strings for fields that are not mentioned.',
            },
            { role: 'USER', content: trimmed },
          ],
          model: 'anthropic/claude-sonnet-4.6',
          jsonSchema: extractionJsonSchema,
        },
        {
          fetchCreateAgentTaskClientToken: async () => {
            const res = await fetch(
              '/structured-chat-completion/api/agent-task-session',
              { method: 'POST' },
            )
            if (!res.ok) {
              throw new Error('Failed to create agent task session')
            }
            const data = (await res.json()) as { clientToken?: string }
            if (!data.clientToken) {
              throw new Error('No clientToken in session response')
            }
            return { clientToken: data.clientToken }
          },
        },
      )

      if (
        response.type !== 'success' ||
        response.response.taskType !== 'StructuredChatCompletion'
      ) {
        return
      }

      setLatestResult(
        extractionSchema.parse(
          JSON.parse(response.response.response.jsonResponse),
        ),
      )
    } catch {
      // Task errors also surface on latest.error
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <textarea
          value={input}
          onChange={(e) => setInput(e.target.value)}
          disabled={isSubmitting}
        />
        <button type="submit" disabled={isSubmitting || !input.trim()}>
          {isSubmitting ? 'Extracting...' : 'Extract record'}
        </button>
      </form>

      {isSubmitting && latest?.params.type === 'StructuredChatCompletion' ? (
        latest.error ? (
          <div>{latest.error.message}</div>
        ) : (
          <AgentTaskProgress agentTask={latest} />
        )
      ) : null}

      {latestResult ? <pre>{JSON.stringify(latestResult, null, 2)}</pre> : null}
    </div>
  )
}

The AgentTaskProgress component displays progress while the extraction task runs. The result is parsed with the Zod schema to ensure type safety.

Running locally

Clone the repository and install dependencies:

git clone https://github.com/fencyai/fency-react-examples.git
cd fency-react-examples
npm install

Copy .env.example to .env.local and add your Fency keys:

cp .env.example .env.local

Set the keys in .env.local:

FENCY_SECRET_KEY=sk_...
NEXT_PUBLIC_FENCY_PUBLISHABLE_KEY=pk_...

Initialize Clerk authentication (provisions a development app):

npx -y clerk@latest init --keyless -y

Start the development server:

npm run dev

Open http://localhost:3000/structured-chat-completion. Sign up from the header, then paste free text to extract structured JSON matching the schema.

On this page