orghunter logo
Home
Charity API Key

Building a Charity Intelligence RAG System: Integrating OrgHunter API with Flowise

Learn to build a charity intelligence RAG chatbot using Flowise and OrgHunter API. Step-by-step tutorial with code, no backend required. Deploy in 1-2 hours.
Title Image

Introduction

Imagine building an AI assistant that can intelligently answer questions about charities, recommend nonprofits based on specific criteria, and provide detailed financial analysis—all without writing complex backend code. By integrating OrgHunter's Charity API with Flowise, you can create a powerful Retrieval-Augmented Generation (RAG) system that combines the conversational capabilities of Large Language Models with real-time charity data.

In this comprehensive tutorial, you'll learn how to:

  • Set up Flowise for charity data integration
  • Create custom API tools to query OrgHunter's database
  • Build a RAG pipeline that retrieves and processes charity information
  • Implement context-aware conversations about nonprofits
  • Deploy a production-ready charity intelligence chatbot

What You'll Build: A conversational AI agent that can search 2.5+ million charities, analyze financial data, recommend organizations based on user criteria, and answer complex questions about the nonprofit sector—all through natural language interaction.

Difficulty Level: Intermediate (basic understanding of APIs and AI concepts helpful)

Time Required: 1-2 hours

Why Flowise + OrgHunter?

The Power of Visual AI Development

Flowise is an open-source, low-code platform that lets you build sophisticated AI applications using a drag-and-drop interface. It's built on top of LangChain and LlamaIndex, which means you get enterprise-grade capabilities without the complexity.

Key Benefits:

  • Visual Development: See your AI pipeline as you build it
  • Rapid Prototyping: Go from idea to working prototype in minutes
  • Production-Ready: Deploy the same flows you build in development
  • Modular Architecture: Easy to modify, test, and extend
  • Built-in Memory: Conversational context management out of the box

The OrgHunter Advantage

OrgHunter provides the most comprehensive charity database available:

  • 2.5M+ U.S. charities with daily updates
  • Detailed financial data from Form 990 filings
  • Geographic information for location-based searches
  • Real-time 501(c)(3) verification
  • RESTful API with comprehensive documentation

Together, they enable you to build charity intelligence systems that were previously only possible for large organizations with dedicated development teams.

Prerequisites

Required Accounts & Keys

  1. OrgHunter API Access
    • Sign up at: https://orghunter.3scale.net/
    • Get your API key from the dashboard
    • Note: Free tier available via affiliate program
  2. OpenAI API Key (or alternative LLM provider)
    • Visit: https://platform.openai.com/api-keys
    • Create a new API key
    • Alternative: Use Azure OpenAI, Anthropic Claude, or other supported LLMs

Software Installation

Option 1: Local Installation (Recommended for Development)

# Install Node.js (v18 or higher)
# Download from: https://nodejs.org/

# Install Flowise globally via npm
npm install -g flowise

# Start Flowise
npx flowise start

# Access at http://localhost:3000

Option 2: Docker Installation

# Pull and run Flowise Docker container
docker run -d --name flowise -p 3000:3000 flowiseai/flowise

# Access at http://localhost:3000

Option 3: Flowise Cloud

  • Visit: https://flowiseai.com/
  • Sign up for hosted version (no installation needed)

Technical Knowledge Required

  • Basic understanding of REST APIs
  • Familiarity with JSON data structures
  • Basic knowledge of AI/LLM concepts (helpful but not required)
  • No coding required, but JavaScript knowledge helpful for custom functions

Understanding the Architecture

Before we dive into building, let's understand how our charity intelligence RAG system will work:

High-Level Flow

User Question

Query Classification (Is it charity-related?)

Query Optimization (Convert to OrgHunter API parameters)

API Retrieval (Fetch charity data from OrgHunter)

Data Processing (Format and enrich response)

LLM Generation (Create natural language response)

Response with Citations

Components We'll Use

  1. Start Node: Entry point for user queries
  2. Condition Agent: Routes queries (charity-related vs. general)
  3. Custom Tool Node: Interfaces with OrgHunter API
  4. LLM Nodes: Process and generate responses
  5. Memory: Maintains conversation context
  6. Output Node: Returns formatted responses

Data Flow

User: "Find environmental charities in Seattle"

Classification: [Charity Query Detected]

