Skip to content

Fulcrum SDK Code Examples

This guide provides practical code examples for common Fulcrum use cases using both the Python and TypeScript SDKs.

1. Basic Policy Enforcement

Protect an agent action by checking it against active policies.

Python

from fulcrum import FulcrumClient

client = FulcrumClient(host="localhost:50051", api_key="dev-key")

with client.envelope(workflow_id="customer-support") as env:
    # Context for policy evaluation
    context = {
        "user_role": "basic_user",
        "resource": "refund_api"
    }

    if env.guard("execute_refund", context):
        print("Refund authorized")
        # Perform action...
    else:
        print("Refund denied by policy")

TypeScript

import { FulcrumClient } from '@fulcrum-governance/sdk';

const client = new FulcrumClient({
  host: 'localhost:50051',
  apiKey: 'dev-key'
});

await client.envelope('customer-support', async (env) => {
  const context = {
    user_role: 'basic_user',
    resource: 'refund_api'
  };

  if (await env.guard('execute_refund', context)) {
    console.log('Refund authorized');
    // Perform action...
  } else {
    console.log('Refund denied by policy');
  }
});

2. Cost Tracking

Track token usage and costs for LLM interactions.

Python

with client.envelope(workflow_id="summarizer") as env:
    # ... LLM call ...
    usage = {
        "model": "gpt-4",
        "input_tokens": 1500,
        "output_tokens": 200,
        "cost_usd": 0.06
    }
    env.track_cost(usage)

TypeScript

await client.envelope('summarizer', async (env) => {
  // ... LLM call ...
  env.trackCost({
    model: 'gpt-4',
    input_tokens: 1500,
    output_tokens: 200,
    cost_usd: 0.06
  });
});

3. Custom Event Logging

Log application-specific events for the audit trail.

Python

env.log("tool_use", {
    "tool_name": "calculator",
    "inputs": "5 * 5",
    "result": "25"
})

TypeScript

env.log('tool_use', {
  tool_name: 'calculator',
  inputs: '5 * 5',
  result: '25'
});