Add Sales Tax to an OpenAI Agents SDK or Claude Tool-Use Agent
One Python function, exposed as a tool. The model decides when a purchase or sale needs a tax figure; the AgentTax API does the arithmetic and says how sure it is. The same function plugs into the OpenAI Agents SDK and into Claude tool use.
Published November 18, 2026. The code on this page was tested against the production API on November 18, 2026; the testing section says exactly what ran.
What you are building
A calculate_sales_tax tool your agent calls before it approves a purchase or sends an invoice. The tool posts the transaction to POST /api/v1/calculate and hands the JSON back to the model. Nothing about tax lives in your prompt or your code: the model passes the facts it has (amount, state, ZIP, what is being bought, who the other party is) and the API returns the figure, the rate it used and a confidence score.
You can run every snippet on this page without signing up. With no API key the API serves a keyless demo lane of 10 calculate calls a day; a free key gives 1,500 calls a month and the full response.
pip install agenttax openai-agents anthropicStep 1: the tool function
Plain Python with type hints and a docstring. Both SDKs build the tool schema the model sees from those, so the docstring is worth writing carefully: it is the only documentation the model reads.
import os
from agenttax import AgentTaxClient, AgentTaxError
# No key = keyless demo mode (10 calculate calls a day per IP).
# A free key from agenttax.io gives 1,500 calls a month.
tax = AgentTaxClient(api_key=os.environ.get("AGENTTAX_API_KEY"))
def calculate_sales_tax(
amount: float,
buyer_state: str,
counterparty_id: str,
transaction_type: str = "compute",
role: str = "buyer",
buyer_zip: str | None = None,
work_type: str | None = None,
is_b2b: bool = False,
) -> dict:
"""Calculate US sales tax (role='seller') or use tax (role='buyer') for one transaction.
Args:
amount: Transaction amount in USD.
buyer_state: Two-letter US state code of the buyer, e.g. 'TX'.
counterparty_id: ID of the other agent or company in the deal.
transaction_type: e.g. 'compute', 'saas', 'api_access', 'consulting'.
role: 'buyer' for the buyer-side use tax figure, 'seller' for the seller-side figure.
buyer_zip: 5-digit ZIP, for the local rate.
work_type: e.g. 'compute', 'research', 'content', 'consulting' (see the API reference for all).
is_b2b: True if the buyer is a business.
"""
try:
return tax.calculate(
role=role,
amount=amount,
buyer_state=buyer_state,
transaction_type=transaction_type,
counterparty_id=counterparty_id,
buyer_zip=buyer_zip,
work_type=work_type,
is_b2b=is_b2b,
)
except AgentTaxError as exc:
# Hand the error back to the model as data instead of crashing the run.
return {"error": str(exc), "status_code": exc.status_code}Errors come back as data rather than exceptions. A model that sees {"error": ..., "status_code": 429} can tell the user it ran out of calls; a model whose tool raised mid-run usually cannot.
Step 2: the OpenAI Agents SDK
function_tool reads the signature and docstring and produces the JSON schema. Put the instruction that matters in the agent: call the tool, and report what it returned rather than a rate from memory.
# pip install agenttax openai-agents (needs OPENAI_API_KEY to run the model)
from agents import Agent, Runner, function_tool
from tools import calculate_sales_tax
tax_agent = Agent(
name="Purchasing agent",
instructions=(
"Before you approve a purchase, call calculate_sales_tax and report "
"total_tax, the rate and the confidence level it returns. Never guess a rate."
),
tools=[function_tool(calculate_sales_tax)],
)
if __name__ == "__main__":
result = Runner.run_sync(
tax_agent,
"We are buying $500 of GPU compute from gpu-provider-42. "
"We are a business in Austin, TX 78701. What tax do we owe?",
)
print(result.final_output)Step 3: Claude tool use
With the Anthropic Messages API you declare the schema yourself and run the loop: while Claude stops with tool_use, run each requested tool and send the results back as tool_result blocks.
# pip install agenttax anthropic (needs ANTHROPIC_API_KEY to run the model)
import json
import anthropic
from tools import calculate_sales_tax
TOOLS = [{
"name": "calculate_sales_tax",
"description": "Calculate US sales tax (role='seller') or use tax (role='buyer') "
"for one transaction. Returns total_tax, combined_rate and a confidence score.",
"input_schema": {
"type": "object",
"properties": {
"amount": {"type": "number", "description": "Amount in USD"},
"buyer_state": {"type": "string", "description": "Two-letter state code"},
"counterparty_id": {"type": "string", "description": "The other party's ID"},
"transaction_type": {"type": "string", "description": "compute, saas, api_access, ..."},
"role": {"type": "string", "enum": ["buyer", "seller"]},
"buyer_zip": {"type": "string", "description": "5-digit ZIP"},
"is_b2b": {"type": "boolean"},
},
"required": ["amount", "buyer_state", "counterparty_id"],
},
}]
def run_tool(name: str, tool_input: dict) -> str:
if name == "calculate_sales_tax":
return json.dumps(calculate_sales_tax(**tool_input))
return json.dumps({"error": f"unknown tool {name}"})
def ask(question: str, model: str = "claude-opus-5-5") -> str:
client = anthropic.Anthropic()
messages = [{"role": "user", "content": question}]
while True:
reply = client.messages.create(model=model, max_tokens=4096, tools=TOOLS, messages=messages)
if reply.stop_reason != "tool_use":
return "".join(b.text for b in reply.content if b.type == "text")
messages.append({"role": "assistant", "content": reply.content})
messages.append({"role": "user", "content": [
{"type": "tool_result", "tool_use_id": b.id, "content": run_tool(b.name, b.input)}
for b in reply.content if b.type == "tool_use"
]})
if __name__ == "__main__":
print(ask("We are buying $500 of GPU compute from gpu-provider-42. "
"We are a business in Austin, TX 78701. What tax do we owe?"))Claude Agent SDK and MCP clients can skip this loop entirely by connecting the AgentTax MCP server, which exposes the same calculation as a ready-made tool.
What the tool returns
The response is JSON the model can read directly. The fields worth telling the model about in your instructions:
total_taxandcombined_rate: the figure and the rate behind it.taxable_base: the gross amount, the amount the rate was applied to, and the ratio between them.confidence: ascorefrom 0 to 100 and alevel. Ask the model to repeat the level, so a person reviewing the run can see when a figure rests on a default.resolution: three short notes (location,nexus,taxability), each with astatus, abasisand a one-sentencedetailsaying how that part was decided.mode:"demo"on the keyless lane. Keyed calls add the jurisdiction breakdown, advisories and an audit trail.
Two inputs change the answer more than any other. role picks the side of the deal: "buyer" returns the buyer-side use tax figure, and "seller" returns the seller-side figure to collect, which for most states stays at 0 until you tell the API where you are registered through POST /api/v1/nexus. The response says when that is the reason, so read resolution.nexus and the advisories, not the total alone. transaction_type and work_type say what is being sold; a wrong value gives a confident wrong answer rather than an error, so pass what you actually know. The API reference lists every accepted value.
How we tested this page
On 18 November 2026 we ran the script below against production with no API key. It checks that the OpenAI Agents SDK accepts the function and derives its schema, calls the tool directly, and pushes a tool_use input through the Claude dispatcher. Both calls returned success: true. The model calls themselves need your own OpenAI or Anthropic key, so we did not run those.
"""Smoke test for the /guides/openai-agents-claude-sales-tax snippets.
Runs the tool layer against production with no API key (keyless demo mode),
and builds both agents without calling a model: the model calls need your own
OpenAI / Anthropic key, the tool calls do not. Uses 2 of the 10 keyless calls.
"""
import json
import openai_agent
import claude_agent
from tools import calculate_sales_tax
# 1. The OpenAI Agents SDK accepted the function as a tool and derived its schema.
tool = openai_agent.tax_agent.tools[0]
assert tool.name == "calculate_sales_tax", tool.name
assert {"amount", "buyer_state", "counterparty_id"} <= set(tool.params_json_schema["properties"])
# 2. A direct call reaches production and returns a determination.
r = calculate_sales_tax(500, "TX", "gpu-provider-42", buyer_zip="78701", work_type="compute", is_b2b=True)
assert r.get("success") is True, r
assert {"total_tax", "combined_rate", "confidence"} <= set(r), sorted(r)
# 3. The Claude dispatcher turns a tool_use input into a tool_result string.
out = json.loads(claude_agent.run_tool("calculate_sales_tax", {
"amount": 500, "buyer_state": "TX", "counterparty_id": "gpu-provider-42",
"transaction_type": "compute", "buyer_zip": "78701", "is_b2b": True,
}))
assert out.get("success") is True, out
print("ok", "mode=" + str(r.get("mode")), "keys=" + ",".join(sorted(r)))AgentTax returns calculations for information; they are not tax advice. See the disclaimer. More guides: all developer guides.
Run it against your own transactions
10 keyless calls a day to try it. A free key gives 1,500 calls a month with the full response, no card.