Learn how to build a structured tax knowledge base using categories, topics, and content to create a searchable repository of tax information.

What You’ll Learn

This complete example demonstrates:

  • Setting up a hierarchical taxonomy for tax content
  • Batch importing tax-related content
  • Creating searchable tax guidance
  • Building a Q&A system for tax queries

Overview

We’ll create a tax knowledge base with:

  • Categories: Major tax areas (Personal, Business, International)
  • Topics: Specific tax subjects within each category
  • Content: Detailed tax information, forms, and guidance

Complete Tax Knowledge Base Setup

const API_URL = 'https://sdk.senso.ai/api/v1';
const API_KEY = 'YOUR_API_KEY';

async function buildTaxKnowledgeBase() {
  try {
    console.log('Building Tax Knowledge Base...\n');
    
    // Step 1: Create the taxonomy structure
    const taxonomy = await createTaxTaxonomy();
    console.log('✓ Taxonomy created');
    
    // Step 2: Import tax content
    await importTaxContent(taxonomy);
    console.log('✓ Content imported');
    
    // Step 3: Test the knowledge base
    await testTaxQueries();
    console.log('✓ Knowledge base tested');
    
    console.log('\nTax Knowledge Base ready for use!');
    
  } catch (error) {
    console.error('Error building knowledge base:', error);
  }
}

async function createTaxTaxonomy() {
  // Create main categories with their topics
  const response = await fetch(`${API_URL}/categories/batch-create`, {
    method: 'POST',
    headers: {
      'X-API-Key': API_KEY,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      categories: [
        {
          name: 'Personal Income Tax',
          description: 'Individual tax filing, deductions, and credits',
          topics: [
            { 
              name: 'Filing Status', 
              description: 'Single, married filing jointly, head of household' 
            },
            { 
              name: 'Deductions', 
              description: 'Standard and itemized deductions' 
            },
            { 
              name: 'Tax Credits', 
              description: 'Child tax credit, earned income credit, education credits' 
            },
            { 
              name: 'Form 1040', 
              description: 'Main individual tax return form' 
            }
          ]
        },
        {
          name: 'Business Tax',
          description: 'Corporate, partnership, and self-employment taxes',
          topics: [
            { 
              name: 'Business Structures', 
              description: 'LLC, S-Corp, C-Corp, Partnership tax implications' 
            },
            { 
              name: 'Business Deductions', 
              description: 'Operating expenses, depreciation, home office' 
            },
            { 
              name: 'Quarterly Taxes', 
              description: 'Estimated tax payments for businesses' 
            },
            { 
              name: 'Form 1099', 
              description: 'Contractor and miscellaneous income reporting' 
            }
          ]
        },
        {
          name: 'State & Local Tax',
          description: 'State income tax, sales tax, property tax',
          topics: [
            { 
              name: 'State Income Tax', 
              description: 'State-specific tax rates and rules' 
            },
            { 
              name: 'Sales Tax', 
              description: 'Sales and use tax requirements' 
            },
            { 
              name: 'Property Tax', 
              description: 'Real estate and personal property taxes' 
            }
          ]
        }
      ]
    })
  });
  
  const categories = await response.json();
  
  // Create a mapping of category and topic IDs for easy reference
  const taxonomy = {};
  for (const cat of categories) {
    taxonomy[cat.name] = {
      id: cat.category_id,
      topics: {}
    };
    // Fetch topics for this category
    const topicsResponse = await fetch(
      `${API_URL}/categories/${cat.category_id}/topics`,
      { headers: { 'X-API-Key': API_KEY } }
    );
    const topics = await topicsResponse.json();
    topics.forEach(topic => {
      taxonomy[cat.name].topics[topic.name] = topic.topic_id;
    });
  }
  
  return taxonomy;
}

