Functions in Braintrust are atomic, reusable building blocks for executing AI-related logic. Functions are hosted and remotely executed in a performant serverless environment and are fully intended for production use. Functions can be invoked through the REST API, SDK, or UI, and have built-in support for streaming and structured outputs.Function types:
Prompts: LLM prompts with model configuration and templating (see Deploy prompts)
Tools: General-purpose code that LLMs can invoke to perform operations or access external data
Scorers: Functions for evaluating LLM output quality (returning a number from 0 to 1)
Agents: Chains of two or more prompts for multi-step workflows
Functions can be composed together to produce sophisticated applications without complex orchestration logic.In this diagram, a prompt is being invoked with an input and calls two different tools and scorers to ultimately produce a streaming output. Out of the box, you also get automatic tracing, including the tool calls and scores.Any function can be used as a tool. For example, a RAG agent can be defined as just two components:
A vector search tool that embeds a query, searches for relevant documents, and returns them
A system prompt with instructions for how to retrieve content and synthesize answers using the tool
Tools are functions that LLMs can call to perform complex operations or access external data. Create tools in code and push them to Braintrust:
TypeScript
Python
calculator.ts
Report incorrect code
Copy
Ask AI
import * as braintrust from "braintrust";import { z } from "zod";const project = braintrust.projects.create({ name: "calculator" });project.tools.create({ handler: ({ op, a, b }) => { switch (op) { case "add": return a + b; case "subtract": return a - b; case "multiply": return a * b; case "divide": return a / b; } }, name: "Calculator", slug: "calculator", description: "A simple calculator that can add, subtract, multiply, and divide.", parameters: z.object({ op: z.enum(["add", "subtract", "multiply", "divide"]), a: z.number(), b: z.number(), }), returns: z.number(), ifExists: "replace",});
Push to Braintrust:
Report incorrect code
Copy
Ask AI
npx braintrust push calculator.ts
calculator.py
Report incorrect code
Copy
Ask AI
from typing import Literalimport braintrustfrom pydantic import BaseModel, RootModelproject = braintrust.projects.create(name="calculator")class CalculatorInput(BaseModel): op: Literal["add", "subtract", "multiply", "divide"] a: float b: floatclass CalculatorOutput(RootModel[float]): passdef calculator(op, a, b): match op: case "add": return a + b case "subtract": return a - b case "multiply": return a * b case "divide": return a / bproject.tools.create( handler=calculator, name="Calculator", slug="calculator", description="A simple calculator that can add, subtract, multiply, and divide.", parameters=CalculatorInput, returns=CalculatorOutput,)