npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@ahnopologetic/use-prompt-api

v0.1.1

Published

A TypeScript library for Chrome's built-in Prompt API with structured output, function calling, and agentic workflows

Readme

use-prompt-api

A comprehensive TypeScript library for Chrome's built-in Prompt API with advanced features including structured output, function calling, agentic workflows, and React hooks integration.

Features

  • 🎯 Type-Safe: Full TypeScript support with strict typing
  • 🔄 Session Management: Persistent sessions with localStorage integration
  • 📊 Structured Output: Zod schema integration for validated responses
  • 🛠️ Function Calling: OpenAI-style function calling support
  • 🤖 Agentic Workflows: Multi-turn task execution with planning and reflection
  • ⚛️ React Hooks: Seamless React integration
  • 📡 Streaming: Full streaming support with custom renderers
  • 💾 Quota Management: Smart quota tracking and warnings

Installation

npm install @ahnopologetic/use-prompt-api zod
# or
pnpm add @ahnopologetic/use-prompt-api zod
# or
yarn add @ahnopologetic/use-prompt-api zod

Prerequisites

This library requires Chrome 128+ with the Prompt API origin trial enabled. Learn more at Chrome AI Documentation.

Quick Start

Basic Usage

import { PromptClient } from '@ahnopologetic/use-prompt-api';

// Initialize the client
const client = new PromptClient();
await client.initialize();

// Create a session
const session = await client.createSession({
  systemPrompt: 'You are a helpful assistant',
  temperature: 0.7,
});

// Prompt the model
const response = await session.prompt('What is the capital of France?');
console.log(response);

Streaming Responses

const stream = session.promptStreaming('Tell me a story');
const reader = stream.getReader();

while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  console.log(value); // Print each chunk as it arrives
}

Structured Output with Zod

import { z } from 'zod';
import { promptWithStructure } from '@ahnopologetic/use-prompt-api';

const personSchema = z.object({
  name: z.string(),
  age: z.number(),
  email: z.string().email(),
});

const result = await promptWithStructure(
  session,
  'Extract person info: John Doe, 30 years old, [email protected]',
  { schema: personSchema }
);

console.log(result); // { name: 'John Doe', age: 30, email: '[email protected]' }

Function Calling

import { FunctionRegistry, createFunctionDefinition } from '@ahnopologetic/use-prompt-api';

const registry = new FunctionRegistry();

registry.register(
  createFunctionDefinition(
    'getWeather',
    'Get the current weather for a location',
    {
      type: 'object',
      properties: {
        location: { type: 'string', description: 'City name' },
      },
      required: ['location'],
    },
    async ({ location }: { location: string }) => {
      // Your weather API call here
      return { temperature: 72, condition: 'sunny' };
    }
  )
);

Basic Agent

import { BasicAgent } from '@ahnopologetic/use-prompt-api';

const agent = new BasicAgent({
  maxIterations: 10,
  functions: [weatherFunction, calculatorFunction],
  systemPrompt: 'You are a helpful assistant',
  onStep: (step) => console.log('Step:', step.iteration),
});

const result = await agent.run('What is the weather in Paris and Tokyo?');
console.log(result.finalAnswer);

Advanced Agent with Planning

import { AdvancedAgent } from '@ahnopologetic/use-prompt-api';

const agent = new AdvancedAgent({
  maxIterations: 20,
  functions: [...],
  enablePlanning: true,
  maxReflections: 2,
});

const result = await agent.runWithPlanning('Research and summarize AI trends in 2024');

React Integration

Basic Hook

import { usePromptAPI } from '@ahnopologetic/use-prompt-api/react';

function ChatComponent() {
  const { prompt, ready, loading, error, quota } = usePromptAPI({
    systemPrompt: 'You are a helpful assistant',
  });

  const [response, setResponse] = useState('');

  const handleSubmit = async (message: string) => {
    const result = await prompt(message);
    setResponse(result);
  };

  if (!ready) return <div>Loading AI model...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <QuotaDisplay quota={quota} />
      <ChatInterface onSubmit={handleSubmit} response={response} />
    </div>
  );
}

Structured Output Hook

import { useStructuredPrompt } from '@ahnopologetic/use-prompt-api/react';
import { z } from 'zod';

const taskSchema = z.object({
  title: z.string(),
  priority: z.enum(['low', 'medium', 'high']),
  dueDate: z.string(),
});

function TaskExtractor() {
  const { prompt, data, loading } = useStructuredPrompt({
    schema: taskSchema,
  });

  const extractTask = async (text: string) => {
    const task = await prompt(`Extract task from: ${text}`);
    console.log(task); // Fully typed!
  };

  return <TaskForm onExtract={extractTask} loading={loading} />;
}

Function Calling Hook

import { useFunctionCalling } from '@ahnopologetic/use-prompt-api/react';

function AssistantComponent() {
  const { prompt, results, loading } = useFunctionCalling({
    functions: [weatherFunction, calculatorFunction],
    autoExecute: true,
  });

  return <Assistant onPrompt={prompt} results={results} />;
}

Agent Hook

import { useAgent } from '@ahnopologetic/use-prompt-api/react';

function AgentComponent() {
  const { run, steps, status, progress } = useAgent({
    maxIterations: 10,
    functions: [...],
  });

  return (
    <div>
      <button onClick={() => run('Complete this task...')}>Start</button>
      <Progress value={progress} />
      <StepsList steps={steps} />
    </div>
  );
}

API Reference

Core Classes

PromptClient

High-level client for managing sessions.

const client = new PromptClient();
await client.initialize();
const session = await client.createSession(options);

SessionManager

Manages individual conversation sessions.

const manager = new SessionManager();
await manager.create({ systemPrompt: '...' });
const response = await manager.prompt('Hello');

Structured Output

promptWithStructure<T>

Get structured output validated against a Zod schema.

const result = await promptWithStructure<PersonType>(session, prompt, {
  schema: personSchema,
  maxRetries: 3,
});

Function Calling

FunctionRegistry

Manage available functions for the AI.

const registry = new FunctionRegistry();
registry.register(functionDefinition);
registry.list(); // Get all functions

Agents

BasicAgent

Simple multi-turn task execution.

const agent = new BasicAgent({
  maxIterations: 10,
  functions: [...],
  onStep: (step) => {...},
});

AdvancedAgent

Agent with planning and reflection.

const agent = new AdvancedAgent({
  maxIterations: 20,
  enablePlanning: true,
  maxReflections: 2,
});

Examples

See the examples directory for complete working examples:

Run Examples

# TypeScript examples (requires pnpm install)
pnpm example:basic         # Basic chat
pnpm example:functions     # Function calling
pnpm example:agent         # Basic agent
pnpm example:advanced      # Advanced agent
pnpm example:streaming     # Streaming agent ⭐
pnpm example:structured    # Structured output

# Browser examples
# Open examples/streaming-agent.html in Chrome

Documentation

Browser Support

  • Chrome 128+ (with Prompt API origin trial enabled)
  • Edge 128+ (with origin trial)

Contributing

Contributions are welcome! Please read our contributing guidelines before submitting PRs.

License

MIT

Acknowledgments

Built for Chrome's built-in Prompt API. Learn more at Chrome AI Documentation.