async function importTaxContent(taxonomy) {
  // Import content for Personal Income Tax
  const personalTaxContent = [
    {
      title: 'Understanding Filing Status',
      text: `# Filing Status Guide

Your filing status determines your tax rates and standard deduction amount.

## Single
- Unmarried or legally separated on December 31
- Standard deduction: $13,850 (2023)

## Married Filing Jointly
- Married couples filing one return
- Standard deduction: $27,700 (2023)
- Generally results in lower taxes

## Head of Household
- Unmarried and paid > 50% of household expenses
- Have a qualifying dependent
- Standard deduction: $20,800 (2023)

## Important Considerations
- Filing status is determined on December 31
- Choose the status that gives you the lowest tax
- Some married couples benefit from filing separately`,
      category_id: taxonomy['Personal Income Tax'].id,
      topic_id: taxonomy['Personal Income Tax'].topics['Filing Status']
    },
    {
      title: 'Common Tax Deductions',
      text: `# Tax Deductions Overview

## Standard Deduction vs. Itemized
Most taxpayers take the standard deduction, but itemizing may save more if your deductions exceed:
- Single: $13,850
- Married Filing Jointly: $27,700
- Head of Household: $20,800

## Common Itemized Deductions
1. **Mortgage Interest**: Up to $750,000 in mortgage debt
2. **State and Local Taxes (SALT)**: Limited to $10,000
3. **Charitable Contributions**: Cash and non-cash donations
4. **Medical Expenses**: Amounts exceeding 7.5% of AGI

## Above-the-Line Deductions
- Student loan interest (up to $2,500)
- IRA contributions
- Health Savings Account contributions
- Self-employment tax (50%)`,
      category_id: taxonomy['Personal Income Tax'].id,
      topic_id: taxonomy['Personal Income Tax'].topics['Deductions']
    }
  ];
  
  // Import business tax content
  const businessTaxContent = [
    {
      title: 'Choosing a Business Structure',
      text: `# Business Structure Tax Implications

## Sole Proprietorship
- Report on Schedule C of Form 1040
- Subject to self-employment tax (15.3%)
- All profits taxed as personal income

## LLC (Limited Liability Company)
- Default: Taxed as sole proprietorship or partnership
- Can elect S-Corp or C-Corp taxation
- Pass-through taxation available

## S-Corporation
- Pass-through taxation
- Owners pay income tax on profits
- Can reduce self-employment tax through salary/distribution split

## C-Corporation
- Double taxation: Corporate tax + dividend tax
- Current corporate tax rate: 21%
- Better for businesses planning to go public`,
      category_id: taxonomy['Business Tax'].id,
      topic_id: taxonomy['Business Tax'].topics['Business Structures']
    }
  ];
  
  // Batch import all content
  const allContent = [...personalTaxContent, ...businessTaxContent];
  
  for (const content of allContent) {
    await fetch(`${API_URL}/content/raw`, {
      method: 'POST',
      headers: {
        'X-API-Key': API_KEY,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(content)
    });
    console.log(`  Imported: ${content.title}`);
  }
  
  // Wait for processing
  await new Promise(resolve => setTimeout(resolve, 3000));
}

async function testTaxQueries() {
  console.log('\nTesting Tax Knowledge Base:');
  
  const testQueries = [
    'What is the standard deduction for married filing jointly?',
    'How do I choose between LLC and S-Corp?',
    'What are the most common itemized deductions?',
    'What is head of household filing status?'
  ];
  
  for (const query of testQueries) {
    const response = await fetch(`${API_URL}/search`, {
      method: 'POST',
      headers: {
        'X-API-Key': API_KEY,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        query,
        max_results: 3
      })
    });
    
    const result = await response.json();
    console.log(`\nQ: ${query}`);
    console.log(`A: ${result.answer.substring(0, 150)}...`);
  }
}

// Run the setup
buildTaxKnowledgeBase();

Extending the Tax Knowledge Base

Add State-Specific Content

def add_state_content(taxonomy, state):
    headers = {'X-API-Key': API_KEY}
    
    state_content = {
        'title': f'{state} State Tax Guide',
        'text': f'State-specific tax information for {state}...',
        'category_id': taxonomy['State & Local Tax']['id'],
        'topic_id': taxonomy['State & Local Tax']['topics']['State Income Tax']
    }
    
    requests.post(
        f'{API_URL}/content/raw',
        headers=headers,
        json=state_content
    )

Import IRS Publications

def import_irs_publication(pub_number, pdf_path):
    headers = {'X-API-Key': API_KEY}
    
    with open(pdf_path, 'rb') as pdf_file:
        files = {'file': pdf_file}
        data = {
            'title': f'IRS Publication {pub_number}',
            'tags': f'irs,official,pub{pub_number}'
        }
        
        response = requests.post(
            f'{API_URL}/content/file',
            headers=headers,
            files=files,
            data=data
        )
        
    return response.json()

Create Tax Calculators

def create_tax_calculator(tax_type):
    headers = {'X-API-Key': API_KEY}
    
    prompt_response = requests.post(
        f'{API_URL}/prompts',
        headers=headers,
        json={
            'name': f'{tax_type} Tax Calculator',
            'text': 'Based on the provided {{income}} and {{deductions}}, calculate the estimated {{tax_type}} tax liability using current rates.'
        }
    )
    prompt = prompt_response.json()
    
    template_response = requests.post(
        f'{API_URL}/templates',
        headers=headers,
        json={
            'name': f'{tax_type} Tax Result',
            'text': '{"taxable_income": {{taxable_income}}, "tax_owed": {{tax_owed}}, "effective_rate": {{rate}}}',
            'output_type': 'json'
        }
    )
    template = template_response.json()
    
    return {'prompt': prompt, 'template': template}

Tax Q&A Examples

The knowledge base can answer complex tax questions:

complex_queries = [
    "Can I deduct home office expenses if I work from home 3 days a week?",
    "What's the difference between a traditional and Roth IRA for taxes?",
    "How much can I contribute to a 529 plan and get a tax deduction?",
    "Do I need to pay quarterly taxes if I have a side business?"
]

for query in complex_queries:
    response = requests.post(
        f'{API_URL}/search',
        headers={'X-API-Key': API_KEY},
        json={
            'query': query,
            'category_id': relevant_category_id
        }
    )
    answer = response.json()
    print(f"Q: {query}\nA: {answer['answer']}\n")

Best Practices for Tax Content

  1. Keep content current: Tax laws change yearly - date your content
  2. Use official sources: Reference IRS publications and forms
  3. Include disclaimers: Tax advice should note professional consultation
  4. Structure for clarity: Use headers, lists, and examples
  5. Tag by tax year: Enable filtering by relevant tax year

Next Steps