Parameter Extraction:
- category: "Environment" → NTEE Code "C"
- location: "Seattle" → city="Seattle", state="WA"

OrgHunter API Call:
GET /search?category=C&city=Seattle&state=WA&eligible=1

Response Processing:
- Parse JSON response
- Extract relevant fields
- Format for LLM context

LLM Generation:
"I found 127 environmental charities in Seattle. Here are the top recommendations..."

Part 1: Setting Up Your Flowise Environment

Step 1: Initial Configuration

  1. Open Flowise (http://localhost:3000)
  2. Create a New Chatflow
    • Click "Add New" button
    • Name it: "OrgHunter Charity Intelligence"
    • Description: "RAG system for charity discovery and analysis"
  3. Configure Environment Variables
    • Go to Settings (gear icon)
    • Add Environment Variables:

ORGHUNTER_API_KEY=your_api_key_hereOPENAI_API_KEY=your_openai_key_here

Step 2: Understanding the Canvas

The Flowise canvas is where you'll visually build your AI pipeline:

  • Left Panel: Component library (drag nodes from here)
  • Center Canvas: Your workflow (connect nodes here)
  • Right Panel: Configuration for selected nodes
  • Top Bar: Save, test, deploy, and embed options

Key Components Categories:

  • Chat Models: LLM providers (OpenAI, Anthropic, etc.)
  • Agents: Orchestration and routing logic
  • Chains: Pre-built conversation patterns
  • Tools: External integrations and custom functions
  • Vector Stores: For document embeddings (we won't use initially)
  • Memory: Conversation history management
  • Document Loaders: For RAG with documents

Part 2: Creating the OrgHunter Custom Tool

Since OrgHunter isn't a built-in integration, we'll create a custom tool. This is where the magic happens!

Step 1: Add Custom Tool Node

  1. Drag "Custom Tool" from the Tools category onto the canvas
  2. Configure the Tool (in right panel):
    • Tool Name: search_charities
    • Tool Description:

Search for charities in the OrgHunter database. Use this tool when users ask about finding, searching, or discovering charities. Can filter by name, category, location (city, state, zip), and eligibility status. Returns charity details including name, EIN, address, and description.

  1. Define Input Schema (JSON):

{
"type": "object",
"properties": {
"charityName": {
"type": "string",
"description": "Charity name to search for (partial match supported)"
},
"category": {
"type": "string",
"description": "NTEE category code (A-Z). Common: A=Arts, B=Education, C=Environment, E=Health, K=Food, P=Human Services"
},
"city": {
"type": "string",
"description": "City name"
},
"state": {
"type": "string",
"description": "Two-letter state code (e.g., CA, NY, TX)"
},
"zipCode": {
"type": "string",
"description": "5-digit zip code"
},
"eligible": {
"type": "number",
"description": "Filter for eligible organizations (1=eligible only, 0=all)"
}
}
}

  1. JavaScript Function (the actual API call):

const axios = require('axios');

async function searchCharities(charityName, category, city, state, zipCode, eligible = 1) {
try {
// Get API key from environment
const apiKey = process.env.ORGHUNTER_API_KEY;

if (!apiKey) {
throw new Error('ORGHUNTER_API_KEY not configured');
}

// Build query parameters
const params = {
eligible: eligible,
rows: 10 // Limit results
};

if (charityName) params.charityName = charityName;
if (category) params.category = category;
if (city) params.city = city;
if (state) params.state = state;
if (zipCode) params.zipCode = zipCode;

// Make API request
const response = await axios.get('https://orghunter.3scale.net/v1/charitysearch', {
params: params,
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});

// Process response
const charities = response.data.data || [];

if (charities.length === 0) {
return JSON.stringify({
message: 'No charities found matching your criteria.',
count: 0,
results: []
});
}

// Format results for LLM
const formattedResults = charities.map(charity => ({
name: charity.charityName,
ein: charity.ein,
city: charity.city,
state: charity.state,
zipCode: charity.zipCode,
category: charity.nteeCode,
description: charity.mission || 'No description available',
website: charity.websiteURL || 'Not available'
}));

return JSON.stringify({
message: `Found ${charities.length} charities`,
count: charities.length,
results: formattedResults
}, null, 2);

} catch (error) {
console.error('OrgHunter API Error:', error.message);
return JSON.stringify({
error: 'Failed to search charities',
message: error.message
});
}
}

// Execute the search
return await searchCharities($charityName, $category, $city, $state, $zipCode, $eligible);

Step 2: Create Financial Data Tool

Now let's add a second tool for detailed financial information:

  1. Add another Custom Tool node
  2. Configure:
    • Tool Name: get_charity_financials
    • Tool Description:

Get detailed financial information for a specific charity including revenue, expenses, assets, liabilities, and Form 990 data. Requires the charity's EIN (Employer Identification Number).Use this when users ask about financial health, overhead costs, or need detailed charity analysis.

  1. Input Schema:

{
"type": "object",
"properties": {
"ein": {
"type": "string",
"description": "The charity's EIN (Employer Identification Number) in format XX-XXXXXXX"
}
},
"required": ["ein"]
}

  1. JavaScript Function:

const axios = require('axios');

async function getCharityFinancials(ein) {
try {
const apiKey = process.env.ORGHUNTER_API_KEY;

if (!apiKey) {
throw new Error('ORGHUNTER_API_KEY not configured');
}

// Remove any dashes from EIN
const cleanEin = ein.replace(/-/g, '');

const response = await axios.get(`https://orghunter.3scale.net/v1/charityfinancial/${cleanEin}`, {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});

const data = response.data.data || response.data;

if (!data) {
return JSON.stringify({
error: 'No financial data found',
message: 'Financial information not available for this charity'
});
}

// Calculate efficiency ratios
const totalExpenses = parseFloat(data.totalExpenses || 0);
const programExpenses = parseFloat(data.programExpenses || 0);
const adminExpenses = parseFloat(data.adminExpenses || 0);

let programRatio = 0;
let overheadRatio = 0;

if (totalExpenses > 0) {
programRatio = ((programExpenses / totalExpenses) * 100).toFixed(2);
overheadRatio = ((adminExpenses / totalExpenses) * 100).toFixed(2);
}

// Format financial data
const financialSummary = {
charity_name: data.charityName,
ein: data.ein,
revenue: {
total: data.totalRevenue,
contributions: data.contributions,
program_service_revenue: data.programServiceRevenue,
investment_income: data.investmentIncome
},
expenses: {
total: data.totalExpenses,
program_expenses: data.programExpenses,
admin_expenses: data.adminExpenses,
fundraising_expenses: data.fundraisingExpenses
},
assets: {
total_assets: data.totalAssets,
total_liabilities: data.totalLiabilities,
net_assets: data.netAssets
},
efficiency_metrics: {
program_expense_ratio: `${programRatio}%`,
overhead_ratio: `${overheadRatio}%`,
rating: programRatio > 75 ? 'Excellent' : programRatio > 65 ? 'Good' : 'Fair'
},
tax_year: data.taxYear,
form_990_filing_date: data.filingDate
};

return JSON.stringify(financialSummary, null, 2);

} catch (error) {
console.error('Financial API Error:', error.message);
return JSON.stringify({
error: 'Failed to retrieve financial data',
message: error.message
});
}
}

return await getCharityFinancials($ein);

Step 3: Test Your Tools

Before integrating them into the full flow:

  1. Click the "Test" button on each tool
  2. Provide sample inputs:
    • For search: {"city": "Seattle", "category": "C"}
    • For financials: {"ein": "94-1156200"} (example EIN)
  3. Verify you get JSON responses with charity data

Part 3: Building the RAG Flow

Now we'll assemble everything into a complete conversational system.

Step 1: Add the Foundation Nodes

  1. Start Node
    • Drag "Start" node onto canvas
    • Configure Input Type: "Chat Input"
    • Enable Session Memory: Yes
  2. Chat OpenAI Node (Main LLM)
    • Drag "ChatOpenAI" from Chat Models
    • Model: gpt-4 or gpt-3.5-turbo
    • Temperature: 0.7 (balance between creativity and accuracy)
    • Connect API Key from environment variable
  3. Buffer Memory
    • Drag "Buffer Memory" node
    • Memory Key: chat_history
    • Session ID: Enable (maintains separate conversations per user)

Step 2: Create the Agent

  1. Add OpenAI Function Agent
    • Drag "OpenAI Function Agent" node
    • This will orchestrate tool usage
  2. Connect Components:

Start Node → OpenAI Function Agent
ChatOpenAI → OpenAI Function Agent (as LLM)
Buffer Memory → OpenAI Function Agent (as Memory)
search_charities Tool → OpenAI Function Agent (as Tool)
get_charity_financials Tool → OpenAI Function Agent (as Tool)

  1. Configure Agent System Prompt:

You are a helpful charity intelligence assistant powered by OrgHunter's database of 2.5+ million charities.

Your role:
- Help users discover charities that match their interests
- Provide detailed financial analysis and transparency
- Recommend organizations based on specific criteria
- Answer questions about the nonprofit sector
- Be honest about data limitations

When searching charities:
- Always use the search_charities tool for discovery queries
- Use get_charity_financials for detailed financial analysis
- Provide specific, actionable recommendations
- Include relevant details like location and mission
- Mention when financial data indicates strong vs. weak performance

NTEE Category Codes Reference:
A = Arts, Culture & Humanities
B = Education
C = Environment
D = Animal-Related
E = Health
F = Mental Health & Crisis Intervention
K = Food, Agriculture & Nutrition
L = Housing & Shelter
P = Human Services
Q = International Affairs
R = Civil Rights & Advocacy
S = Community Improvement
T = Philanthropy & Grantmaking
U = Science & Technology

When you cannot find relevant information, be honest and suggest alternatives.
Always cite the charity name and EIN when providing recommendations.

Step 3: Add Output Formatting

While the agent handles most formatting, let's add polish:

  1. Add "LLM Chain" node for final formatting (optional but recommended)
  2. Configure Prompt Template:

Format the following charity information in a clear, user-friendly way:

{agent_response}

Guidelines:
- Use clear headings and bullet points
- Highlight key financial metrics
- Include actionable next steps
- Add relevant context about the charity sector
- Keep tone conversational and helpful

Part 4: Advanced Configuration

Adding Query Classification

To make your system smarter, add a routing mechanism:

  1. Add Condition Agent after Start node
  2. Configure Instructions:

Analyze the user's question and determine if it's:
1. A charity/nonprofit-related query (searching, analyzing, recommending charities)
2. A general question unrelated to charities

If charity-related, output "CHARITY_QUERY"
If general, output "GENERAL_QUERY"

Examples:
- "Find food banks in Chicago" → CHARITY_QUERY
- "Tell me about the Red Cross financials" → CHARITY_QUERY
- "What's the weather today?" → GENERAL_QUERY
- "How do I cook pasta?" → GENERAL_QUERY

  1. Create Two Branches:
    • Output 0 (CHARITY_QUERY) → Goes to main agent with tools
    • Output 1 (GENERAL_QUERY) → Goes to simple LLM (polite redirect)

Adding Geolocation Support

For "near me" queries:

  1. Add Custom Tool: get_nearby_charities
  2. JavaScript Function (requires user's location):

const axios = require('axios');

async function getNearbyCharities(latitude, longitude, radius = 10, category = null) {
try {
const apiKey = process.env.ORGHUNTER_API_KEY;

// First, get charities with geolocation data
const params = {
eligible: 1,
rows: 50
};

if (category) params.category = category;

const response = await axios.get('https://orghunter.3scale.net/v1/charitygeo', {
params: params,
headers: {
'Authorization': `Bearer ${apiKey}`
}
});

const charities = response.data.data || [];

// Filter by distance using Haversine formula
const nearbyCharities = charities
.filter(c => c.latitude && c.longitude)
.map(c => {
const distance = calculateDistance(
latitude, longitude,
c.latitude, c.longitude
);
return { ...c, distance };
})
.filter(c => c.distance <= radius)
.sort((a, b) => a.distance - b.distance)
.slice(0, 10);

return JSON.stringify({
count: nearbyCharities.length,
results: nearbyCharities.map(c => ({
name: c.charityName,
ein: c.ein,
distance_miles: c.distance.toFixed(2),
address: `${c.city}, ${c.state}`,
category: c.nteeCode
}))
}, null, 2);

} catch (error) {
return JSON.stringify({ error: error.message });
}
}

function calculateDistance(lat1, lon1, lat2, lon2) {
const R = 3959; // Earth radius in miles
const dLat = (lat2 - lat1) * Math.PI / 180;
const dLon = (lon2 - lon1) * Math.PI / 180;
const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
Math.sin(dLon/2) * Math.sin(dLon/2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c;
}

return await getNearbyCharities($latitude, $longitude, $radius, $category);

Adding NTEE Category Helper

To help with category code translation:

  1. Add Custom Function node
  2. JavaScript:

function getCategoryCode(categoryName) {
const categories = {
'arts': 'A', 'culture': 'A', 'education': 'B', 'school': 'B',
'environment': 'C', 'environmental': 'C', 'climate': 'C',
'animal': 'D', 'animals': 'D', 'wildlife': 'D',
'health': 'E', 'medical': 'E', 'healthcare': 'E',
'mental health': 'F', 'crisis': 'F',
'food': 'K', 'hunger': 'K', 'nutrition': 'K',
'housing': 'L', 'shelter': 'L', 'homeless': 'L',
'human services': 'P', 'social services': 'P',
'youth': 'O', 'children': 'O', 'kids': 'O'
};

const lower = categoryName.toLowerCase();
for (const [key, code] of Object.entries(categories)) {
if (lower.includes(key)) return code;
}
return null;
}

return getCategoryCode($input);

Part 5: Testing Your RAG System

Test Scenarios

Scenario 1: Basic Search

User: "Find environmental charities in Seattle"

Expected Flow:
1. Agent calls search_charities
2. Parameters: {city: "Seattle", category: "C"}
3. Returns list of charities
4. LLM formats response with recommendations

Scenario 2: Financial Analysis

User: "Tell me about the financial health of the American Red Cross"

Expected Flow:
1. Agent searches for "American Red Cross"
2. Gets EIN from search results
3. Calls get_charity_financials with EIN
4. Analyzes program expense ratio and overhead
5. Provides assessment with specific numbers

Scenario 3: Multi-Turn Conversation

User: "Find food banks in Chicago"
Assistant: [Lists 10 food banks]
User: "Tell me more about the first one"
Assistant: [Uses memory to know which charity, gets detailed financials]
User: "How does it compare to others?"
Assistant: [Retrieves financials for multiple charities, provides comparison]

Debug Mode

Enable debug mode to see:

  • Which tools are being called
  • What parameters are passed
  • API responses
  • LLM reasoning process

To enable:

  1. Click on Agent node
  2. Toggle "Show Agent Messages" to ON
  3. Test queries and review the thought process

Common Issues and Solutions

Issue: Tool not being called

  • Solution: Improve tool description, make it more specific about when to use
  • Check that input schema matches what LLM is trying to pass

Issue: API errors

  • Solution: Verify API key is correct in environment variables
  • Check API endpoint URLs match documentation
  • Add better error handling in JavaScript functions

Issue: Generic responses

  • Solution: Improve system prompt with more specific instructions
  • Add examples of good responses
  • Lower temperature for more focused answers

Issue: Memory not working

  • Solution: Ensure Session ID is enabled in memory configuration
  • Verify memory is connected to agent
  • Check that memory key matches in all nodes

Part 6: Production Deployment

Option 1: Embed in Website

  1. Click "Embed" button in top right
  2. Get Embed Code:

<script type="module">
import Chatbot from "https://cdn.jsdelivr.net/npm/flowise-embed/dist/web.js"
Chatbot.init({
chatflowid: "your-chatflow-id",
apiHost: "http://localhost:3000",
theme: {
button: {
backgroundColor: "#3B82F6",
right: 20,
bottom: 20,
size: "medium",
iconColor: "white",
},
chatWindow: {
welcomeMessage: "Hi! I can help you discover and analyze charities. What are you looking for?",
backgroundColor: "#ffffff",
height: 700,
width: 400,
fontSize: 16,
}
}
})
</script>

  1. Add to your website in the <body> tag

Option 2: API Endpoint

Use Flowise as a backend API:

Make requests:

curl -X POST http://localhost:3000/api/v1/prediction/your-chatflow-id \
-H "Content-Type: application/json" \
-d '{"question": "Find health charities in Boston"}'

Response:

{
"text": "I found 45 health-related charities in Boston...",
"sourceDocuments": [],
"chatId": "session-123"
}

Option 3: Flowise Cloud

Deploy to Flowise's managed hosting:

  1. Export your chatflow (JSON file)
  2. Sign up at https://flowiseai.com/
  3. Import chatflow
  4. Configure environment variables in cloud dashboard
  5. Get production API endpoint

Security Considerations

API Key Protection:

  • Never expose API keys in client-side code
  • Use environment variables
  • Consider API key rotation

Rate Limiting:

  • Implement rate limiting on your endpoint
  • Cache frequent queries
  • Monitor API usage

Data Privacy:

  • Don't log user queries with PII
  • Comply with data protection regulations
  • Add privacy policy to chatbot interface

Part 7: Optimization & Best Practices

Performance Optimization

1. Implement Caching

Add a caching layer for frequent queries:

// In your custom tool
const cache = {};
const CACHE_TTL = 3600000; // 1 hour

async function cachedSearch(params) {
const cacheKey = JSON.stringify(params);
const now = Date.now();

if (cache[cacheKey] && (now - cache[cacheKey].timestamp) < CACHE_TTL) {
return cache[cacheKey].data;
}

const data = await searchCharities(params);
cache[cacheKey] = { data, timestamp: now };
return data;
}

2. Batch API Calls

When analyzing multiple charities:

async function batchGetFinancials(eins) {
const promises = eins.map(ein => getCharityFinancials(ein));
const results = await Promise.all(promises);
return results;
}

3. Optimize LLM Calls

  • Use GPT-3.5-turbo for simple queries, GPT-4 for complex analysis
  • Reduce temperature for factual responses
  • Limit max tokens to prevent overly long responses

Accuracy Improvements

Add Validation Layer:

function validateCharityData(data) {
// Check for required fields
const required = ['charityName', 'ein', 'city', 'state'];
for (const field of required) {
if (!data[field]) {
console.warn(`Missing required field: ${field}`);
}
}

// Validate EIN format
if (data.ein && !/^\d{2}-\d{7}$/.test(data.ein)) {
data.ein = data.ein.replace(/(\d{2})(\d{7})/, '$1-$2');
}

return data;
}

Add Confidence Scoring:

Update your system prompt:

When providing recommendations, include a confidence score:
- High confidence: Multiple matching criteria, recent financial data
- Medium confidence: Some matching criteria, older data
- Low confidence: Limited matching criteria or data

Example: "American Red Cross (EIN: 53-0196605) - High Confidence ✓"

User Experience Enhancements

1. Add Suggested Questions

In your welcome message:

Hi! I can help you discover charities. Try asking:
• "Find food banks in [your city]"
• "Show me highly-rated environmental charities"
• "Analyze the financials of [charity name]"
• "What are the largest health charities?"

2. Progressive Disclosure

Show basic info first, offer details:

"I found 15 animal shelters in Austin. Here are the top 3:

1. Austin Pets Alive! (EIN: XX-XXXXXXX)
Focus: No-kill shelter, program expense ratio: 89%

Would you like:
• Financial details for any of these
• More charities from the list
• Charities in a different category"

3. Add Rich Formatting

Use markdown in responses:

// In your tool response formatting
return `
## ${charity.name}
**EIN:** ${charity.ein}
**Location:** ${charity.city}, ${charity.state}

### Financial Health
- Program Expenses: ${programRatio}%
- Rating: ${rating}

[View Full 990 →](link-to-990)
`;

Part 8: Advanced Use Cases

Multi-Charity Comparison

Create a comparison tool:

Custom Tool: compare_charities

async function compareCharities(eins) {
const charities = await Promise.all(
eins.map(ein => getCharityFinancials(ein))
);

const comparison = charities.map(c => {
const data = JSON.parse(c);
return {
name: data.charity_name,
program_ratio: data.efficiency_metrics.program_expense_ratio,
total_revenue: data.revenue.total,
total_assets: data.assets.total_assets,
rating: data.efficiency_metrics.rating
};
});

// Sort by program ratio
comparison.sort((a, b) =>
parseFloat(b.program_ratio) - parseFloat(a.program_ratio)
);

return JSON.stringify({
comparison,
best_performer: comparison[0].name,
analysis: `${comparison[0].name} has the highest program expense ratio at ${comparison[0].program_ratio}`
}, null, 2);
}

Charity Recommendation Engine

Build a sophisticated recommendation system:

System Prompt Addition:

When making recommendations, consider:
1. Mission alignment with user's stated interests
2. Financial efficiency (>75% program expenses = excellent)
3. Geographic preference (local vs national vs international)
4. Size (user may prefer large established orgs or small grassroots)
5. Recent activity (prefer orgs with recent 990 filings)

Provide 3-5 recommendations with brief justification for each.

Trend Analysis

Add historical analysis capability:

async function analyzeCharityTrends(ein) {
// Get multiple years of data
const years = [2023, 2022, 2021, 2020];
const historicalData = await Promise.all(
years.map(year => getFinancialsByYear(ein, year))
);

// Calculate trends
const revenues = historicalData.map(d => d.revenue.total);
const growthRate = calculateGrowthRate(revenues);

return {
trend: growthRate > 0 ? 'growing' : 'declining',
growth_rate: `${growthRate.toFixed(2)}%`,
analysis: `Revenue ${growthRate > 0 ? 'increased' : 'decreased'} by ${Math.abs(growthRate)}% over ${years.length} years`
};
}

Part 9: Monitoring & Analytics

Add Usage Tracking

Track what users are searching for:

// In your tools
function logToolUsage(toolName, params) {
const log = {
timestamp: new Date().toISOString(),
tool: toolName,
parameters: params
};

// Send to your analytics service
// or log to database
console.log('Tool Usage:', log);
}

Performance Metrics

Monitor key metrics:

  • Average response time
  • API success/failure rate
  • Most searched categories
  • Most requested charities
  • Conversation length
  • User satisfaction (via thumbs up/down)

Error Handling & Logging

Comprehensive error handling:

async function robustAPICall(endpoint, params) {
const maxRetries = 3;
let lastError;

for (let i = 0; i < maxRetries; i++) {
try {
return await makeAPICall(endpoint, params);
} catch (error) {
lastError = error;
console.error(`Attempt ${i+1} failed:`, error.message);

if (error.response?.status === 429) {
// Rate limit - wait and retry
await new Promise(resolve => setTimeout(resolve, 2000 * (i + 1)));
} else if (error.response?.status >= 500) {
// Server error - retry
await new Promise(resolve => setTimeout(resolve, 1000));
} else {
// Client error - don't retry
throw error;
}
}
}

throw new Error(`Failed after ${maxRetries} attempts: ${lastError.message}`);
}

Part 10: Real-World Examples

Example 1: Disaster Relief Coordinator

Scenario: After a natural disaster, users need to quickly find legitimate relief organizations.

Enhanced Prompt:

You are a disaster relief coordinator assistant. When users mention disasters or crises:
1. Search for disaster relief charities with high efficiency ratings
2. Prioritize organizations with "Emergency" or "Disaster" in their NTEE subcategory
3. Highlight charities currently operating in affected areas
4. Show financial transparency to build trust
5. Provide multiple options in case preferred charities are overwhelmed

Custom Tool: get_disaster_relief_orgs

Example 2: Corporate Matching Program

Scenario: Companies want to verify employee donation requests.

Flow Additions:

  • EIN verification tool
  • 501(c)(3) status checker
  • Eligibility validator
  • Receipt generator

Benefits:

  • Instant verification (no manual review)
  • Reduced fraud risk
  • Employee self-service
  • Automatic documentation

Example 3: Donor Education Platform

Scenario: Teaching users about effective giving.

Educational Prompts:

When users ask about choosing charities, educate them on:
- Program expense ratio (what % goes to mission vs overhead)
- Different charity types (operating vs grantmaking foundations)
- How to read Form 990
- Red flags (no recent filings, excessive executive compensation)
- Why local vs national charities matter

Then help them search using these criteria.

Troubleshooting Guide

Common Errors & Solutions

Error Cause Solution "API key not found" Environment variable not set Add ORGHUNTER_API_KEY to Flowise settings "Tool not called" Unclear tool description Make description more specific "401 Unauthorized" Invalid API key Verify key at orghunter.3scale.net "429 Rate Limit" Too many requests Add rate limiting, implement caching "Cannot read property of undefined" Missing data in API response Add null checks in tool functions "Memory not working" Session ID not configured Enable Session ID in memory settings "Hallucinated data" LLM making up information Add "only use tool data" to system prompt

Debugging Steps

  1. Enable Verbose Logging
    • Turn on "Show Agent Messages"
    • Check browser console for errors
    • Review Flowise server logs
  2. Test Components Individually
    • Test each tool in isolation
    • Verify API responses with Postman/curl
    • Check LLM responses without tools
  3. Validate Data Flow
    • Confirm data moves between nodes correctly
    • Check variable naming consistency
    • Verify JSON parsing at each step

Next Steps & Extensions

Immediate Enhancements

  1. Add more tools:
    • Geographic search with radius
    • Category recommendations
    • Similar charity finder
    • Historical data comparison
  2. Improve UI:
    • Custom branding
    • Rich media (charity logos, photos)
    • Interactive charts for financial data
    • Map integration for location-based search
  3. Add integrations:
    • Google Sheets (export search results)
    • Email (send charity reports)
    • Calendar (add volunteer events)
    • Payment processing (direct donations)

Advanced Projects

Project 1: Multi-Agent System

  • Search Agent (discovery)
  • Analysis Agent (financial review)
  • Recommendation Agent (personalized suggestions)
  • Coordinator Agent (orchestrates others)

Project 2: Voice Interface

  • Integrate with speech-to-text
  • Add voice output
  • Create Alexa/Google Home skill

Project 3: Slack Bot

  • Deploy as Slack app
  • Team-based charity research
  • Automated CSR reporting

Resources & Community

Documentation

  • Flowise Docs: https://docs.flowiseai.com/
  • OrgHunter API: https://charityapi.com/docs-introduction
  • LangChain: https://python.langchain.com/docs/

Community

  • Flowise Discord: Join for support and inspiration
  • GitHub Discussions: Report bugs, request features
  • YouTube Tutorials: Video walkthroughs

Getting Help

OrgHunter Support:

  • Email: support@orghunter.com
  • API Status: Check dashboard
  • Documentation: charityapi.com

Flowise Support:

  • GitHub Issues: github.com/FlowiseAI/Flowise
  • Discord Community
  • Documentation Portal

Conclusion

You've now built a production-ready charity intelligence RAG system that combines the conversational power of LLMs with the comprehensive data of OrgHunter's charity database. This system can:

✅ Search 2.5+ million charities intelligently ✅ Analyze financial health and efficiency ✅ Provide personalized recommendations ✅ Maintain conversational context ✅ Handle complex multi-turn dialogues ✅ Scale to production workloads

Key Takeaways:

  1. Flowise makes RAG development visual and accessible
  2. Custom tools extend capabilities to any API
  3. Proper prompting is crucial for accuracy
  4. Memory management enables natural conversations
  5. Iterative testing leads to better results

What's Next?

  • Deploy your chatbot to production
  • Gather user feedback and iterate
  • Add more advanced features
  • Share your creation with the community

Remember: The best AI applications solve real problems for real people. By making charity data accessible and actionable, you're empowering better giving decisions and helping nonprofits connect with supporters.

Ready to deploy your charity intelligence system? The world of effective philanthropy awaits!

Appendix

Complete NTEE Category Reference

A: Arts, Culture & Humanities
A01: Alliance/Advocacy Organizations
A02: Management & Technical Assistance
A03: Professional Societies/Associations
A05: Research Institutes/Public Policy Analysis
...

B: Education
B01: Alliance/Advocacy Organizations
B02: Management & Technical Assistance
B03: Professional Societies/Associations
...

C: Environment
C01: Alliance/Advocacy Organizations
C20: Pollution Abatement and Control
C27: Recycling
C30: Natural Resources Conservation/Protection
C32: Water Resources, Wetlands Conservation
...

[Full list available in OrgHunter API documentation]

Sample API Responses

Search Response:

{
"data": [
{
"ein": "94-1156200",
"charityName": "Silicon Valley Community Foundation",
"city": "Mountain View",
"state": "CA",
"zipCode": "94041",
"nteeCode": "T31",
"mission": "Supporting community needs through grantmaking",
"websiteURL": "https://www.siliconvalleycf.org/"
}
]
}

Financial Response:

{
"data": {
"charityName": "Silicon Valley Community Foundation",
"ein": "941156200",
"totalRevenue": "5234567890",
"totalExpenses": "3456789012",
"programExpenses": "2987654321",
"adminExpenses": "234567891",
"totalAssets": "12345678901"
}
}

Built with ❤️ using Flowise and OrgHunter Charity API

Have questions or want to share your implementation? Reach out:

  • OrgHunter: support@orghunter.com
  • Flowise Community: discord.gg/flowise

orghunter logo
Home
API Key
© OrgHunter 2024. All rights reserved.

When you visit or interact with our sites, services or tools, we or our authorized service providers may use cookies for storing information to help provide you with a better, faster and safer experience and for marketing purposes.