Integration guide

Using OpenVerb with OpenAI and Anthropic

Turn an OpenVerb verb library into native tool definitions for OpenAI function calling and Anthropic tool use, then run every call through one executor, in JavaScript and Python.

Last reviewed

OpenAI calls it function calling; Anthropic calls it tool use. Both let a model ask your code to run a named action with structured arguments. An OpenVerb verb library is a single JSON description of those actions that you can turn into either provider's format, so your app defines its actions once and every call, whichever model made it, goes through the same executor.

What you'll build

  1. Load the OpenVerb core library and register handlers for two verbs.
  2. Convert each verb into a JSON Schema the providers accept.
  3. Run a tool-calling loop against OpenAI and against Anthropic, executing every call through OpenVerb.
  4. Gate destructive verbs behind a confirmation step, using flags the verb already carries.

1. Install

terminal
# JavaScript
npm install openverb openai @anthropic-ai/sdk

# Python
pip install openverb openai anthropic

2. Load the library and register handlers

The openverb package ships the openverb.core library. A handler receives the action's params and returns a result with a status of success or error.

agent.mjs
import { createRequire } from 'node:module';
import { loadLibrary, createExecutor } from 'openverb';

const require = createRequire(import.meta.url);
const library = loadLibrary(require('openverb/openverb.core.json'));
const executor = createExecutor(library);

const db = {};
executor.register('create_item', ({ collection, data }) => {
  db[collection] ??= [];
  const item = { id: String(db[collection].length), ...data };
  db[collection].push(item);
  return { verb: 'create_item', status: 'success', data: item };
});

executor.register('list_items', ({ collection }) => ({
  verb: 'list_items',
  status: 'success',
  data: { items: db[collection] ?? [] },
}));

3. Turn verbs into tool definitions

Both providers describe arguments with JSON Schema. OpenVerb params are close to it, but the core library uses two shorthand types, enum and array<string>, that need translating. This converter handles every verb in openverb.core:

agent.mjs (continued)
// OpenVerb param types -> JSON Schema.
// The core library uses 'enum' and 'array<string>', which JSON Schema spells differently.
function paramToSchema(p) {
  const base = { description: p.description };
  if (p.type === 'enum') return { ...base, type: 'string', enum: p.enum };
  const arr = /^array<(.+)>$/.exec(p.type);
  if (arr) return { ...base, type: 'array', items: { type: arr[1] } };
  return { ...base, type: p.type };
}

function verbToJsonSchema(verb) {
  const properties = {};
  const required = [];
  for (const [name, p] of Object.entries(verb.params ?? {})) {
    properties[name] = paramToSchema(p);
    if (p.required) required.push(name);
  }
  return { type: 'object', properties, required };
}

// Only expose the verbs you've written handlers for.
const enabled = ['create_item', 'list_items'].map((name) => executor.getVerb(name));

4. Route every call through one function

Verbs carry destructive and requires_confirmation flags (in the core library, delete_item, write_file, delete_file and run_command set them). Checking them in one place means a model can never delete something without the user agreeing, regardless of which provider asked. executor.execute then rejects unknown verbs and missing required params before your handler runs.

agent.mjs (continued)
// One place where every model-requested action goes through.
async function runAction(action) {
  const verb = executor.getVerb(action.verb);
  if (verb?.destructive || verb?.requires_confirmation) {
    const ok = await askUserToConfirm(verb, action.params); // your UI
    if (!ok) return { verb: action.verb, status: 'error', error_message: 'Declined by user' };
  }
  return executor.execute(action); // validates the verb and its required params
}

5a. OpenAI function calling

Pass the converted verbs as tools, run any tool_calls the model returns, and send each result back as a tool message until the model answers in plain text.

openai.mjs
import OpenAI from 'openai';

const openai = new OpenAI(); // reads OPENAI_API_KEY
const model = process.env.OPENAI_MODEL; // any current model with tool calling

const tools = enabled.map((verb) => ({
  type: 'function',
  function: { name: verb.name, description: verb.description, parameters: verbToJsonSchema(verb) },
}));

const messages = [{ role: 'user', content: 'Add a project for Smith Construction, then list all projects.' }];

while (true) {
  const response = await openai.chat.completions.create({ model, messages, tools });
  const message = response.choices[0].message;
  messages.push(message);

  if (!message.tool_calls?.length) {
    console.log(message.content);
    break;
  }

  for (const call of message.tool_calls) {
    const result = await runAction({
      verb: call.function.name,
      params: JSON.parse(call.function.arguments),
    });
    messages.push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify(result) });
  }
}

5b. Anthropic tool use

Claude takes the same schema as input_schema. When stop_reason is tool_use, run each tool_use block and return every result in a single user message. This example also opts into server-side fallbacks, so if the model declines a request the API retries it on a fallback model within the same call; check for a refusal stop reason either way.

anthropic.mjs
import Anthropic from '@anthropic-ai/sdk';

const anthropic = new Anthropic(); // reads ANTHROPIC_API_KEY

const tools = enabled.map((verb) => ({
  name: verb.name,
  description: verb.description,
  input_schema: verbToJsonSchema(verb),
}));

const messages = [{ role: 'user', content: 'Add a project for Smith Construction, then list all projects.' }];

