Forge
Skip to main content

Python tutorial: Financial agent observability with W&B Weave

Learn how to make LLM agents transparent and production-ready by instrumenting a financial multi-agent pipeline with W&B Weave.
Last updated: April 17, 2026
Build a fully observable financial analysis pipeline in Python using W&B Weave. By the end, you'll have a multi-agent system that ingests financial data, computes the Altman Z-Score, runs LLM-based credit risk assessment, and generates an executive summary, with every step traced and inspectable in the Weave dashboard.
What you'll learn:
  • How to instrument agent functions with @weave.op() for automatic tracing
  • How Weave constructs hierarchical trace trees from nested function calls
  • How to attach structured metadata to spans for filtering and debugging
  • How to inspect prompts, LLM responses, and latency in the Weave UI
What you'll build:
  • A data ingestion agent that fetches financial statements
  • A feature extraction agent that computes ratios and the Altman Z-Score
  • A risk assessment agent that uses a local LLM to rate credit risk
  • A reporting agent that generates an executive summary
  • An orchestrator that ties them together into a single traced pipeline
Prerequisites: A Weights & Biases account (free tier works) and Python 3.9+. No paid LLM APIs required, we'll use a local open-source model.

Setup and dependencies

Install the required packages:
pip install wandb weave llama-cpp-python python-dotenv --quiet
Now import the libraries and initialize Weave. You'll need your W&B API key, which you can find at wandb.ai/authorize. The project name can be anything; it's where your traces will appear in the Weights & Biases dashboard.
import os
import time
import weave
from llama_cpp import Llama

os.environ["WANDB_API_KEY"] = "<Your Wandb API KEY>"
weave.init('<Project Name>')
When weave.init() runs successfully, you'll see output confirming the connection and a link to your project. Click it to open the Weave dashboard; it'll be empty for now, but every traced function call from here on will appear there.



Loading the local LLM

We'll use TinyLlama, a small open-source model that runs locally. The from_pretrained method downloads the quantised model file automatically from Hugging Face:
llm = Llama.from_pretrained(
repo_id="TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF",
filename="tinyllama-1.1b-chat-v1.0.Q2_K.gguf",
)
This will take a moment on the first run while the model (~500MB) downloads. You'll see progress output from llama-cpp-python as it loads the weights. Once it finishes, the model is ready for local inference. No API keys or network calls needed for the LLM itself.


Agent 1: Data ingestion

The first agent fetches financial statement data for a given company. In production, this would call the SEC EDGAR API or a market data provider; here, we'll use mock data to keep the focus on observability.
Notice two things in the code below.
  • First, @weave.op(name="data_ingestion"): this decorator is all Weave needs to trace the function. Every call will automatically record the inputs, outputs, and execution time.
    Second, weave.attributes(): this attaches structured metadata (ticker, fiscal year, data source) to the span, which you can later use to filter and search traces in the dashboard.
#Ingestion Agent
@weave.op(name="data_ingestion")
def fetch_financial_data(ticker: str, fiscal_year: int) -> dict:
with weave.attributes({
"ticker": ticker,
"fiscal_year": fiscal_year,
"data_source": "MOCK_SEC",
}):
financial_data = {
"revenue": 25_000_000_000,
"net_income": 5_000_000_000,
"total_assets": 50_000_000_000,
"total_liabilities": 30_000_000_000,
"cash": 10_000_000_000,
}
return financial_data
What to look for in Weave: After you run this function, open your project dashboard. You'll see a data_ingestion trace. Click into it, and you'll find the full input arguments (ticker="AAPL", fiscal_year=2023) on the left, the returned dictionary on the right, and the custom attributes (ticker, fiscal year, data source) in the metadata panel.



Agent 2: Feature extraction (Altman Z-Score)

The feature extraction agent computes financial ratios and the Altman Z-Score from the raw data. This is split into two functions, both decorated with @weave.op().
Define the Z-Score calculation first, since the ratios function will call it:
# Feature Extraction Agent
@weave.op(name="calculate_z_score")
def calculate_z_score(data: dict) -> float:
working_capital = data["cash"] - (data["total_liabilities"] * 0.3)
retained_earnings = data["net_income"] * 0.5
ebit = data["net_income"] * 1.2

