python
import json
import os
from openai import OpenAI
from pydantic import BaseModel, Field
client = OpenAI(
api_key=os.environ["TOPAI_API_KEY"],
base_url="https://api.topai.id/v1",
)
RATE_CARD_ITEMS = [
{"item": "Discovery Workshop, Solution Architecture & UI/UX Blueprint", "unit": "Package", "qty": 1, "unit_price_usd": 2400},
{"item": "Core API Integration & Automated Workflow Engineering", "unit": "Man-Days", "qty": 14, "unit_price_usd": 650},
{"item": "End-to-End UAT, Technical Runbooks & Team Onboarding", "unit": "Package", "qty": 1, "unit_price_usd": 1800},
]
class MilestoneClause(BaseModel):
phase_name: str
deliverables: list[str]
acceptance_criteria: str = Field(description="Objective verification gate required to trigger milestone sign-off.")
class CommercialProposalPack(BaseModel):
executive_summary: str = Field(description="Concise executive framing linking client pain points to ROI outcomes.")
in_scope_items: list[str]
out_of_scope_exclusions: list[str] = Field(description="Explicit list of excluded work requiring a separate Change Request.")
client_dependencies: list[str]
milestones: list[MilestoneClause]
risk_flags_for_internal_review: list[str]
def compute_commercial_quotation(items: list[dict], discount_pct: float = 5.0, tax_rate: float = 0.11) -> dict:
# Deterministic arithmetic prevents rounding bugs and pricing hallucinations completely
line_items = []
subtotal = 0
for row in items:
line_total = round(row["qty"] * row["unit_price_usd"], 2)
subtotal += line_total
line_items.append({**row, "line_total_usd": line_total})
discount_amount = round(subtotal * (discount_pct / 100.0), 2)
taxable_base = round(subtotal - discount_amount, 2)
tax_amount = round(taxable_base * tax_rate, 2)
grand_total = round(taxable_base + tax_amount, 2)
tranche_1 = round(grand_total * 0.30, 2)
tranche_2 = round(grand_total * 0.40, 2)
tranche_3 = round(grand_total - tranche_1 - tranche_2, 2)
payment_schedule = [
{"term": "Milestone 1 (30% - Project Kickoff Activation)", "amount_usd": tranche_1},
{"term": "Milestone 2 (40% - Staging UAT Sign-Off)", "amount_usd": tranche_2},
{"term": "Milestone 3 (30% - Production Go-Live & Final Acceptance)", "amount_usd": tranche_3},
]
return {
"currency": "USD",
"validity_days": 14,
"line_items": line_items,
"subtotal_usd": round(subtotal, 2),
"discount_pct": discount_pct,
"discount_amount_usd": discount_amount,
"taxable_base_usd": taxable_base,
"tax_amount_usd": tax_amount,
"grand_total_usd": grand_total,
"payment_schedule": payment_schedule,
}
def build_proposal_narrative(client_brief: str, locked_quotation: dict) -> CommercialProposalPack:
prompt = (
f"Raw Discovery Brief:\n{client_brief}\n\n"
f"Locked Commercial Quotation (NEVER MODIFY NUMBERS):\n"
f"{json.dumps(locked_quotation, indent=2)}\n\n"
"PROPOSAL DRAFTING INSTRUCTIONS:\n"
"1. Write a crisp executive summary tied directly to measurable workflow ROI.\n"
"2. Define unambiguous In-Scope items and strict Out-of-Scope exclusions.\n"
"3. Bind each billing milestone cleanly to objective acceptance gates."
)
response = client.beta.chat.completions.parse(
model="claude-sonnet-5-5",
temperature=0.2,
messages=[
{
"role": "system",
"content": "You are a Solutions Architect & Commercial Lead drafting unambiguous B2B project proposals.",
},
{"role": "user", "content": prompt},
],
response_format=CommercialProposalPack,
)
return response.choices[0].message.parsed
if __name__ == "__main__":
discovery_notes = (
"Client: Meridian Freight Ops. Bottleneck: Ops coordinators manually reconcile 400 waybills daily "
"across disconnected spreadsheets, delaying invoicing by four business days. Target: ERP-to-tracking "
"dashboard automation within six weeks. Note: Client API docs remain incomplete and stakeholder casually "
"asked whether five years of legacy spreadsheet history can be migrated too."
)
quotation = compute_commercial_quotation(RATE_CARD_ITEMS, discount_pct=5.0)
proposal = build_proposal_narrative(discovery_notes, quotation)
print("=== LOCKED QUOTATION ===")
print(json.dumps(quotation, indent=2))
print("\n=== STRUCTURED PROPOSAL PACK ===")
print(json.dumps(proposal.model_dump(), indent=2))
Notice two subtle safeguards built into that code: calculating the final payment tranche by subtracting milestones one and two from grand_total ensures accounting reconciliation never misses a single cent, while risk_flags_for_internal_review surfaces the missing API documentation and offhand five-year migration request internally before a fixed-price commitment leaves your inbox.
Commercial Privacy Governance and Pre-Send Audit Checklist
Speed never excuses leaking sensitive internal pricing mechanics or confidential client credentials. Before dispatching raw discovery summaries over TOP AI, strip personal customer phone numbers, NDA-covered proprietary source schemas, internal staff salary bands, and raw gross-margin floor percentages from the prompt payload—supplying only client-facing published unit rates and sanitized architecture requirements.
Before exporting the merged JSON into your branded PDF or electronic signature tool, complete a three-minute human verification pass: verify currency codes and tax treatment consistency across prose and quotation tables, confirm revision caps and UAT turnaround deadlines appear as concrete integers, and check that the quotation validity date stands clearly on the signature block. Uniting deterministic Python quoting, disciplined risk auditing via claude-sonnet-5-5, and structured narrative synthesis on TOP AI transforms proposal assembly from an error-prone multi-day chore into a repeatable twenty-minute commercial engine.