while (true) {
  const response = await anthropic.beta.messages.create({
    model: 'claude-opus-5-5',
    max_tokens: 16000,
    tools,
    messages,
    // If the model declines, retry on a fallback model inside the same call.
    betas: ['server-side-fallback-2026-07-01'],
    fallbacks: 'default',
  });

  if (response.stop_reason === 'refusal') {
    console.log('Request declined:', response.stop_details?.explanation);
    break;
  }

  messages.push({ role: 'assistant', content: response.content });

  if (response.stop_reason !== 'tool_use') {
    for (const block of response.content) if (block.type === 'text') console.log(block.text);
    break;
  }

  const results = [];
  for (const block of response.content) {
    if (block.type !== 'tool_use') continue;
    const result = await runAction({ verb: block.name, params: block.input });
    results.push({
      type: 'tool_result',
      tool_use_id: block.id,
      content: JSON.stringify(result),
      is_error: result.status === 'error',
    });
  }
  // All results for one turn go back in a single user message.
  messages.push({ role: 'user', content: results });
}

The same thing in Python

The Python package mirrors the JavaScript one: load_core_library, create_executor, register, execute and get_verb.

agent.py
import json, os, re
from openverb import load_core_library, create_executor

library = load_core_library()
executor = create_executor(library)
db = {}

def create_item(params):
    items = db.setdefault(params['collection'], [])
    item = {'id': str(len(items)), **params['data']}
    items.append(item)
    return {'verb': 'create_item', 'status': 'success', 'data': item}

def list_items(params):
    return {'verb': 'list_items', 'status': 'success',
            'data': {'items': db.get(params['collection'], [])}}

executor.register('create_item', create_item)
executor.register('list_items', list_items)

def param_to_schema(p):
    base = {'description': p.get('description', '')}
    if p['type'] == 'enum':
        return {**base, 'type': 'string', 'enum': p['enum']}
    m = re.fullmatch(r'array<(.+)>', p['type'])
    if m:
        return {**base, 'type': 'array', 'items': {'type': m.group(1)}}
    return {**base, 'type': p['type']}

def verb_to_json_schema(verb):
    params = verb.get('params', {})
    return {
        'type': 'object',
        'properties': {name: param_to_schema(p) for name, p in params.items()},
        'required': [name for name, p in params.items() if p.get('required')],
    }

enabled = [executor.get_verb(n) for n in ('create_item', 'list_items')]

def run_action(action):
    verb = executor.get_verb(action['verb']) or {}
    if verb.get('destructive') or verb.get('requires_confirmation'):
        if not ask_user_to_confirm(verb, action.get('params')):  # your UI
            return {'verb': action['verb'], 'status': 'error', 'error_message': 'Declined by user'}
    return executor.execute(action)
openai_agent.py
from openai import OpenAI

client = OpenAI()  # reads OPENAI_API_KEY
tools = [{'type': 'function', 'function': {
    'name': v['name'], 'description': v['description'], 'parameters': verb_to_json_schema(v)}}
    for v in enabled]

messages = [{'role': 'user', 'content': 'Add a project for Smith Construction, then list all projects.'}]
while True:
    response = client.chat.completions.create(
        model=os.environ['OPENAI_MODEL'], messages=messages, tools=tools)
    message = response.choices[0].message
    messages.append(message)
    if not message.tool_calls:
        print(message.content)
        break
    for call in message.tool_calls:
        result = run_action({'verb': call.function.name,
                             'params': json.loads(call.function.arguments)})
        messages.append({'role': 'tool', 'tool_call_id': call.id, 'content': json.dumps(result)})
anthropic_agent.py
import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY
tools = [{'name': v['name'], 'description': v['description'],
          'input_schema': verb_to_json_schema(v)} for v in enabled]

messages = [{'role': 'user', 'content': 'Add a project for Smith Construction, then list all projects.'}]
while True:
    response = client.beta.messages.create(
        model='claude-opus-5-5',
        max_tokens=16000,
        tools=tools,
        messages=messages,
        betas=['server-side-fallback-2026-07-01'],
        fallbacks='default',
    )
    if response.stop_reason == 'refusal':
        print('Request declined:', response.stop_details and response.stop_details.explanation)
        break
    messages.append({'role': 'assistant', 'content': response.content})
    if response.stop_reason != 'tool_use':
        print(''.join(b.text for b in response.content if b.type == 'text'))
        break
    results = []
    for block in response.content:
        if block.type == 'tool_use':
            result = run_action({'verb': block.name, 'params': block.input})
            results.append({'type': 'tool_result', 'tool_use_id': block.id,
                            'content': json.dumps(result),
                            'is_error': result['status'] == 'error'})
    messages.append({'role': 'user', 'content': results})

Production checklist

  • Expose only what you handle. Build tools from the verbs you registered, not the whole library; an advertised verb with no handler returns an error.
  • Return errors to the model. Send a failed result back (with is_error on Anthropic) so the model can correct its arguments instead of stopping.
  • Validate beyond presence. The executor checks that required params exist; check types, ranges and permissions inside your handlers.
  • Log every action. Because every call passes through runAction, that is the one place to record who asked for what, and the Universal Action Ledger can collect those records for you.
OpenVerb Sandbox

Paste a Verb Library JSON schema here to define what actions the AI can perform.

Ask the AI to perform a task. It will use the vocabulary defined in your library.

The AI proposes a structured action based on your library vocabulary.

Waiting for prompt...

OpenVerb Core intercepts the AI's action and validates it before execution.

Verb exists in library
Payload matches JSON Schema
Policy requirements passed
Inputs valid and sanitized

The validated action is routed to the application backend for execution.

Waiting...

OpenVerb Core generates an execution receipt for full auditability.

Waiting for execution...