X1 = working_capital / data["total_assets"]
X2 = retained_earnings / data["total_assets"]
X3 = ebit / data["total_assets"]
X4 = (data["total_assets"] - data["total_liabilities"]) / data["total_liabilities"]
X5 = data["revenue"] / data["total_assets"]

return 1.2 * X1 + 1.4 * X2 + 3.3 * X3 + 0.6 * X4 + 1.0 * X5

Observability output :


Here, we shall be calculating a few basic ratios to determine the profit_margin, roa, debt_to_equity ratio, current_ratio, which will form the parameters to calculate the Altman-z score.
@weave.op(name="feature_extraction")
def calculate_financial_ratios(financial_data: dict) -> dict:
ratios = {
"profit_margin": financial_data["net_income"] / financial_data["revenue"],
"roa": financial_data["net_income"] / financial_data["total_assets"],
"debt_to_equity": financial_data["total_liabilities"]
/ (financial_data["total_assets"] - financial_data["total_liabilities"]),
"current_ratio": financial_data["cash"] / (financial_data["total_liabilities"] * 0.3),
}
ratios["z_score"] = calculate_z_score(financial_data)
return ratios
What to look for in Weave: This is where you first see Weave's automatic hierarchy in action. Because both functions are decorated and one calls the other, Weave nests calculate_z_score as a child span inside feature_extraction. In the trace view, expand the feature_extraction span, and you'll see the child call with its own inputs, output (the Z-Score float), and timing. No manual wiring required.


Agent 3: Risk assessment (LLM-based)

The risk assessment agent takes the computed ratios and asks the local LLM to produce a credit risk rating. Before building it, we need a small helper to extract the rating from the LLM's free-text response:
When debugging a bad outcome, start from the wrong answer, not the code: open the specific trace in Weave, then walk backwards through spans until you find the first place the data or assumptions went wrong.
💡
# Risk Assessment Agent (local LLM)
@weave.op(name="risk_assessment")
def assess_credit_risk(ticker: str, ratios: dict) -> dict:
prompt = f"""
You are a financial analyst assessing credit risk for {ticker}.

Financial Metrics:
- Profit Margin: {ratios['profit_margin']:.2%}
- Return on Assets: {ratios['roa']:.2%}
- Debt-to-Equity Ratio: {ratios['debt_to_equity']:.2f}
- Current Ratio: {ratios['current_ratio']:.2f}
- Altman Z-Score: {ratios['z_score']:.2f}

Provide:
1. Credit risk rating (Low/Medium/High)
2. Key risk factors
3. Recommendations
"""

output = llm.create_chat_completion(
messages=[
{"role": "system", "content": "You are an expert financial analyst."},
{"role": "user", "content": prompt},
],
max_tokens=256,
temperature=0.3,
)
assessment = output["choices"][0]["message"]["content"]
risk_rating = extract_risk_rating(assessment)
return {
"assessment": assessment,
"risk_rating": risk_rating,
}
What to look for in Weave: This span is the most important one to inspect when debugging. Click into risk_assessment, and you'll see the exact prompt that was sent to the LLM (with the formatted ratios baked in), the model's full response text, and the duration of the LLM call. If the risk rating ever seems wrong, start here. You can check whether the prompt was well-formed, whether the ratios were correct, and whether the LLM's response actually contained the rating the parser extracted. You'll also see extract_risk_rating as a child span.



Agent 4: Executive reporting

The reporting agent takes everything computed so far and asks the LLM to produce a concise executive summary:
@weave.op()
def extract_risk_rating(text: str) -> str:
lower = text.lower()
if "low risk" in lower:
return "Low"
if "high risk" in lower:
return "High"
return "Medium"
Observability Output :

Using the calculated values and the prompt template, we generate a report output for better understanding -
#Reporting Agent
@weave.op(name="generate_report")
def generate_executive_summary(ticker: str, ratios: dict, risk: dict) -> str:
z = ratios["z_score"]
z_label = "Healthy" if z > 2.99 else "Distressed or At Risk"

