Skip to main content

The Answer Architect: How My AI Crafts the Final Legal Response 🏗️

Or: How my legal AI turns raw data and tool results into a polished masterpiece, every single time!

Updated 4 min readMarkdown
Part of seriesSmart Legal QA — Building an AI Legal Assistant with RAG & LangChain
The Answer Architect: How My AI Crafts the Final Legal Response 🏗️

Chapter 1: The Grand Construction Project Begins 🚧

After all the retrieval, reranking, confidence calculations, and backup tool magic, my AI stands before its greatest challenge: building the perfect legal response. This isn't just about generating text—it's about orchestrating a complete, well-sourced, and transparent answer.

Chapter 2: Preparing the Foundation - Context Engineering 📐

Before any construction can begin, my AI needs to lay a solid foundation. Enter the format_context function, the unsung hero of response quality:

def format_context(retrieved_docs, tool_results):
    """Transform messy documents into organized, numbered context"""
    context_parts = []

    # Add retrieved documents with metadata
    if retrieved_docs:
        context_parts.append("## Retrieved Legal Documents:")
        for i, doc in enumerate(retrieved_docs, 1):
            title = doc.metadata.get('title', 'Unknown Document')
            page = doc.metadata.get('page', 'Unknown Page')
            source = doc.metadata.get('source', 'Unknown Source')

            context_parts.append(f"\n### Document {i}: {title}")
            context_parts.append(f"**Source:** {source} (Page {page})")
            context_parts.append(f"**Content:** {doc.page_content}")

    return "\n".join(context_parts)

This function is like a master organizer—it takes the messy pile of retrieved documents and transforms them into a neat, numbered catalog. Each document gets its own introduction with source, page, and document type, making it easy for the LLM to reference specific information.

Chapter 3: The LLM Generation Process 🏗️

With the foundation ready, my system carefully crafts the perfect prompt with all the dynamic pieces and sends it to the LLM. The LLM becomes the master craftsman, taking the organized context, following detailed instructions, and building a response that's both accurate and beautifully formatted.

Chapter 4: The Citation Workshop - Building Credibility 📚

No legal response is complete without proper citations. Enter the extract_citations function, the system's meticulous librarian:

def extract_citations(response_text, retrieved_docs):
    """Extract and format proper legal citations"""
    citations = []
    seen = set()  # Avoid duplicates

    for i, doc in enumerate(retrieved_docs, 1):
        doc_reference = f"Document {i}"
        if doc_reference in response_text:
            source_key = f"{doc.metadata.get('source', 'Unknown')}-{doc.metadata.get('page', 'Unknown')}"

            if source_key not in seen:
                citation = {
                    "document_number": i,
                    "title": doc.metadata.get('title', 'Unknown Document'),
                    "source": doc.metadata.get('source', 'Unknown Source'),
                    "page": doc.metadata.get('page', 'Unknown Page'),
                    "act": doc.metadata.get('act', 'Unknown Act'),
                    "section": doc.metadata.get('section', 'Unknown Section')
                }
                citations.append(citation)
                seen.add(source_key)

    return citations

Chapter 5: The Final Assembly Line 🏭

Now comes the grand finale—assembling everything into the final response structure:

class ChatResponse(BaseModel):
    response: str                   # The main AI answer
    citations: List[Dict]           # Extracted citations
    confidence_score: float         # How confident we are
    tools_used: Optional[List[str]] # Which backup tools helped
    query_processed: str            # The cleaned query
    reading_level: str              # Response complexity
    response_time: float            # How long it took

No black boxes here! Everything is open, traceable, and auditable.

Chapter 6: The Quality Assurance Department 📊

Before shipping the response, my system does some final quality checks and housekeeping. The system records performance metrics, tracks detailed metadata about how the response was generated, and ensures everything is properly cached for future requests. (More on this in the upcoming articles)

Chapter 7: The Grand Reveal 🎭

Finally, my AI delivers its masterpiece - a carefully crafted legal document that includes:

  • 🎨 A properly formatted HTML answer

  • 🎯 Transparent confidence scoring

  • 📖 Full citation lists

  • 📊 Performance metrics

  • 🔧 Tool usage reports

Every response is a work of art, grounded in data, and built for transparency.

The Architect's Philosophy 🏛️

What makes this answer architecture special isn't just the code—it's the philosophy behind it:

  • 🔍 Transparency First: Every piece of information used is documented and shared

  • ⚡ Performance Matters: Context optimization and caching keep things fast

  • ✨ Quality Over Quantity: Source deduplication ensures only the best references

  • 👥 User Experience: HTML formatting and snippets make responses readable

  • 📈 Continuous Improvement: Detailed metrics help optimize the system

My AI doesn't just answer questions—it builds complete, trustworthy, and transparent legal responses that users can rely on.


And there we have it! The complete journey from query to response is now complete. Our legal AI has successfully navigated through hybrid retrieval, intelligent reranking, confidence-based tool selection, parallel execution, and final answer architecture.

Next up in our series: We'll dive deeper into the architectural decisions that make this system robust—from token calculation and cost optimization, to evaluation metrics and performance monitoring. The foundation is built; now let's explore what makes it enterprise-ready! 🏗️

No comments yet. Be the first to comment.

Smart Legal QA — Building an AI Legal Assistant with RAG & LangChain

Part 8 of 9

Documenting how I designed and built an AI assistant that can answer complex legal questions from uploaded PDFs. Learn about RAG pipelines, LangChain, embeddings, evaluation datasets, and architectural choices.

Up nextThe Penny-Pinching Detective: How My AI Tracks Every Token and Cent 🕵️‍♂️💰The intricate tale of how my legal AI became a forensic accountant, dissecting every conversation to track costs with surgical precision