prompt = f"""
Generate a concise executive summary for {ticker}.

Z-Score: {z:.2f} ({z_label})
Profit Margin: {ratios['profit_margin']:.2%}
Debt-to-Equity: {ratios['debt_to_equity']:.2f}
Overall Risk Rating: {risk['risk_rating']}

Risk Analysis: {risk['assessment']}

Provide a 3–4 sentence summary suitable for an executive.
"""

output = llm.create_chat_completion(
messages=[{"role": "user", "content": prompt}],
max_tokens=256,
temperature=0.5,
)
summary = output["choices"][0]["message"]["content"]
return summary
What to look for in Weave: Compare the latency of this span against the risk assessment span. Both make LLM calls, but the reporting prompt includes the full risk analysis text from the previous step, which means more input tokens. If you're optimizing for speed later, this comparison tells you where the time is going.



The orchestrator: Tying it all together

The orchestrator calls each agent in sequence. Because it's also decorated with @weave.op(), it becomes the root span, and every agent call nests inside it automatically:
#Orchestrator
@weave.op(name="financial_analysis_agent")
def analyze_company(ticker: str, fiscal_year: int) -> dict:
start = time.time()

financials = fetch_financial_data(ticker, fiscal_year)
ratios = calculate_financial_ratios(financials)
risk_assessment = assess_credit_risk(ticker, ratios)
summary = generate_executive_summary(ticker, ratios, risk_assessment)

total_latency = time.time() - start

# expose latency via return value so it's visible in the trace
return {
"ticker": ticker,
"ratios": ratios,
"risk": risk_assessment,
"summary": summary,
"total_latency": total_latency,
}
Observability Output :



Running the agentic pipeline

Run the full agent pipeline:
res = analyze_company("AAPL", 2023)
print("Ticker:", res["ticker"])
print("\nRatios:", res["ratios"])
print("\nRisk rating:", res["risk"]["risk_rating"])
print("\nSummary:\n", res["summary"])
print("\nTotal latency:", res["total_latency"], "seconds")
Output :

Summary that is generated on the basis of the calculated results states that -
The credit risk rating for AAPL is assigned a Z-Score of 1.39 and a Profit Margin of 20%. The debt-to-equity ratio is 1.50, indicating a low credit risk rating. The current ratio is 1.00, indicating a healthy financial position. The Altman Z-Score is low, indicating a low likelihood of default.

Exploring the Trace in Weave

Click into the financial_analysis_agent trace. You'll see the complete hierarchy:
  • Inputs: the exact arguments passed to the function
  • Outputs: the return value, fully serialized
  • Duration: how long the function took, including any child calls
  • Metadata: any custom attributes you attached via weave.attributes()

This is the observability payoff. If the risk rating is ever wrong, you don't have to guess. You open the trace, click into risk_assessment, read the exact prompt and LLM response, and trace backward. Was the Z-Score calculation correct? Click feature_extraction. Was the input data right? Click data_ingestion. Every step is recorded.

Next steps

This tutorial used mock data and a small local model to keep things simple. From here, you can extend the pipeline in several directions:
  • Swap in real data: connect the ingestion agent to the SEC EDGAR API or a market data provider like Yahoo Finance.
  • Upgrade the model: replace TinyLlama with a larger local model (Mistral, Llama 4) or connect to an API (OpenAI, Anthropic) for higher-quality assessments.
  • Add evaluations: use Weave's built-in Scorers, and Evaluations to build a regression suite that checks risk ratings against known-good outputs on every code change.
  • Add PII redaction: if you're working with real client data, wrap your agent inputs with a sanitizer before they hit the trace logs. The companion article covers this with a working llm-guard example.
  • Integrate with OpenTelemetry: if you already have OTEL-instrumented services, you can route those traces into the same Weave project for a unified view. See the companion article for the configuration.
The core pattern stays the same no matter how complex the pipeline gets: decorate each agent function with @weave.op(), and Weave handles the rest.