Add comprehensive documentation for GB templates and configuration
modules Add detailed README documentation for 15+ bot templates including: - Platform analytics, BI reporting, and web crawler templates - CRM, contacts, and marketing automation templates - Legal document processing and office productivity templates - LLM tools, LLM server, and API client integration templates - Reminder management and meta-template for creating new templates Add new Rust configuration modules: - BM25 config for Tantivy-based sparse
This commit is contained in:
parent
ad311944b8
commit
7a5e369402
28 changed files with 10193 additions and 0 deletions
431
docs/src/chapter-02/template-analytics.md
Normal file
431
docs/src/chapter-02/template-analytics.md
Normal file
|
|
@ -0,0 +1,431 @@
|
|||
# Platform Analytics Template (analytics.gbai)
|
||||
|
||||
A General Bots template for platform metrics, performance monitoring, and custom report generation.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
The Analytics template provides comprehensive platform analytics capabilities, allowing administrators and stakeholders to monitor usage, track performance, analyze trends, and generate custom reports through conversational AI.
|
||||
|
||||
## Features
|
||||
|
||||
- **Platform Overview** - Key metrics summary with trend analysis
|
||||
- **Message Analytics** - Conversation statistics by channel and bot
|
||||
- **User Analytics** - Active users, sessions, and engagement
|
||||
- **Performance Metrics** - Response times and throughput monitoring
|
||||
- **LLM Usage Tracking** - Token consumption and cost analysis
|
||||
- **Storage Analytics** - Disk usage and file statistics
|
||||
- **Error Analysis** - Error patterns and troubleshooting insights
|
||||
- **Custom Report Generator** - Build and schedule personalized reports
|
||||
- **AI-Powered Insights** - Automatic trend analysis and recommendations
|
||||
|
||||
---
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
analytics.gbai/
|
||||
├── analytics.gbdialog/
|
||||
│ ├── start.bas # Main menu and navigation
|
||||
│ ├── platform-overview.bas # Key metrics dashboard
|
||||
│ └── custom-report.bas # Custom report builder
|
||||
└── analytics.gbot/
|
||||
└── config.csv # Bot configuration
|
||||
```
|
||||
|
||||
## Scripts
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `start.bas` | Main entry point with analytics menu options |
|
||||
| `platform-overview.bas` | Platform-wide metrics with trends and export |
|
||||
| `custom-report.bas` | Interactive custom report generator with scheduling |
|
||||
|
||||
---
|
||||
|
||||
## Available Analytics
|
||||
|
||||
### 1. Platform Overview
|
||||
|
||||
High-level metrics summary including:
|
||||
- Total messages and trend percentage
|
||||
- Average active sessions
|
||||
- Response time performance
|
||||
- Error rates
|
||||
- LLM token consumption
|
||||
|
||||
### 2. Message Analytics
|
||||
|
||||
- Message volume by time period
|
||||
- Breakdown by channel (WhatsApp, Web, API)
|
||||
- Bot-specific conversation stats
|
||||
- Peak usage times
|
||||
|
||||
### 3. User Analytics
|
||||
|
||||
- Active users (daily, weekly, monthly)
|
||||
- Session duration analysis
|
||||
- User retention rates
|
||||
- Geographic distribution
|
||||
|
||||
### 4. Performance Metrics
|
||||
|
||||
- Average response time
|
||||
- Response time distribution
|
||||
- Throughput (messages per second)
|
||||
- Latency percentiles (p50, p95, p99)
|
||||
|
||||
### 5. LLM Usage
|
||||
|
||||
- Token consumption by model
|
||||
- Cost analysis
|
||||
- Usage patterns
|
||||
- Optimization recommendations
|
||||
|
||||
### 6. Storage Analytics
|
||||
|
||||
- Disk usage trends
|
||||
- File count and types
|
||||
- Storage by bot/package
|
||||
- Cleanup recommendations
|
||||
|
||||
### 7. Error Analysis
|
||||
|
||||
- Error frequency and patterns
|
||||
- Error categorization
|
||||
- Root cause analysis
|
||||
- Resolution suggestions
|
||||
|
||||
### 8. Custom Reports
|
||||
|
||||
- Select metrics to include
|
||||
- Choose time ranges
|
||||
- Set grouping intervals
|
||||
- Export in multiple formats
|
||||
- Schedule automatic delivery
|
||||
|
||||
---
|
||||
|
||||
## Sample Conversation
|
||||
|
||||
```
|
||||
User: Show me analytics
|
||||
|
||||
Bot: Welcome to the Analytics Center. I can help you
|
||||
understand your platform metrics and generate reports.
|
||||
|
||||
What would you like to analyze?
|
||||
1. Platform Overview - Key metrics summary
|
||||
2. Message Analytics - Conversation statistics
|
||||
3. User Analytics - Active users and sessions
|
||||
4. Performance Metrics - Response times
|
||||
5. LLM Usage - Token consumption and costs
|
||||
6. Storage Analytics - Disk usage
|
||||
7. Error Analysis - Error patterns
|
||||
8. Generate Custom Report
|
||||
|
||||
User: 1
|
||||
|
||||
Bot: Generating platform overview...
|
||||
Select time range (1h, 6h, 24h, 7d, 30d):
|
||||
|
||||
User: 24h
|
||||
|
||||
Bot: 📊 Platform Overview for Last 24 Hours
|
||||
════════════════════════════════════════
|
||||
|
||||
📨 Messages
|
||||
Total: 15,432
|
||||
Trend: ▲ +12.5% vs previous period
|
||||
|
||||
👥 Sessions
|
||||
Average Active: 234
|
||||
Peak: 412 (at 2:30 PM)
|
||||
Trend: ▲ +5.2%
|
||||
|
||||
⚡ Performance
|
||||
Avg Response Time: 145 ms
|
||||
P95: 320 ms
|
||||
P99: 580 ms
|
||||
|
||||
❌ Errors
|
||||
Total: 23
|
||||
Error Rate: 0.15%
|
||||
Most Common: Timeout (12)
|
||||
|
||||
🤖 LLM Usage
|
||||
Total Tokens: 1,245,678
|
||||
Estimated Cost: $18.45
|
||||
Avg per Message: 81 tokens
|
||||
|
||||
Would you like to:
|
||||
(D)etail, (E)xport report, (A)lerts, (B)ack
|
||||
|
||||
User: E
|
||||
|
||||
Bot: Export format (PDF, CSV, XLSX):
|
||||
|
||||
User: PDF
|
||||
|
||||
Bot: ✅ Report exported: platform_overview_20240515.pdf
|
||||
|
||||
The file is available in your Drive.
|
||||
Download link: [secure link]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Custom Report Generation
|
||||
|
||||
```
|
||||
User: I need a custom report
|
||||
|
||||
Bot: Custom Report Generator
|
||||
What would you like to name this report?
|
||||
|
||||
User: Weekly Performance Summary
|
||||
|
||||
Bot: Select the time range:
|
||||
1. Last Hour
|
||||
2. Last 24 Hours
|
||||
3. Last 7 Days
|
||||
4. Last 30 Days
|
||||
5. Custom Range
|
||||
|
||||
User: 3
|
||||
|
||||
Bot: Select metrics to include (comma-separated):
|
||||
1. Message Volume
|
||||
2. Active Sessions
|
||||
3. Response Time
|
||||
4. LLM Token Usage
|
||||
5. Error Rate
|
||||
6. Storage Usage
|
||||
7. API Calls
|
||||
8. User Activity
|
||||
9. Bot Performance
|
||||
10. All Metrics
|
||||
|
||||
User: 1,3,4,5
|
||||
|
||||
Bot: Select grouping interval:
|
||||
1. Hourly
|
||||
2. Daily
|
||||
3. Weekly
|
||||
|
||||
User: 2
|
||||
|
||||
Bot: Generating your custom report...
|
||||
|
||||
✅ Report generated successfully!
|
||||
|
||||
📋 Weekly Performance Summary
|
||||
📅 Period: May 8-15, 2025
|
||||
📊 Metrics: Messages, Response Time, LLM Usage, Errors
|
||||
📈 Grouping: Daily
|
||||
|
||||
Download: [secure link]
|
||||
|
||||
Would you like to schedule this report?
|
||||
|
||||
User: Yes, weekly
|
||||
|
||||
Bot: ✅ Report scheduled!
|
||||
|
||||
Frequency: Weekly on Monday at 8:00 AM
|
||||
Delivery: Email to your address
|
||||
|
||||
You can manage scheduled reports anytime.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Metrics Query System
|
||||
|
||||
The template uses a metrics query system:
|
||||
|
||||
```basic
|
||||
' Query metrics for a time range
|
||||
messages = QUERY METRICS "messages" FOR "24h"
|
||||
totalMessages = SUM(messages, "count")
|
||||
|
||||
' Query with grouping
|
||||
hourlyMessages = QUERY METRICS "messages" FOR "24h" BY "1h"
|
||||
|
||||
' Query with offset for comparison
|
||||
prevMessages = QUERY METRICS "messages" FOR "24h" OFFSET 1
|
||||
trend = ((totalMessages - SUM(prevMessages, "count")) / SUM(prevMessages, "count")) * 100
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Export Formats
|
||||
|
||||
Reports can be exported in multiple formats:
|
||||
|
||||
| Format | Description |
|
||||
|--------|-------------|
|
||||
| PDF | Formatted report with charts |
|
||||
| XLSX | Excel spreadsheet |
|
||||
| CSV | Raw data export |
|
||||
| JSON | Structured data format |
|
||||
|
||||
---
|
||||
|
||||
## Scheduled Reports
|
||||
|
||||
Configure automatic report delivery:
|
||||
|
||||
| Schedule | Cron Expression | Description |
|
||||
|----------|-----------------|-------------|
|
||||
| Daily | `0 8 * * *` | Every day at 8 AM |
|
||||
| Weekly | `0 8 * * 1` | Monday at 8 AM |
|
||||
| Monthly | `0 8 1 * *` | 1st of month at 8 AM |
|
||||
|
||||
```basic
|
||||
SET SCHEDULE "0 8 * * 1", "generate-scheduled-report.bas"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
Configure in `analytics.gbot/config.csv`:
|
||||
|
||||
| Parameter | Description | Example |
|
||||
|-----------|-------------|---------|
|
||||
| `Default Time Range` | Default period for queries | `7d` |
|
||||
| `Data Retention Days` | How long to keep metrics | `90` |
|
||||
| `Admin Email` | Email for scheduled reports | `admin@company.com` |
|
||||
| `Enable AI Insights` | Auto-generate insights | `true` |
|
||||
| `Export Path` | Report storage location | `/reports/` |
|
||||
|
||||
---
|
||||
|
||||
## Customization
|
||||
|
||||
### Adding Custom Metrics
|
||||
|
||||
```basic
|
||||
' Track custom events
|
||||
INSERT INTO "custom_metrics" VALUES {
|
||||
"name": "feature_usage",
|
||||
"value": 1,
|
||||
"tags": {"feature": "chat", "plan": "pro"},
|
||||
"timestamp": NOW()
|
||||
}
|
||||
|
||||
' Query custom metrics
|
||||
usage = QUERY METRICS "feature_usage" FOR "30d" WHERE tags.feature = "chat"
|
||||
```
|
||||
|
||||
### Custom Dashboard Widgets
|
||||
|
||||
```basic
|
||||
' Add to start.bas
|
||||
TALK "Custom Metrics:"
|
||||
TALK "9. Feature Usage"
|
||||
TALK "10. Revenue Analytics"
|
||||
TALK "11. Customer Health Score"
|
||||
|
||||
' Handle custom options
|
||||
CASE 9
|
||||
CALL "feature-usage.bas"
|
||||
CASE 10
|
||||
CALL "revenue-analytics.bas"
|
||||
```
|
||||
|
||||
### AI-Powered Insights
|
||||
|
||||
```basic
|
||||
' Generate AI insights from metrics
|
||||
SET CONTEXT "You are an analytics expert. Generate executive insights."
|
||||
|
||||
insights = LLM "Analyze this data and provide 3-5 key insights: " + JSON(report_data)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Integration Examples
|
||||
|
||||
### With Alerting
|
||||
|
||||
```basic
|
||||
' Set up alerts based on metrics
|
||||
errorRate = SUM(errors, "count") / SUM(messages, "count") * 100
|
||||
|
||||
IF errorRate > 5 THEN
|
||||
SEND EMAIL admin_email, "High Error Rate Alert",
|
||||
"Error rate is " + errorRate + "%, above 5% threshold."
|
||||
END IF
|
||||
```
|
||||
|
||||
### With External BI Tools
|
||||
|
||||
```basic
|
||||
' Export data for external tools
|
||||
data = QUERY METRICS "messages" FOR "30d" BY "1d"
|
||||
WRITE "analytics_export.csv", CSV(data)
|
||||
|
||||
' Or send to webhook
|
||||
POST "https://bi-tool.example.com/webhook", data
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Set appropriate time ranges** - Don't query more data than needed
|
||||
2. **Use caching** - Cache expensive queries
|
||||
3. **Schedule off-peak** - Run heavy reports during low traffic
|
||||
4. **Monitor the monitor** - Track analytics query performance
|
||||
5. **Archive old data** - Move historical data to cold storage
|
||||
6. **Validate insights** - Review AI-generated insights for accuracy
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Issue | Cause | Solution |
|
||||
|-------|-------|----------|
|
||||
| Slow queries | Large time range | Reduce range or add filters |
|
||||
| Missing data | Metrics not collected | Verify instrumentation |
|
||||
| Export fails | Large report size | Export in chunks |
|
||||
| Stale data | Cache not refreshed | Clear cache |
|
||||
| Incorrect trends | Insufficient history | Wait for more data |
|
||||
|
||||
---
|
||||
|
||||
## Use Cases
|
||||
|
||||
- **Operations Teams** - Monitor platform health and performance
|
||||
- **Product Managers** - Track feature usage and engagement
|
||||
- **Executives** - High-level KPI dashboards
|
||||
- **Support Teams** - Identify error patterns
|
||||
- **Finance** - LLM cost tracking and optimization
|
||||
|
||||
---
|
||||
|
||||
## Data Privacy
|
||||
|
||||
- Analytics data is aggregated and anonymized
|
||||
- User-level data requires appropriate permissions
|
||||
- Respect data retention policies
|
||||
- Comply with GDPR/CCPA as applicable
|
||||
|
||||
---
|
||||
|
||||
## Related Templates
|
||||
|
||||
- [BI Template](./template-bi.md) - Business Intelligence reporting
|
||||
- [Talk to Data](./template-talk-to-data.md) - Natural language data queries
|
||||
- [CRM](./template-crm.md) - CRM analytics and pipeline reports
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
- [Templates Reference](./templates.md) - Full template list
|
||||
- [Template Samples](./template-samples.md) - Example conversations
|
||||
- [gbdialog Reference](../chapter-06-gbdialog/README.md) - BASIC scripting guide
|
||||
466
docs/src/chapter-02/template-api-client.md
Normal file
466
docs/src/chapter-02/template-api-client.md
Normal file
|
|
@ -0,0 +1,466 @@
|
|||
# API Client Template (api-client.gbai)
|
||||
|
||||
A General Bots template demonstrating REST API integration patterns for connecting to external services and data sources.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
The API Client template provides examples and patterns for integrating General Bots with external REST APIs. It includes examples for weather services, Microsoft Partner Center integration, and general HTTP request patterns that can be adapted for any API.
|
||||
|
||||
## Features
|
||||
|
||||
- **REST API Integration** - GET, POST, PUT, DELETE request patterns
|
||||
- **Authentication** - OAuth, Bearer tokens, API keys
|
||||
- **Header Management** - Custom headers for API requirements
|
||||
- **Pagination Support** - Handle paginated API responses
|
||||
- **Data Synchronization** - Sync external data to local tables
|
||||
- **Scheduled Jobs** - Automated API polling and sync
|
||||
|
||||
---
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
api-client.gbai/
|
||||
├── api-client.gbdialog/
|
||||
│ ├── climate.bas # Weather API example
|
||||
│ └── msft-partner-center.bas # Microsoft Partner Center integration
|
||||
└── api-client.gbot/
|
||||
└── config.csv # Bot configuration
|
||||
```
|
||||
|
||||
## Scripts
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `climate.bas` | Weather API tool for getting current conditions |
|
||||
| `msft-partner-center.bas` | Full Microsoft Partner Center billing sync |
|
||||
|
||||
---
|
||||
|
||||
## Basic API Patterns
|
||||
|
||||
### Simple GET Request
|
||||
|
||||
```basic
|
||||
' Get data from an API
|
||||
response = GET "https://api.example.com/data"
|
||||
|
||||
IF response THEN
|
||||
TALK "Data received: " + response.value
|
||||
ELSE
|
||||
TALK "Failed to fetch data"
|
||||
END IF
|
||||
```
|
||||
|
||||
### POST Request with Body
|
||||
|
||||
```basic
|
||||
' Send data to an API
|
||||
SET HEADER "Content-Type" AS "application/json"
|
||||
|
||||
payload = {"name": "John", "email": "john@example.com"}
|
||||
response = POST "https://api.example.com/users", payload
|
||||
|
||||
IF response.id THEN
|
||||
TALK "User created with ID: " + response.id
|
||||
END IF
|
||||
```
|
||||
|
||||
### PUT Request for Updates
|
||||
|
||||
```basic
|
||||
' Update existing resource
|
||||
SET HEADER "Content-Type" AS "application/json"
|
||||
|
||||
updates = {"status": "active", "role": "admin"}
|
||||
response = PUT "https://api.example.com/users/123", updates
|
||||
|
||||
TALK "User updated: " + response.status
|
||||
```
|
||||
|
||||
### DELETE Request
|
||||
|
||||
```basic
|
||||
' Delete a resource
|
||||
response = DELETE "https://api.example.com/users/123"
|
||||
|
||||
IF response.deleted THEN
|
||||
TALK "User deleted successfully"
|
||||
END IF
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Authentication Patterns
|
||||
|
||||
### API Key Authentication
|
||||
|
||||
```basic
|
||||
SET HEADER "X-API-Key" AS "your-api-key-here"
|
||||
|
||||
response = GET "https://api.example.com/protected-resource"
|
||||
```
|
||||
|
||||
### Bearer Token Authentication
|
||||
|
||||
```basic
|
||||
SET HEADER "Authorization" AS "Bearer " + access_token
|
||||
|
||||
response = GET "https://api.example.com/user/profile"
|
||||
```
|
||||
|
||||
### OAuth 2.0 Token Exchange
|
||||
|
||||
```basic
|
||||
' Get OAuth token
|
||||
SET HEADER "Content-Type" AS "application/x-www-form-urlencoded"
|
||||
|
||||
tokenResponse = POST "https://auth.example.com/oauth/token",
|
||||
"grant_type=client_credentials&client_id=" + clientId +
|
||||
"&client_secret=" + clientSecret
|
||||
|
||||
access_token = tokenResponse.access_token
|
||||
|
||||
' Use token for API calls
|
||||
SET HEADER "Authorization" AS "Bearer " + access_token
|
||||
data = GET "https://api.example.com/resources"
|
||||
```
|
||||
|
||||
### Basic Authentication
|
||||
|
||||
```basic
|
||||
credentials = BASE64(username + ":" + password)
|
||||
SET HEADER "Authorization" AS "Basic " + credentials
|
||||
|
||||
response = GET "https://api.example.com/secure-endpoint"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Weather API Example
|
||||
|
||||
The `climate.bas` tool demonstrates a simple API integration:
|
||||
|
||||
```basic
|
||||
PARAM location AS "The city and state, e.g. San Francisco, CA"
|
||||
PARAM unit AS "celsius", "fahrenheit"
|
||||
|
||||
DESCRIPTION "Get the current weather in a given location"
|
||||
|
||||
' Implementation would call weather API
|
||||
' response = GET "https://api.weather.com/current?location=" + location
|
||||
|
||||
RETURN weather_info
|
||||
```
|
||||
|
||||
### Sample Conversation
|
||||
|
||||
```
|
||||
User: What's the weather in New York?
|
||||
|
||||
Bot: [Calls climate tool with location="New York"]
|
||||
It's currently 72°F and sunny in New York, NY.
|
||||
|
||||
Today's forecast:
|
||||
🌡️ High: 78°F / Low: 65°F
|
||||
💧 Humidity: 45%
|
||||
💨 Wind: 8 mph NW
|
||||
|
||||
User: What about São Paulo in celsius?
|
||||
|
||||
Bot: [Calls climate tool with location="São Paulo", unit="celsius"]
|
||||
It's currently 24°C and partly cloudy in São Paulo, Brazil.
|
||||
|
||||
Today's forecast:
|
||||
🌡️ High: 28°C / Low: 19°C
|
||||
💧 Humidity: 62%
|
||||
💨 Wind: 12 km/h SE
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Microsoft Partner Center Integration
|
||||
|
||||
The `msft-partner-center.bas` demonstrates a complex enterprise API integration:
|
||||
|
||||
### Features
|
||||
|
||||
- OAuth token authentication with Azure AD
|
||||
- Multi-resource synchronization (Customers, Subscriptions, Billing)
|
||||
- Scheduled execution
|
||||
- Pagination handling
|
||||
- Database table management
|
||||
|
||||
### Configuration
|
||||
|
||||
```basic
|
||||
' Required parameters
|
||||
tenantId = GET ENV "AZURE_TENANT_ID"
|
||||
clientId = GET ENV "AZURE_CLIENT_ID"
|
||||
clientSecret = GET ENV "AZURE_CLIENT_SECRET"
|
||||
host = "https://api.partnercenter.microsoft.com"
|
||||
```
|
||||
|
||||
### Scheduled Sync
|
||||
|
||||
```basic
|
||||
SET SCHEDULE "1 * * * * *" ' Run periodically
|
||||
|
||||
' Set required headers
|
||||
SET HEADER "MS-Contract-Version" AS "v1"
|
||||
SET HEADER "MS-CorrelationId" AS UUID()
|
||||
SET HEADER "MS-RequestId" AS UUID()
|
||||
SET HEADER "MS-PartnerCenter-Application" AS "General Bots"
|
||||
SET HEADER "X-Locale" AS "en-US"
|
||||
```
|
||||
|
||||
### Sync Customers and Subscriptions
|
||||
|
||||
```basic
|
||||
SET PAGE MODE "none"
|
||||
customers = GET host + "/v1/customers?size=20000"
|
||||
|
||||
MERGE "Customers" WITH customers.items BY "Id"
|
||||
|
||||
FOR EACH customer IN customers
|
||||
subs = GET host + "/v1/customers/" + customer.id + "/subscriptions"
|
||||
MERGE "Subscriptions" WITH subs.items BY "Id"
|
||||
END FOR
|
||||
```
|
||||
|
||||
### Billing Data Sync
|
||||
|
||||
```basic
|
||||
SET PAGE MODE "auto"
|
||||
billingItems = GET host + "/v1/invoices/unbilled/lineitems" +
|
||||
"?provider=onetime&invoicelineitemtype=usagelineitems¤cycode=USD"
|
||||
|
||||
FOR EACH item IN billingItems
|
||||
SAVE "Billing", item.alternateId, item.customerId, item.productName,
|
||||
item.quantity, item.unitPrice, item.subtotal, item.chargeStartDate
|
||||
END FOR
|
||||
```
|
||||
|
||||
### Table Definitions
|
||||
|
||||
```basic
|
||||
TABLE Billing
|
||||
CustomerId Customers
|
||||
ResourceGroup string(200)
|
||||
CustomerName string(400)
|
||||
ProductName string(400)
|
||||
Quantity double
|
||||
UnitPrice double
|
||||
Subtotal double
|
||||
ChargeStartDate date
|
||||
ChargeEndDate date
|
||||
END TABLE
|
||||
|
||||
TABLE Customers
|
||||
TenantId guid
|
||||
CompanyName string(100)
|
||||
Id guid
|
||||
END TABLE
|
||||
|
||||
TABLE Subscriptions
|
||||
CustomerId Customers
|
||||
Id guid
|
||||
OfferName string(50)
|
||||
END TABLE
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Custom API Integration
|
||||
|
||||
### Creating Your Own API Client
|
||||
|
||||
```basic
|
||||
' my-api-client.bas
|
||||
PARAM resource AS STRING LIKE "users" DESCRIPTION "API resource to fetch"
|
||||
PARAM filters AS STRING LIKE "status=active" DESCRIPTION "Query filters" OPTIONAL
|
||||
|
||||
DESCRIPTION "Fetch data from custom API"
|
||||
|
||||
' Configuration
|
||||
api_base = GET ENV "MY_API_BASE_URL"
|
||||
api_key = GET ENV "MY_API_KEY"
|
||||
|
||||
' Set authentication
|
||||
SET HEADER "Authorization" AS "Bearer " + api_key
|
||||
SET HEADER "Content-Type" AS "application/json"
|
||||
|
||||
' Build URL
|
||||
url = api_base + "/" + resource
|
||||
IF filters THEN
|
||||
url = url + "?" + filters
|
||||
END IF
|
||||
|
||||
' Make request
|
||||
response = GET url
|
||||
|
||||
IF response.error THEN
|
||||
RETURN {"success": false, "error": response.error}
|
||||
END IF
|
||||
|
||||
RETURN {"success": true, "data": response.data, "count": UBOUND(response.data)}
|
||||
```
|
||||
|
||||
### Handling Pagination
|
||||
|
||||
```basic
|
||||
' paginated-fetch.bas
|
||||
PARAM endpoint AS STRING DESCRIPTION "API endpoint"
|
||||
|
||||
DESCRIPTION "Fetch all pages from a paginated API"
|
||||
|
||||
all_results = []
|
||||
page = 1
|
||||
has_more = true
|
||||
|
||||
DO WHILE has_more
|
||||
response = GET endpoint + "?page=" + page + "&per_page=100"
|
||||
|
||||
IF response.data THEN
|
||||
all_results = MERGE all_results, response.data
|
||||
|
||||
IF UBOUND(response.data) < 100 THEN
|
||||
has_more = false
|
||||
ELSE
|
||||
page = page + 1
|
||||
END IF
|
||||
ELSE
|
||||
has_more = false
|
||||
END IF
|
||||
LOOP
|
||||
|
||||
RETURN all_results
|
||||
```
|
||||
|
||||
### Error Handling with Retry
|
||||
|
||||
```basic
|
||||
' api-with-retry.bas
|
||||
PARAM url AS STRING DESCRIPTION "API URL to call"
|
||||
PARAM max_retries AS INTEGER LIKE 3 DESCRIPTION "Maximum retry attempts"
|
||||
|
||||
DESCRIPTION "API call with automatic retry on failure"
|
||||
|
||||
retries = 0
|
||||
success = false
|
||||
|
||||
DO WHILE retries < max_retries AND NOT success
|
||||
response = GET url
|
||||
|
||||
IF response.error THEN
|
||||
retries = retries + 1
|
||||
WAIT retries * 2 ' Exponential backoff
|
||||
ELSE
|
||||
success = true
|
||||
END IF
|
||||
LOOP
|
||||
|
||||
IF success THEN
|
||||
RETURN response
|
||||
ELSE
|
||||
RETURN {"error": "Max retries exceeded", "last_error": response.error}
|
||||
END IF
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
Configure in `api-client.gbot/config.csv`:
|
||||
|
||||
| Parameter | Description | Example |
|
||||
|-----------|-------------|---------|
|
||||
| `API Base URL` | Default API endpoint | `https://api.example.com` |
|
||||
| `API Timeout` | Request timeout in seconds | `30` |
|
||||
| `Retry Count` | Number of retry attempts | `3` |
|
||||
| `Log Requests` | Enable request logging | `true` |
|
||||
|
||||
### Environment Variables
|
||||
|
||||
Store sensitive values as environment variables:
|
||||
|
||||
```bash
|
||||
MY_API_KEY=your-api-key
|
||||
MY_API_SECRET=your-secret
|
||||
AZURE_TENANT_ID=your-tenant-id
|
||||
AZURE_CLIENT_ID=your-client-id
|
||||
AZURE_CLIENT_SECRET=your-client-secret
|
||||
```
|
||||
|
||||
Access in BASIC:
|
||||
|
||||
```basic
|
||||
api_key = GET ENV "MY_API_KEY"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Common HTTP Headers
|
||||
|
||||
| Header | Purpose | Example |
|
||||
|--------|---------|---------|
|
||||
| `Content-Type` | Request body format | `application/json` |
|
||||
| `Accept` | Expected response format | `application/json` |
|
||||
| `Authorization` | Authentication | `Bearer token` |
|
||||
| `X-API-Key` | API key auth | `your-key` |
|
||||
| `User-Agent` | Client identification | `GeneralBots/1.0` |
|
||||
|
||||
---
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Secure credentials** - Never hardcode API keys; use environment variables
|
||||
2. **Handle errors** - Always check for error responses
|
||||
3. **Rate limiting** - Respect API rate limits with delays
|
||||
4. **Pagination** - Handle paginated responses properly
|
||||
5. **Logging** - Log API calls for debugging
|
||||
6. **Timeouts** - Set appropriate timeout values
|
||||
7. **Retries** - Implement retry logic for transient failures
|
||||
8. **Caching** - Cache responses when appropriate
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Issue | Cause | Solution |
|
||||
|-------|-------|----------|
|
||||
| 401 Unauthorized | Invalid credentials | Check API key/token |
|
||||
| 403 Forbidden | Missing permissions | Verify API access rights |
|
||||
| 404 Not Found | Wrong endpoint | Verify URL path |
|
||||
| 429 Too Many Requests | Rate limited | Add delays between requests |
|
||||
| 500 Server Error | API issue | Retry with backoff |
|
||||
| Timeout | Slow API | Increase timeout setting |
|
||||
|
||||
---
|
||||
|
||||
## Use Cases
|
||||
|
||||
- **Data Synchronization** - Sync data from external systems
|
||||
- **Service Integration** - Connect to SaaS platforms
|
||||
- **Automation** - Automate cross-system workflows
|
||||
- **Monitoring** - Poll external systems for changes
|
||||
- **Reporting** - Aggregate data from multiple APIs
|
||||
|
||||
---
|
||||
|
||||
## Related Templates
|
||||
|
||||
- [Public APIs](./template-public-apis.md) - Pre-built integrations for public APIs
|
||||
- [Bling ERP](./template-bling.md) - ERP API integration example
|
||||
- [LLM Server](./template-llm-server.md) - Building your own API endpoints
|
||||
- [CRM](./template-crm.md) - CRM with external API sync
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
- [Templates Reference](./templates.md) - Full template list
|
||||
- [Template Samples](./template-samples.md) - Example conversations
|
||||
- [gbdialog Reference](../chapter-06-gbdialog/README.md) - BASIC scripting guide
|
||||
272
docs/src/chapter-02/template-bi.md
Normal file
272
docs/src/chapter-02/template-bi.md
Normal file
|
|
@ -0,0 +1,272 @@
|
|||
# Business Intelligence Template (bi.gbai)
|
||||
|
||||
A General Bots template for automated business intelligence reporting and data visualization.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
The BI template provides scheduled analytics reporting with automatic chart generation and delivery. It's designed for organizations that need automated consumption reports, category analysis, and customer-specific insights.
|
||||
|
||||
## Features
|
||||
|
||||
- **Scheduled Reporting** - Automated report generation on configurable schedules
|
||||
- **Time-Series Charts** - Monthly consumption trends visualization
|
||||
- **Category Analysis** - Product category breakdown with donut charts
|
||||
- **Per-Customer Reports** - Individual customer consumption analysis
|
||||
- **Multi-Channel Delivery** - Send reports via chat, email, or messaging platforms
|
||||
|
||||
---
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
bi.gbai/
|
||||
├── bi.gbai/
|
||||
│ ├── bi-admin.bas # Administrative scheduled reports
|
||||
│ └── bi-user.bas # Per-customer report generation
|
||||
```
|
||||
|
||||
## Scripts
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `bi-admin.bas` | Scheduled job for generating platform-wide analytics reports |
|
||||
| `bi-user.bas` | Loop through customers to generate individual consumption reports |
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
Configure the template in your bot's `config.csv`:
|
||||
|
||||
| Parameter | Description | Example |
|
||||
|-----------|-------------|---------|
|
||||
| `Schedule` | Cron expression for report timing | `1 * * * * *` |
|
||||
| `Data Source` | Table/view for billing data | `Orders` |
|
||||
|
||||
---
|
||||
|
||||
## Usage
|
||||
|
||||
### Administrative Reports
|
||||
|
||||
The `bi-admin.bas` script runs on a schedule and generates:
|
||||
|
||||
1. **Monthly Consumption Chart** - Time-series showing spending trends
|
||||
2. **Product Category Breakdown** - Donut chart of spending by category
|
||||
|
||||
```basic
|
||||
SET SCHEDULE "1 * * * * *"
|
||||
|
||||
billing = FIND "Orders"
|
||||
|
||||
' Monthly consumption
|
||||
data = SELECT SUM(UnitPrice * Quantity) as Value,
|
||||
MONTH(OrderDate)+'/'+YEAR(OrderDate)
|
||||
FROM billing
|
||||
GROUP BY MONTH(OrderDate), YEAR(OrderDate)
|
||||
|
||||
img = CHART "timeseries", data
|
||||
SEND FILE img, "Monthly Consumption"
|
||||
```
|
||||
|
||||
### Per-Customer Reports
|
||||
|
||||
The `bi-user.bas` script iterates through customers to generate personalized reports:
|
||||
|
||||
```basic
|
||||
customers = FIND "Customers"
|
||||
|
||||
FOR EACH c IN customers
|
||||
data = SELECT SUM(UnitPrice * Quantity) AS Value,
|
||||
MONTH(OrderDate)+'/'+YEAR(OrderDate)
|
||||
FROM billing
|
||||
JOIN Customers ON billing.CustomerID = Customers.CustomerID
|
||||
GROUP BY MONTH(OrderDate), YEAR(OrderDate)
|
||||
WHERE Customers.CustomerID = c.CustomerID
|
||||
|
||||
img = CHART "timeseries", data
|
||||
SEND FILE img, "Monthly Consumption"
|
||||
END FOR
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Chart Types
|
||||
|
||||
The template supports various chart types:
|
||||
|
||||
| Type | Use Case |
|
||||
|------|----------|
|
||||
| `timeseries` | Trends over time (monthly, weekly, daily) |
|
||||
| `donut` | Category distribution |
|
||||
| `bar` | Comparative analysis |
|
||||
| `pie` | Percentage breakdowns |
|
||||
|
||||
---
|
||||
|
||||
## Data Requirements
|
||||
|
||||
### Orders Table Schema
|
||||
|
||||
The template expects a billing/orders data source with:
|
||||
|
||||
- `OrderDate` - Date of the transaction
|
||||
- `UnitPrice` - Price per unit
|
||||
- `Quantity` - Number of units
|
||||
- `ProductID` - Foreign key to products
|
||||
- `CustomerID` - Foreign key to customers
|
||||
|
||||
### Products Table Schema
|
||||
|
||||
- `ProductID` - Primary key
|
||||
- `CategoryID` - Foreign key to categories
|
||||
- `ProductName` - Product name
|
||||
|
||||
### Categories Table Schema
|
||||
|
||||
- `CategoryID` - Primary key
|
||||
- `CategoryName` - Category display name
|
||||
|
||||
---
|
||||
|
||||
## Example Output
|
||||
|
||||
### Monthly Consumption Report
|
||||
|
||||
```
|
||||
📊 Monthly Consumption Report
|
||||
-----------------------------
|
||||
Generated: 2024-01-15 08:00
|
||||
|
||||
[Time Series Chart Image]
|
||||
|
||||
Total Revenue: $125,430
|
||||
Top Month: December ($18,500)
|
||||
Growth Rate: +12% MoM
|
||||
```
|
||||
|
||||
### Category Breakdown
|
||||
|
||||
```
|
||||
📊 Product Category Distribution
|
||||
--------------------------------
|
||||
|
||||
[Donut Chart Image]
|
||||
|
||||
Electronics: 35%
|
||||
Clothing: 28%
|
||||
Home & Garden: 22%
|
||||
Other: 15%
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Customization
|
||||
|
||||
### Adding New Reports
|
||||
|
||||
Create additional `.bas` files in the `bi.gbai` folder:
|
||||
|
||||
```basic
|
||||
' sales-by-region.bas
|
||||
SET SCHEDULE "0 9 * * 1" ' Every Monday at 9 AM
|
||||
|
||||
data = SELECT Region, SUM(Amount) as Total
|
||||
FROM Sales
|
||||
GROUP BY Region
|
||||
|
||||
img = CHART "bar", data
|
||||
SEND FILE img, "Weekly Regional Sales"
|
||||
```
|
||||
|
||||
### Customizing Delivery
|
||||
|
||||
Send reports to specific users or channels:
|
||||
|
||||
```basic
|
||||
' Send to specific user
|
||||
SEND FILE img TO "manager@company.com", "Weekly Report"
|
||||
|
||||
' Send to WhatsApp
|
||||
SEND FILE img TO "+1234567890", "Your monthly report"
|
||||
|
||||
' Send to team channel
|
||||
TALK TO "sales-team", img
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Scheduling Options
|
||||
|
||||
| Schedule | Cron Expression | Description |
|
||||
|----------|-----------------|-------------|
|
||||
| Every minute | `1 * * * * *` | Testing/real-time |
|
||||
| Hourly | `0 0 * * * *` | Frequent updates |
|
||||
| Daily 8 AM | `0 0 8 * * *` | Morning reports |
|
||||
| Weekly Monday | `0 0 9 * * 1` | Weekly summaries |
|
||||
| Monthly 1st | `0 0 8 1 * *` | Monthly reports |
|
||||
|
||||
---
|
||||
|
||||
## Integration Examples
|
||||
|
||||
### With CRM
|
||||
|
||||
```basic
|
||||
' Combine with CRM data
|
||||
opportunities = FIND "opportunities.csv"
|
||||
revenue = SELECT stage, SUM(amount) FROM opportunities GROUP BY stage
|
||||
|
||||
img = CHART "funnel", revenue
|
||||
SEND FILE img, "Sales Pipeline"
|
||||
```
|
||||
|
||||
### With ERP
|
||||
|
||||
```basic
|
||||
' Inventory analysis
|
||||
inventory = FIND "inventory.csv"
|
||||
low_stock = SELECT product, quantity FROM inventory WHERE quantity < reorder_level
|
||||
|
||||
img = CHART "bar", low_stock
|
||||
SEND FILE img, "Low Stock Alert"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Schedule appropriately** - Don't run heavy reports too frequently
|
||||
2. **Filter data** - Use date ranges to limit data volume
|
||||
3. **Cache results** - Store computed metrics for faster access
|
||||
4. **Log activities** - Track report generation for auditing
|
||||
5. **Handle errors** - Wrap queries in error handling
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Issue | Solution |
|
||||
|-------|----------|
|
||||
| Empty charts | Verify data source has records |
|
||||
| Schedule not running | Check cron syntax |
|
||||
| Slow reports | Add date filters, optimize queries |
|
||||
| Missing data | Verify JOIN conditions |
|
||||
|
||||
---
|
||||
|
||||
## Related Templates
|
||||
|
||||
- [Platform Analytics](./template-analytics.md) - Platform metrics and monitoring
|
||||
- [Talk to Data](./template-talk-to-data.md) - Natural language data queries
|
||||
- [CRM](./template-crm.md) - CRM with built-in reporting
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
- [Templates Reference](./templates.md) - Full template list
|
||||
- [Template Samples](./template-samples.md) - Example conversations
|
||||
- [gbdialog Reference](../chapter-06-gbdialog/README.md) - BASIC scripting guide
|
||||
330
docs/src/chapter-02/template-crawler.md
Normal file
330
docs/src/chapter-02/template-crawler.md
Normal file
|
|
@ -0,0 +1,330 @@
|
|||
# Web Crawler Template (crawler.gbai)
|
||||
|
||||
A General Bots template for automated web crawling and content extraction for knowledge base population.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
The Crawler template enables your bot to automatically fetch, parse, and index web content. It's designed for building knowledge bases from websites, monitoring web pages for changes, and extracting structured data from online sources.
|
||||
|
||||
## Features
|
||||
|
||||
- **Automated Web Scraping** - Fetch and parse web pages automatically
|
||||
- **Document Mode** - Answer questions based on crawled content
|
||||
- **Configurable Depth** - Control how many pages to crawl
|
||||
- **Content Indexing** - Automatically add content to knowledge base
|
||||
- **LLM Integration** - Use AI to understand and summarize crawled content
|
||||
|
||||
---
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
crawler.gbai/
|
||||
├── crawler.gbkb/ # Knowledge base for crawled content
|
||||
│ └── docs/ # Indexed documents
|
||||
└── crawler.gbot/
|
||||
└── config.csv # Crawler configuration
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
Configure the crawler in `crawler.gbot/config.csv`:
|
||||
|
||||
| Parameter | Description | Example |
|
||||
|-----------|-------------|---------|
|
||||
| `Website` | Target URL to crawl | `https://pragmatismo.com.br/` |
|
||||
| `website Max Documents` | Maximum pages to crawl | `2` |
|
||||
| `Answer Mode` | How to respond to queries | `document` |
|
||||
| `Theme Color` | UI theme color | `purple` |
|
||||
| `LLM Provider` | AI provider for processing | `openai` |
|
||||
|
||||
### Example config.csv
|
||||
|
||||
```csv
|
||||
name,value
|
||||
Website,https://pragmatismo.com.br/
|
||||
website Max Documents,2
|
||||
Answer Mode,document
|
||||
Theme Color,purple
|
||||
LLM Provider,openai
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## How It Works
|
||||
|
||||
1. **Initialization** - Bot reads the target website from configuration
|
||||
2. **Crawling** - Fetches pages starting from the root URL
|
||||
3. **Extraction** - Parses HTML and extracts meaningful text content
|
||||
4. **Indexing** - Stores content in the knowledge base for RAG
|
||||
5. **Q&A** - Users can ask questions about the crawled content
|
||||
|
||||
---
|
||||
|
||||
## Usage
|
||||
|
||||
### Basic Setup
|
||||
|
||||
1. Copy the template to your bot's packages directory:
|
||||
|
||||
```bash
|
||||
cp -r templates/crawler.gbai /path/to/your/bot/packages/
|
||||
```
|
||||
|
||||
2. Edit `crawler.gbot/config.csv` with your target website:
|
||||
|
||||
```csv
|
||||
name,value
|
||||
Website,https://your-website.com/
|
||||
website Max Documents,10
|
||||
Answer Mode,document
|
||||
```
|
||||
|
||||
3. Deploy and the bot will automatically crawl the configured site.
|
||||
|
||||
### Querying Crawled Content
|
||||
|
||||
Once crawled, users can ask questions naturally:
|
||||
|
||||
- "What services does the company offer?"
|
||||
- "Tell me about the pricing"
|
||||
- "Summarize the about page"
|
||||
- "What are the main features?"
|
||||
|
||||
### Answer Modes
|
||||
|
||||
| Mode | Behavior |
|
||||
|------|----------|
|
||||
| `document` | Answers strictly based on crawled content |
|
||||
| `hybrid` | Combines crawled content with general knowledge |
|
||||
| `summary` | Provides concise summaries of relevant pages |
|
||||
|
||||
---
|
||||
|
||||
## Sample Conversation
|
||||
|
||||
```
|
||||
User: What does this company do?
|
||||
|
||||
Bot: Based on the website content:
|
||||
|
||||
Pragmatismo provides enterprise AI solutions
|
||||
including:
|
||||
|
||||
• General Bots platform
|
||||
• Custom AI development
|
||||
• Conversational AI consulting
|
||||
• Integration services
|
||||
|
||||
📄 Source: pragmatismo.com.br/about
|
||||
|
||||
User: Do they have any case studies?
|
||||
|
||||
Bot: Yes! According to the website, they have worked
|
||||
with several enterprise clients:
|
||||
|
||||
• Banking sector automation
|
||||
• Healthcare chatbots
|
||||
• E-commerce customer service
|
||||
|
||||
📄 Source: pragmatismo.com.br/cases
|
||||
|
||||
User: How can I contact them?
|
||||
|
||||
Bot: Contact information from the website:
|
||||
|
||||
📧 Email: contact@pragmatismo.com.br
|
||||
📍 Location: São Paulo, Brazil
|
||||
🌐 Website: pragmatismo.com.br
|
||||
|
||||
📄 Source: pragmatismo.com.br/contact
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Advanced Configuration
|
||||
|
||||
### Limiting Crawl Scope
|
||||
|
||||
Control which pages are crawled:
|
||||
|
||||
```csv
|
||||
name,value
|
||||
Website,https://example.com/docs/
|
||||
website Max Documents,50
|
||||
Website Include Pattern,/docs/*
|
||||
Website Exclude Pattern,/docs/archive/*
|
||||
```
|
||||
|
||||
### Scheduling Recrawls
|
||||
|
||||
Set up periodic recrawling to keep content fresh:
|
||||
|
||||
```csv
|
||||
name,value
|
||||
Website Refresh Schedule,0 0 * * 0
|
||||
```
|
||||
|
||||
This example recrawls every Sunday at midnight.
|
||||
|
||||
### Authentication
|
||||
|
||||
For sites requiring authentication:
|
||||
|
||||
```csv
|
||||
name,value
|
||||
Website Auth Type,basic
|
||||
Website Username,user
|
||||
Website Password,secret
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Customization
|
||||
|
||||
### Creating Custom Crawl Logic
|
||||
|
||||
Create a BASIC dialog for custom crawling:
|
||||
|
||||
```basic
|
||||
' custom-crawl.bas
|
||||
urls = ["https://site1.com", "https://site2.com", "https://site3.com"]
|
||||
|
||||
FOR EACH url IN urls
|
||||
content = GET url
|
||||
|
||||
IF content THEN
|
||||
SAVE "crawled_pages.csv", url, content, NOW()
|
||||
SET CONTEXT content
|
||||
END IF
|
||||
NEXT
|
||||
|
||||
TALK "Crawled " + UBOUND(urls) + " pages successfully."
|
||||
```
|
||||
|
||||
### Processing Crawled Content
|
||||
|
||||
Use LLM to process and structure crawled data:
|
||||
|
||||
```basic
|
||||
' process-crawled.bas
|
||||
pages = FIND "crawled_pages.csv"
|
||||
|
||||
FOR EACH page IN pages
|
||||
summary = LLM "Summarize this content in 3 bullet points: " + page.content
|
||||
|
||||
WITH processed
|
||||
url = page.url
|
||||
summary = summary
|
||||
processed_at = NOW()
|
||||
END WITH
|
||||
|
||||
SAVE "processed_content.csv", processed
|
||||
NEXT
|
||||
```
|
||||
|
||||
### Extracting Structured Data
|
||||
|
||||
Extract specific information from pages:
|
||||
|
||||
```basic
|
||||
' extract-products.bas
|
||||
SET CONTEXT "You are a data extraction assistant. Extract product information as JSON."
|
||||
|
||||
page_content = GET "https://store.example.com/products"
|
||||
|
||||
products = LLM "Extract all products with name, price, and description as JSON array: " + page_content
|
||||
|
||||
SAVE "products.json", products
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Integration Examples
|
||||
|
||||
### With Knowledge Base
|
||||
|
||||
```basic
|
||||
' Add crawled content to KB
|
||||
content = GET "https://docs.example.com/api"
|
||||
|
||||
IF content THEN
|
||||
USE KB "api-docs.gbkb"
|
||||
ADD TO KB content, "API Documentation"
|
||||
END IF
|
||||
```
|
||||
|
||||
### With Notifications
|
||||
|
||||
```basic
|
||||
' Monitor for changes
|
||||
previous = GET BOT MEMORY "last_content"
|
||||
current = GET "https://news.example.com"
|
||||
|
||||
IF current <> previous THEN
|
||||
SEND EMAIL "admin@company.com", "Website Changed", "The monitored page has been updated."
|
||||
SET BOT MEMORY "last_content", current
|
||||
END IF
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Respect robots.txt** - Only crawl pages allowed by the site's robots.txt
|
||||
2. **Rate limiting** - Don't overwhelm target servers with requests
|
||||
3. **Set reasonable limits** - Start with low `Max Documents` values
|
||||
4. **Monitor content quality** - Review crawled content for accuracy
|
||||
5. **Keep content fresh** - Schedule periodic recrawls for dynamic sites
|
||||
6. **Handle errors gracefully** - Implement retry logic for failed requests
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Issue | Cause | Solution |
|
||||
|-------|-------|----------|
|
||||
| No content indexed | Invalid URL | Verify the Website URL is accessible |
|
||||
| Partial content | Max Documents too low | Increase the limit in config |
|
||||
| Stale answers | Content not refreshed | Set up scheduled recrawls |
|
||||
| Authentication errors | Missing credentials | Add auth settings to config |
|
||||
| Timeout errors | Slow target site | Increase timeout settings |
|
||||
|
||||
---
|
||||
|
||||
## Limitations
|
||||
|
||||
- JavaScript-rendered content may not be fully captured
|
||||
- Some sites block automated crawlers
|
||||
- Large sites may take significant time to fully crawl
|
||||
- Dynamic content may require special handling
|
||||
|
||||
---
|
||||
|
||||
## Use Cases
|
||||
|
||||
- **Documentation Bots** - Index product docs for support
|
||||
- **Competitive Intelligence** - Monitor competitor websites
|
||||
- **News Aggregation** - Collect news from multiple sources
|
||||
- **Research Assistants** - Build knowledge bases from academic sources
|
||||
- **FAQ Generators** - Extract FAQs from help sites
|
||||
|
||||
---
|
||||
|
||||
## Related Templates
|
||||
|
||||
- [AI Search](./template-ai-search.md) - AI-powered document search
|
||||
- [Talk to Data](./template-talk-to-data.md) - Natural language data queries
|
||||
- [Law](./template-law.md) - Legal document processing with similar RAG approach
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
- [Templates Reference](./templates.md) - Full template list
|
||||
- [Template Samples](./template-samples.md) - Example conversations
|
||||
- [gbkb Reference](../chapter-03/README.md) - Knowledge base guide
|
||||
481
docs/src/chapter-02/template-crm.md
Normal file
481
docs/src/chapter-02/template-crm.md
Normal file
|
|
@ -0,0 +1,481 @@
|
|||
# Sales CRM Template (crm.gbai)
|
||||
|
||||
A comprehensive General Bots template for sales customer relationship management with lead tracking, opportunity management, and sales pipeline automation.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
The CRM template provides a full-featured sales CRM system with conversational AI capabilities. It enables sales teams to manage leads, track opportunities through the pipeline, generate quotes, send proposals, and forecast revenue—all through natural conversation or automated workflows.
|
||||
|
||||
## Features
|
||||
|
||||
- **Lead Management** - Capture, qualify, convert, and nurture leads
|
||||
- **Opportunity Pipeline** - Track deals through customizable stages
|
||||
- **Account Management** - Manage customer accounts and contacts
|
||||
- **Activity Tracking** - Log calls, emails, meetings, and tasks
|
||||
- **Quote Generation** - Create and send professional quotes
|
||||
- **Proposal Automation** - Generate and deliver sales proposals
|
||||
- **Sales Forecasting** - Pipeline analysis and revenue projections
|
||||
- **Email Integration** - Receive and process emails automatically
|
||||
- **Sentiment Analysis** - AI-powered customer sentiment tracking
|
||||
- **Data Enrichment** - Automatic lead data enhancement
|
||||
|
||||
---
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
crm.gbai/
|
||||
├── crm.gbdialog/
|
||||
│ ├── lead-management.bas # Lead lifecycle management
|
||||
│ ├── opportunity-management.bas # Opportunity pipeline
|
||||
│ ├── account-management.bas # Account/company management
|
||||
│ ├── activity-tracking.bas # Activity logging
|
||||
│ ├── case-management.bas # Support case handling
|
||||
│ ├── analyze-customer-sentiment.bas # AI sentiment analysis
|
||||
│ ├── data-enrichment.bas # Lead data enhancement
|
||||
│ ├── send-proposal.bas # Proposal generation
|
||||
│ ├── create-lead-from-draft.bas # Email to lead conversion
|
||||
│ ├── crm-jobs.bas # Scheduled background jobs
|
||||
│ └── tables.bas # Database schema definitions
|
||||
└── crm.gbot/
|
||||
└── config.csv # Bot configuration
|
||||
```
|
||||
|
||||
## Scripts
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `lead-management.bas` | Complete lead lifecycle: capture, qualify, convert, follow-up, nurture |
|
||||
| `opportunity-management.bas` | Pipeline stages, quotes, products, forecasting |
|
||||
| `account-management.bas` | Account and contact management |
|
||||
| `activity-tracking.bas` | Log and track all sales activities |
|
||||
| `case-management.bas` | Customer support case handling |
|
||||
| `analyze-customer-sentiment.bas` | AI-powered sentiment analysis |
|
||||
| `data-enrichment.bas` | Enrich leads with external data |
|
||||
| `send-proposal.bas` | Generate and send proposals |
|
||||
| `on-receive-email.bas` | Process incoming emails |
|
||||
| `crm-jobs.bas` | Scheduled automation tasks |
|
||||
| `tables.bas` | CRM database schema |
|
||||
|
||||
---
|
||||
|
||||
## Data Schema
|
||||
|
||||
### Leads Table
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `id` | GUID | Unique identifier |
|
||||
| `name` | String | Lead name |
|
||||
| `email` | Email | Email address |
|
||||
| `phone` | Phone | Phone number |
|
||||
| `company` | String | Company name |
|
||||
| `source` | String | Lead source |
|
||||
| `status` | String | new, qualified, hot, warm, cold, converted |
|
||||
| `score` | Integer | Lead qualification score (0-100) |
|
||||
| `assigned_to` | String | Sales rep ID |
|
||||
| `created_at` | DateTime | Creation timestamp |
|
||||
|
||||
### Opportunities Table
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `id` | GUID | Unique identifier |
|
||||
| `name` | String | Opportunity name |
|
||||
| `account_id` | GUID | Related account |
|
||||
| `contact_id` | GUID | Primary contact |
|
||||
| `amount` | Decimal | Deal value |
|
||||
| `stage` | String | Pipeline stage |
|
||||
| `probability` | Integer | Win probability (0-100) |
|
||||
| `close_date` | Date | Expected close date |
|
||||
| `owner_id` | String | Sales rep ID |
|
||||
| `lead_source` | String | Original lead source |
|
||||
|
||||
### Accounts Table
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `id` | GUID | Unique identifier |
|
||||
| `name` | String | Company name |
|
||||
| `type` | String | prospect, customer, partner |
|
||||
| `industry` | String | Industry vertical |
|
||||
| `owner_id` | String | Account owner |
|
||||
| `created_from_lead` | GUID | Original lead ID |
|
||||
|
||||
### Contacts Table
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `id` | GUID | Unique identifier |
|
||||
| `account_id` | GUID | Parent account |
|
||||
| `name` | String | Full name |
|
||||
| `email` | Email | Email address |
|
||||
| `phone` | Phone | Phone number |
|
||||
| `title` | String | Job title |
|
||||
| `primary_contact` | Boolean | Primary contact flag |
|
||||
|
||||
### Activities Table
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `id` | GUID | Unique identifier |
|
||||
| `type` | String | call, email, meeting, task |
|
||||
| `subject` | String | Activity subject |
|
||||
| `lead_id` | GUID | Related lead |
|
||||
| `opportunity_id` | GUID | Related opportunity |
|
||||
| `created_at` | DateTime | Activity timestamp |
|
||||
|
||||
---
|
||||
|
||||
## Pipeline Stages
|
||||
|
||||
| Stage | Probability | Description |
|
||||
|-------|-------------|-------------|
|
||||
| `qualification` | 10% | Initial qualification |
|
||||
| `needs_analysis` | 20% | Understanding requirements |
|
||||
| `value_proposition` | 50% | Presenting solution |
|
||||
| `decision_makers` | 60% | Engaging decision makers |
|
||||
| `proposal` | 75% | Proposal sent |
|
||||
| `negotiation` | 90% | Terms negotiation |
|
||||
| `closed_won` | 100% | Deal closed - won |
|
||||
| `closed_lost` | 0% | Deal closed - lost |
|
||||
|
||||
---
|
||||
|
||||
## Sample Conversations
|
||||
|
||||
### Lead Capture
|
||||
|
||||
```
|
||||
User: I just got a lead from the website
|
||||
|
||||
Bot: Great! I'll help you capture it. What's their name?
|
||||
|
||||
User: John Smith from TechCorp
|
||||
|
||||
Bot: What's their email?
|
||||
|
||||
User: john@techcorp.com
|
||||
|
||||
Bot: ✅ Lead captured: John Smith (TechCorp)
|
||||
ID: LEAD-20240115-4821
|
||||
|
||||
Would you like to qualify this lead now?
|
||||
```
|
||||
|
||||
### Lead Qualification (BANT)
|
||||
|
||||
```
|
||||
User: Yes, qualify the lead
|
||||
|
||||
Bot: I'll ask a few questions to qualify them.
|
||||
|
||||
What is TechCorp's annual revenue range?
|
||||
1. Under $1M
|
||||
2. $1M - $10M
|
||||
3. $10M - $50M
|
||||
4. Over $50M
|
||||
|
||||
User: 3
|
||||
|
||||
Bot: How many employees?
|
||||
|
||||
User: About 200
|
||||
|
||||
Bot: What's their timeline for making a decision?
|
||||
|
||||
User: This quarter
|
||||
|
||||
Bot: Do they have budget allocated?
|
||||
|
||||
User: Yes
|
||||
|
||||
Bot: 🔥 Hot Lead! Score: 85/100
|
||||
|
||||
This lead is a great fit. I've:
|
||||
• Notified sales@company.com
|
||||
• Created a follow-up task
|
||||
|
||||
Would you like to convert to an opportunity?
|
||||
```
|
||||
|
||||
### Opportunity Management
|
||||
|
||||
```
|
||||
User: Create a new opportunity for Acme Corp
|
||||
|
||||
Bot: What should we call this opportunity?
|
||||
|
||||
User: Enterprise License Deal
|
||||
|
||||
Bot: What is the estimated value of this deal?
|
||||
|
||||
User: $50,000
|
||||
|
||||
Bot: When do you expect to close this deal?
|
||||
|
||||
User: End of Q2
|
||||
|
||||
Bot: ✅ Opportunity created: Enterprise License Deal
|
||||
|
||||
Account: Acme Corp
|
||||
Value: $50,000
|
||||
Stage: Qualification (10%)
|
||||
Close Date: June 30, 2024
|
||||
```
|
||||
|
||||
### Pipeline Update
|
||||
|
||||
```
|
||||
User: Update the Acme deal to proposal stage
|
||||
|
||||
Bot: Current stage: value_proposition
|
||||
|
||||
Select new stage:
|
||||
1. Qualification (10%)
|
||||
2. Needs Analysis (20%)
|
||||
3. Value Proposition (50%)
|
||||
4. Decision Makers (60%)
|
||||
5. Proposal (75%)
|
||||
6. Negotiation (90%)
|
||||
7. Closed Won (100%)
|
||||
8. Closed Lost (0%)
|
||||
|
||||
User: 5
|
||||
|
||||
Bot: ✅ Stage updated to proposal (75%)
|
||||
|
||||
Would you like to generate a quote for this opportunity?
|
||||
```
|
||||
|
||||
### Sales Forecast
|
||||
|
||||
```
|
||||
User: Show me the sales forecast
|
||||
|
||||
Bot: 📊 SALES FORECAST
|
||||
════════════════════════════════════════
|
||||
|
||||
Total Pipeline: $425,000
|
||||
Weighted Pipeline: $187,500
|
||||
|
||||
Quarterly Forecast:
|
||||
├── Q1: $45,000
|
||||
├── Q2: $82,500
|
||||
├── Q3: $35,000
|
||||
└── Q4: $25,000
|
||||
|
||||
Top Opportunities:
|
||||
1. Enterprise License - Acme Corp ($50,000) - 75%
|
||||
2. Platform Upgrade - TechStart ($35,000) - 60%
|
||||
3. Consulting Deal - DataFlow ($28,000) - 50%
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Lead Qualification Scoring
|
||||
|
||||
The qualification process scores leads based on BANT criteria:
|
||||
|
||||
- **Budget** - Revenue range (up to 30 points)
|
||||
- **Authority** - Employee count/company size (up to 25 points)
|
||||
- **Need** - Timeline urgency (up to 30 points)
|
||||
- **Timeline** - Budget allocation (up to 25 points)
|
||||
|
||||
### Scoring Thresholds
|
||||
|
||||
| Score | Status | Action |
|
||||
|-------|--------|--------|
|
||||
| ≥70 | Hot Lead | Immediate follow-up |
|
||||
| 50-69 | Warm Lead | 24-hour response |
|
||||
| 30-49 | Cold Lead | Nurture campaign |
|
||||
| <30 | Unqualified | Archive |
|
||||
|
||||
---
|
||||
|
||||
## Lead Nurturing
|
||||
|
||||
Automated nurture campaigns based on lead age:
|
||||
|
||||
| Days | Content |
|
||||
|------|---------|
|
||||
| 3 | 5 Tips to Improve Your Business |
|
||||
| 7 | Case Study: How We Helped Similar Companies |
|
||||
| 14 | Free Consultation Offer |
|
||||
| 30 | Special Limited Time Offer |
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
Configure in `crm.gbot/config.csv`:
|
||||
|
||||
| Parameter | Description | Example |
|
||||
|-----------|-------------|---------|
|
||||
| `Company Name` | Your company name | `Acme Sales` |
|
||||
| `Currency` | Default currency | `USD` |
|
||||
| `Tax Rate` | Default tax percentage | `10` |
|
||||
| `Quote Validity Days` | Quote expiration | `30` |
|
||||
| `Pipeline Stages` | Custom stage definitions | (JSON) |
|
||||
| `Lead Sources` | Available lead sources | `web,referral,event` |
|
||||
| `Admin Email` | Notifications email | `sales@company.com` |
|
||||
|
||||
---
|
||||
|
||||
## Scheduled Jobs
|
||||
|
||||
| Job | Schedule | Description |
|
||||
|-----|----------|-------------|
|
||||
| Lead nurturing | Daily | Send nurture emails to cold/warm leads |
|
||||
| Follow-up reminders | Hourly | Alert reps of overdue follow-ups |
|
||||
| Pipeline cleanup | Weekly | Archive stale opportunities |
|
||||
| Forecast update | Daily | Recalculate sales forecast |
|
||||
| Activity sync | Real-time | Sync emails and calendar events |
|
||||
|
||||
---
|
||||
|
||||
## Email Integration
|
||||
|
||||
### Receiving Emails
|
||||
|
||||
```basic
|
||||
' on-receive-email.bas
|
||||
email_from = GET "email.from"
|
||||
email_subject = GET "email.subject"
|
||||
email_body = GET "email.body"
|
||||
|
||||
' Check if from existing contact
|
||||
contact = FIND "contacts.csv", "email = '" + email_from + "'"
|
||||
|
||||
IF contact THEN
|
||||
' Log activity against contact
|
||||
WITH activity
|
||||
type = "email"
|
||||
subject = email_subject
|
||||
contact_id = contact.id
|
||||
END WITH
|
||||
SAVE "activities.csv", activity
|
||||
ELSE
|
||||
' Create new lead from email
|
||||
CALL "create-lead-from-draft.bas"
|
||||
END IF
|
||||
```
|
||||
|
||||
### Sending Proposals
|
||||
|
||||
```basic
|
||||
' send-proposal.bas
|
||||
proposal = GENERATE FROM TEMPLATE "proposal_template.docx" WITH {
|
||||
"company": account.name,
|
||||
"contact": contact.name,
|
||||
"products": opportunity_products,
|
||||
"total": quote.total,
|
||||
"valid_until": quote.valid_until
|
||||
}
|
||||
|
||||
SEND EMAIL contact.email, "Proposal: " + opportunity.name,
|
||||
"Please find attached our proposal.", ATTACHMENT proposal
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## AI Features
|
||||
|
||||
### Customer Sentiment Analysis
|
||||
|
||||
```basic
|
||||
' analyze-customer-sentiment.bas
|
||||
SET CONTEXT "Analyze customer communication for sentiment and buying signals."
|
||||
|
||||
communications = FIND "activities.csv", "contact_id = '" + contact_id + "'"
|
||||
|
||||
analysis = LLM "Analyze these customer communications and provide:
|
||||
1. Overall sentiment (positive, neutral, negative)
|
||||
2. Buying signals detected
|
||||
3. Concerns or objections
|
||||
4. Recommended next action
|
||||
|
||||
Communications: " + JSON(communications)
|
||||
|
||||
TALK analysis
|
||||
```
|
||||
|
||||
### Data Enrichment
|
||||
|
||||
```basic
|
||||
' data-enrichment.bas
|
||||
' Enrich lead with external data
|
||||
company_info = GET "https://api.enrichment.com/company/" + lead.company
|
||||
|
||||
IF company_info THEN
|
||||
lead.industry = company_info.industry
|
||||
lead.employee_count = company_info.employees
|
||||
lead.revenue_range = company_info.revenue
|
||||
lead.linkedin_url = company_info.linkedin
|
||||
|
||||
UPDATE "leads.csv", lead
|
||||
END IF
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Qualify early** - Use BANT scoring to prioritize leads
|
||||
2. **Track everything** - Log all customer interactions
|
||||
3. **Follow up promptly** - Hot leads within hours, warm within 24h
|
||||
4. **Use automation** - Let nurture campaigns work cold leads
|
||||
5. **Clean pipeline** - Archive stale opportunities regularly
|
||||
6. **Forecast accurately** - Keep close dates and probabilities updated
|
||||
7. **Segment leads** - Use tags and sources for better targeting
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Issue | Cause | Solution |
|
||||
|-------|-------|----------|
|
||||
| Lead not found | Search criteria too strict | Use partial match |
|
||||
| Stage not updating | Missing opportunity ID | Set opportunity in session |
|
||||
| Quote not generating | Missing products | Add products to opportunity first |
|
||||
| Email not sending | Missing contact email | Verify contact record |
|
||||
| Forecast incorrect | Stale data | Update opportunity amounts |
|
||||
|
||||
---
|
||||
|
||||
## Use Cases
|
||||
|
||||
- **Inside Sales** - Lead qualification and opportunity management
|
||||
- **Field Sales** - Account management and activity tracking
|
||||
- **Sales Management** - Pipeline visibility and forecasting
|
||||
- **Business Development** - Lead generation and nurturing
|
||||
- **Customer Success** - Account health and expansion opportunities
|
||||
|
||||
---
|
||||
|
||||
## Integration Points
|
||||
|
||||
- **Email** - Inbound/outbound email tracking
|
||||
- **Calendar** - Meeting scheduling
|
||||
- **ERP** - Order and billing sync
|
||||
- **Marketing Automation** - Lead handoff
|
||||
- **Support Ticketing** - Case management
|
||||
|
||||
---
|
||||
|
||||
## Related Templates
|
||||
|
||||
- [Contacts](./template-crm-contacts.md) - Contact directory management
|
||||
- [Marketing](./template-marketing.md) - Marketing automation and campaigns
|
||||
- [Analytics](./template-analytics.md) - Sales analytics and reporting
|
||||
- [Reminder](./template-reminder.md) - Follow-up reminders
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
- [Templates Reference](./templates.md) - Full template list
|
||||
- [Template Samples](./template-samples.md) - Example conversations
|
||||
- [gbdialog Reference](../chapter-06-gbdialog/README.md) - BASIC scripting guide
|
||||
352
docs/src/chapter-02/template-law.md
Normal file
352
docs/src/chapter-02/template-law.md
Normal file
|
|
@ -0,0 +1,352 @@
|
|||
# Legal Document Processing Template (law.gbai)
|
||||
|
||||
A General Bots template for legal case management, document analysis, and AI-powered legal Q&A.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
The Law template enables legal professionals to load case documents, query case information using natural language, and get AI-assisted analysis of legal materials. It's designed for law firms, legal departments, and compliance teams who need efficient document-based legal research.
|
||||
|
||||
## Features
|
||||
|
||||
- **Case Document Loading** - Load and index PDF case files by case number
|
||||
- **Document Q&A** - Ask questions about loaded legal documents
|
||||
- **Context-Aware Responses** - AI responses grounded in actual case content
|
||||
- **Case Summarization** - Generate summaries of case documents
|
||||
- **Multi-Document Support** - Work with multiple cases simultaneously
|
||||
- **Audit Trail** - Track all document access and queries
|
||||
|
||||
---
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
law.gbai/
|
||||
├── law.gbdialog/
|
||||
│ └── case.bas # Case loading and query handler
|
||||
├── law.gbdrive/ # Case document storage
|
||||
│ └── (case-*.pdf) # Case PDF files
|
||||
├── law.gbkb/ # Knowledge base for legal reference
|
||||
└── law.gbot/
|
||||
└── config.csv # Bot configuration
|
||||
```
|
||||
|
||||
## Scripts
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `case.bas` | Loads case documents by number and enables document-based Q&A |
|
||||
|
||||
---
|
||||
|
||||
## How It Works
|
||||
|
||||
### Case Loading Flow
|
||||
|
||||
1. User provides a case number (e.g., "12345")
|
||||
2. Bot searches for `case-12345.pdf` in the drive
|
||||
3. Document content is extracted and set as context
|
||||
4. Answer mode switches to "document" for grounded responses
|
||||
5. User can ask questions about the loaded case
|
||||
|
||||
### Code Example
|
||||
|
||||
```basic
|
||||
PARAM cod AS STRING LIKE "12345" DESCRIPTION "Case number to load and query"
|
||||
|
||||
DESCRIPTION "Load a legal case document by case number for Q&A and analysis"
|
||||
|
||||
text = GET "case-" + cod + ".pdf"
|
||||
|
||||
IF text THEN
|
||||
SET CONTEXT "Based on this document, answer the person's questions:\n\n" + text
|
||||
SET ANSWER MODE "document"
|
||||
TALK "Case ${cod} loaded. Ask me anything about the case or request a summary."
|
||||
ELSE
|
||||
TALK "Case not found. Please check the case number."
|
||||
END IF
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
Configure in `law.gbot/config.csv`:
|
||||
|
||||
| Parameter | Description | Example |
|
||||
|-----------|-------------|---------|
|
||||
| `Answer Mode` | Response grounding mode | `document` |
|
||||
| `Theme Color` | UI accent color | `navy` |
|
||||
| `LLM Provider` | AI provider | `openai` |
|
||||
| `Document Retention` | Days to keep loaded docs | `30` |
|
||||
| `Require Authentication` | Require user login | `true` |
|
||||
|
||||
---
|
||||
|
||||
## Sample Conversation
|
||||
|
||||
```
|
||||
User: Load case 12345
|
||||
|
||||
Bot: Case 12345 loaded. Ask me anything about the case
|
||||
or request a summary.
|
||||
|
||||
User: What are the main claims in this case?
|
||||
|
||||
Bot: Based on the document, the main claims are:
|
||||
|
||||
1. Breach of contract regarding the delivery terms
|
||||
in Section 3.2
|
||||
2. Failure to meet quality standards as specified
|
||||
in Exhibit A
|
||||
3. Request for damages in the amount of $250,000
|
||||
|
||||
📄 Source: Case 12345, Pages 3-5
|
||||
|
||||
User: Summarize the defendant's response
|
||||
|
||||
Bot: The defendant argues that:
|
||||
|
||||
• Delivery delays were caused by force majeure events
|
||||
(documented in Exhibit C)
|
||||
• Quality standards were met according to third-party
|
||||
inspection report
|
||||
• Damages claimed are excessive and not substantiated
|
||||
by evidence
|
||||
|
||||
📄 Source: Case 12345, Pages 12-18
|
||||
|
||||
User: What are the key dates mentioned?
|
||||
|
||||
Bot: Key dates from the case file:
|
||||
|
||||
📅 Contract signed: January 15, 2024
|
||||
📅 Delivery due date: March 30, 2024
|
||||
📅 Actual delivery: April 22, 2024
|
||||
📅 Complaint filed: May 10, 2024
|
||||
📅 Response deadline: June 15, 2024
|
||||
|
||||
📄 Source: Case 12345, Pages 1-2
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Document Naming Convention
|
||||
|
||||
Case documents should follow this naming pattern:
|
||||
|
||||
```
|
||||
case-{case_number}.pdf
|
||||
```
|
||||
|
||||
Examples:
|
||||
- `case-12345.pdf`
|
||||
- `case-2024-CV-0001.pdf`
|
||||
- `case-APPEAL-789.pdf`
|
||||
|
||||
---
|
||||
|
||||
## Customization
|
||||
|
||||
### Adding Case Search
|
||||
|
||||
```basic
|
||||
' search-cases.bas
|
||||
PARAM query AS STRING DESCRIPTION "Search term for finding cases"
|
||||
|
||||
DESCRIPTION "Search for cases by party name, date, or keywords"
|
||||
|
||||
cases = FIND "case_index.csv", "content LIKE '%" + query + "%'"
|
||||
|
||||
IF UBOUND(cases) > 0 THEN
|
||||
TALK "Found " + UBOUND(cases) + " matching cases:"
|
||||
|
||||
FOR EACH c IN cases
|
||||
TALK "- Case " + c.case_number + ": " + c.title
|
||||
NEXT
|
||||
ELSE
|
||||
TALK "No cases found matching: " + query
|
||||
END IF
|
||||
```
|
||||
|
||||
### Case Summarization
|
||||
|
||||
```basic
|
||||
' summarize-case.bas
|
||||
PARAM cod AS STRING DESCRIPTION "Case number to summarize"
|
||||
|
||||
DESCRIPTION "Generate an executive summary of a legal case"
|
||||
|
||||
text = GET "case-" + cod + ".pdf"
|
||||
|
||||
IF text THEN
|
||||
summary = LLM "As a legal professional, provide an executive summary of this case including:
|
||||
1. Parties involved
|
||||
2. Key facts
|
||||
3. Legal issues
|
||||
4. Current status
|
||||
5. Next steps
|
||||
|
||||
Document: " + text
|
||||
|
||||
TALK "## Case " + cod + " Summary\n\n" + summary
|
||||
|
||||
' Save summary for future reference
|
||||
SAVE "case_summaries.csv", cod, summary, NOW()
|
||||
ELSE
|
||||
TALK "Case not found."
|
||||
END IF
|
||||
```
|
||||
|
||||
### Supporting Multiple Document Types
|
||||
|
||||
```basic
|
||||
' load-document.bas
|
||||
PARAM doc_type AS STRING LIKE "contract" DESCRIPTION "Type: case, contract, brief, motion"
|
||||
PARAM doc_id AS STRING DESCRIPTION "Document identifier"
|
||||
|
||||
DESCRIPTION "Load various legal document types"
|
||||
|
||||
filename = doc_type + "-" + doc_id + ".pdf"
|
||||
text = GET filename
|
||||
|
||||
IF text THEN
|
||||
SET CONTEXT "This is a legal " + doc_type + ". Answer questions based on its content:\n\n" + text
|
||||
SET ANSWER MODE "document"
|
||||
TALK "Loaded " + doc_type + " " + doc_id + ". Ready for questions."
|
||||
ELSE
|
||||
TALK "Document not found: " + filename
|
||||
END IF
|
||||
```
|
||||
|
||||
### Compliance Logging
|
||||
|
||||
```basic
|
||||
' Add audit logging to case.bas
|
||||
IF text THEN
|
||||
' Log access for compliance
|
||||
WITH audit_entry
|
||||
timestamp = NOW()
|
||||
user = GET SESSION "user_email"
|
||||
case_number = cod
|
||||
action = "document_access"
|
||||
ip_address = GET SESSION "client_ip"
|
||||
END WITH
|
||||
|
||||
SAVE "legal_audit_log.csv", audit_entry
|
||||
|
||||
SET CONTEXT "Based on this document..." + text
|
||||
END IF
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Integration Examples
|
||||
|
||||
### With Calendar
|
||||
|
||||
```basic
|
||||
' Schedule case deadlines
|
||||
deadline = LLM "Extract the next deadline date from this case: " + text
|
||||
|
||||
IF deadline THEN
|
||||
CREATE CALENDAR EVENT "Case " + cod + " Deadline", deadline
|
||||
TALK "Deadline added to calendar: " + deadline
|
||||
END IF
|
||||
```
|
||||
|
||||
### With Email
|
||||
|
||||
```basic
|
||||
' Email case summary to team
|
||||
summary = LLM "Summarize the key points of this case in 3 paragraphs: " + text
|
||||
|
||||
SEND EMAIL "legal-team@firm.com", "Case " + cod + " Summary", summary
|
||||
TALK "Summary sent to legal team."
|
||||
```
|
||||
|
||||
### With Document Generation
|
||||
|
||||
```basic
|
||||
' Generate response document
|
||||
response = LLM "Draft a formal response letter addressing the claims in this case: " + text
|
||||
|
||||
CREATE DRAFT response, "Response to Case " + cod
|
||||
TALK "Draft response created. Review in your documents."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Security Considerations
|
||||
|
||||
1. **Access Control** - Implement role-based access for sensitive cases
|
||||
2. **Audit Logging** - Log all document access for compliance
|
||||
3. **Data Encryption** - Enable encryption for stored documents
|
||||
4. **Session Timeout** - Configure appropriate session timeouts
|
||||
5. **Authentication** - Require strong authentication for legal systems
|
||||
6. **Data Retention** - Follow legal data retention requirements
|
||||
|
||||
---
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Organize documents** - Use consistent naming conventions
|
||||
2. **Index cases** - Maintain a searchable case index
|
||||
3. **Regular backups** - Back up case documents frequently
|
||||
4. **Version control** - Track document versions
|
||||
5. **Clear context** - Clear previous case context before loading new cases
|
||||
6. **Verify AI responses** - Always verify AI-generated legal content
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Issue | Cause | Solution |
|
||||
|-------|-------|----------|
|
||||
| Case not found | Wrong filename | Check naming convention |
|
||||
| Empty responses | Document not parsed | Verify PDF is text-based |
|
||||
| Slow loading | Large document | Consider document chunking |
|
||||
| Context errors | Multiple cases loaded | Clear context between cases |
|
||||
| Access denied | Missing permissions | Check user authentication |
|
||||
|
||||
---
|
||||
|
||||
## Limitations
|
||||
|
||||
- PDF documents must be text-based (not scanned images)
|
||||
- Very large documents may require chunking
|
||||
- Complex legal analysis should be verified by professionals
|
||||
- AI responses are assistive, not legal advice
|
||||
|
||||
---
|
||||
|
||||
## Use Cases
|
||||
|
||||
- **Case Research** - Quickly find relevant information in case files
|
||||
- **Document Review** - AI-assisted document analysis
|
||||
- **Client Communication** - Generate case status summaries
|
||||
- **Deadline Tracking** - Extract and track important dates
|
||||
- **Knowledge Management** - Build searchable legal knowledge bases
|
||||
|
||||
---
|
||||
|
||||
## Disclaimer
|
||||
|
||||
This template provides AI-assisted document analysis tools. It does not constitute legal advice. All AI-generated content should be reviewed by qualified legal professionals. Users are responsible for ensuring compliance with applicable legal and ethical standards.
|
||||
|
||||
---
|
||||
|
||||
## Related Templates
|
||||
|
||||
- [HIPAA Medical](./template-hipaa.md) - Healthcare compliance
|
||||
- [Talk to Data](./template-talk-to-data.md) - Natural language document queries
|
||||
- [AI Search](./template-ai-search.md) - AI-powered document search
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
- [Templates Reference](./templates.md) - Full template list
|
||||
- [Template Samples](./template-samples.md) - Example conversations
|
||||
- [gbkb Reference](../chapter-03/README.md) - Knowledge base guide
|
||||
423
docs/src/chapter-02/template-llm-server.md
Normal file
423
docs/src/chapter-02/template-llm-server.md
Normal file
|
|
@ -0,0 +1,423 @@
|
|||
# LLM Server Template (llm-server.gbai)
|
||||
|
||||
A General Bots template for deploying LLM-powered web services that process orders and requests via API endpoints.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
The LLM Server template transforms General Bots into a headless API service that processes structured requests using LLM intelligence. It's designed for integrating AI-powered order processing, chatbot backends, and automated response systems into existing applications.
|
||||
|
||||
## Features
|
||||
|
||||
- **REST API Endpoints** - HTTP endpoints for bot interaction
|
||||
- **Order Processing** - Structured JSON responses for orders
|
||||
- **Product Catalog Integration** - Dynamic product menu from CSV
|
||||
- **System Prompt Configuration** - Customizable AI behavior
|
||||
- **Session Management** - Track conversations across requests
|
||||
- **Operator Support** - Multi-operator/tenant architecture
|
||||
|
||||
---
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
llm-server.gbai/
|
||||
├── llm-server.gbdata/ # Data files
|
||||
│ └── products.csv # Product catalog
|
||||
├── llm-server.gbdialog/
|
||||
│ └── start.bas # Main dialog with system prompt
|
||||
├── llm-server.gbkb/ # Knowledge base
|
||||
└── llm-server.gbot/
|
||||
└── config.csv # Bot configuration
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### Start a Session
|
||||
|
||||
```http
|
||||
POST https://{host}/{botId}/dialogs/start
|
||||
Content-Type: application/x-www-form-urlencoded
|
||||
|
||||
operator=123
|
||||
userSystemId=999
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"pid": "1237189231897",
|
||||
"conversationId": "abc123",
|
||||
"status": "started"
|
||||
}
|
||||
```
|
||||
|
||||
### Send a Message
|
||||
|
||||
```http
|
||||
POST https://{host}/api/dk/messageBot
|
||||
Content-Type: application/x-www-form-urlencoded
|
||||
|
||||
pid=1237189231897
|
||||
text=I want a banana
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"orderedItems": [
|
||||
{
|
||||
"item": {
|
||||
"id": 102,
|
||||
"price": 0.30,
|
||||
"name": "Banana",
|
||||
"quantity": 1,
|
||||
"notes": ""
|
||||
}
|
||||
}
|
||||
],
|
||||
"userId": "123",
|
||||
"accountIdentifier": "TableA",
|
||||
"deliveryTypeId": 2
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
### System Prompt
|
||||
|
||||
The `start.bas` defines the AI behavior:
|
||||
|
||||
```basic
|
||||
PARAM operator AS number LIKE 12312312 DESCRIPTION "Operator code."
|
||||
DESCRIPTION It is a WebService of GB.
|
||||
|
||||
products = FIND "products.csv"
|
||||
|
||||
BEGIN SYSTEM PROMPT
|
||||
|
||||
You are a chatbot assisting a store attendant in processing orders. Follow these rules:
|
||||
|
||||
1. **Order Format**: Each order must include the product name, the table number, and the customer's name.
|
||||
|
||||
2. **Product Details**: The available products are:
|
||||
|
||||
${TOYAML(products)}
|
||||
|
||||
3. **JSON Response**: For each order, return a valid RFC 8259 JSON object containing:
|
||||
- product name
|
||||
- table number
|
||||
|
||||
4. **Guidelines**:
|
||||
- Do **not** engage in conversation.
|
||||
- Return the response in plain text JSON format only.
|
||||
|
||||
END SYSTEM PROMPT
|
||||
```
|
||||
|
||||
### Product Catalog
|
||||
|
||||
Create `products.csv` in the `llm-server.gbdata` folder:
|
||||
|
||||
```csv
|
||||
id,name,price,category,description
|
||||
101,Apple,0.50,Fruit,Fresh red apple
|
||||
102,Banana,0.30,Fruit,Ripe yellow banana
|
||||
103,Orange,0.40,Fruit,Juicy orange
|
||||
201,Milk,1.20,Dairy,1 liter whole milk
|
||||
202,Cheese,2.50,Dairy,200g cheddar
|
||||
```
|
||||
|
||||
### Bot Configuration
|
||||
|
||||
Configure in `llm-server.gbot/config.csv`:
|
||||
|
||||
| Parameter | Description | Example |
|
||||
|-----------|-------------|---------|
|
||||
| `LLM Provider` | AI model provider | `openai` |
|
||||
| `LLM Model` | Specific model | `gpt-4` |
|
||||
| `Max Tokens` | Response length limit | `500` |
|
||||
| `Temperature` | Response creativity | `0.3` |
|
||||
| `API Mode` | Enable API mode | `true` |
|
||||
|
||||
---
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### cURL Examples
|
||||
|
||||
**Start Session:**
|
||||
```bash
|
||||
curl -X POST https://api.example.com/llmservergbot/dialogs/start \
|
||||
-d "operator=123" \
|
||||
-d "userSystemId=999"
|
||||
```
|
||||
|
||||
**Send Order:**
|
||||
```bash
|
||||
curl -X POST https://api.example.com/api/dk/messageBot \
|
||||
-d "pid=1237189231897" \
|
||||
-d "text=I need 2 apples and 1 milk"
|
||||
```
|
||||
|
||||
### JavaScript Integration
|
||||
|
||||
```javascript
|
||||
async function startBotSession(operator, userId) {
|
||||
const response = await fetch('https://api.example.com/llmservergbot/dialogs/start', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({ operator, userSystemId: userId })
|
||||
});
|
||||
return response.json();
|
||||
}
|
||||
|
||||
async function sendMessage(pid, text) {
|
||||
const response = await fetch('https://api.example.com/api/dk/messageBot', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({ pid, text })
|
||||
});
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// Usage
|
||||
const session = await startBotSession('123', '999');
|
||||
const order = await sendMessage(session.pid, 'I want a banana');
|
||||
console.log(order.orderedItems);
|
||||
```
|
||||
|
||||
### Python Integration
|
||||
|
||||
```python
|
||||
import requests
|
||||
|
||||
class LLMServerClient:
|
||||
def __init__(self, base_url, operator):
|
||||
self.base_url = base_url
|
||||
self.operator = operator
|
||||
self.pid = None
|
||||
|
||||
def start_session(self, user_id):
|
||||
response = requests.post(
|
||||
f"{self.base_url}/llmservergbot/dialogs/start",
|
||||
data={"operator": self.operator, "userSystemId": user_id}
|
||||
)
|
||||
self.pid = response.json()["pid"]
|
||||
return self.pid
|
||||
|
||||
def send_message(self, text):
|
||||
response = requests.post(
|
||||
f"{self.base_url}/api/dk/messageBot",
|
||||
data={"pid": self.pid, "text": text}
|
||||
)
|
||||
return response.json()
|
||||
|
||||
# Usage
|
||||
client = LLMServerClient("https://api.example.com", "123")
|
||||
client.start_session("999")
|
||||
order = client.send_message("I need 2 bananas")
|
||||
print(order)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Response Format
|
||||
|
||||
### Order Response Structure
|
||||
|
||||
```json
|
||||
{
|
||||
"orderedItems": [
|
||||
{
|
||||
"item": {
|
||||
"id": 102,
|
||||
"price": 0.30,
|
||||
"name": "Banana",
|
||||
"sideItems": [],
|
||||
"quantity": 2,
|
||||
"notes": "ripe ones please"
|
||||
}
|
||||
}
|
||||
],
|
||||
"userId": "123",
|
||||
"accountIdentifier": "Table5",
|
||||
"deliveryTypeId": 2
|
||||
}
|
||||
```
|
||||
|
||||
### Field Descriptions
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `orderedItems` | Array | List of ordered items |
|
||||
| `item.id` | Number | Product ID from catalog |
|
||||
| `item.price` | Number | Unit price |
|
||||
| `item.name` | String | Product name |
|
||||
| `item.sideItems` | Array | Additional items |
|
||||
| `item.quantity` | Number | Order quantity |
|
||||
| `item.notes` | String | Special instructions |
|
||||
| `userId` | String | Operator identifier |
|
||||
| `accountIdentifier` | String | Table/customer identifier |
|
||||
| `deliveryTypeId` | Number | Delivery method |
|
||||
|
||||
---
|
||||
|
||||
## Customization
|
||||
|
||||
### Custom Response Format
|
||||
|
||||
Modify the system prompt for different output structures:
|
||||
|
||||
```basic
|
||||
BEGIN SYSTEM PROMPT
|
||||
Return responses as JSON with this structure:
|
||||
{
|
||||
"intent": "order|question|complaint",
|
||||
"entities": [...extracted entities...],
|
||||
"response": "...",
|
||||
"confidence": 0.0-1.0
|
||||
}
|
||||
END SYSTEM PROMPT
|
||||
```
|
||||
|
||||
### Adding Validation
|
||||
|
||||
```basic
|
||||
' Validate order before returning
|
||||
order = LLM_RESPONSE
|
||||
|
||||
IF NOT order.orderedItems THEN
|
||||
RETURN {"error": "No items in order", "suggestion": "Please specify products"}
|
||||
END IF
|
||||
|
||||
FOR EACH item IN order.orderedItems
|
||||
product = FIND "products.csv", "id = " + item.item.id
|
||||
IF NOT product THEN
|
||||
RETURN {"error": "Invalid product ID: " + item.item.id}
|
||||
END IF
|
||||
NEXT
|
||||
|
||||
RETURN order
|
||||
```
|
||||
|
||||
### Multi-Language Support
|
||||
|
||||
```basic
|
||||
PARAM language AS STRING LIKE "en" DESCRIPTION "Response language"
|
||||
|
||||
BEGIN SYSTEM PROMPT
|
||||
Respond in ${language} language.
|
||||
Available products: ${TOYAML(products)}
|
||||
Return JSON format only.
|
||||
END SYSTEM PROMPT
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Error Handling
|
||||
|
||||
### Common Error Responses
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "session_expired",
|
||||
"message": "Please start a new session",
|
||||
"code": 401
|
||||
}
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "invalid_request",
|
||||
"message": "Missing required parameter: text",
|
||||
"code": 400
|
||||
}
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "product_not_found",
|
||||
"message": "Product 'pizza' is not in our catalog",
|
||||
"code": 404
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Keep prompts focused** - Single-purpose system prompts work better
|
||||
2. **Validate responses** - Always validate LLM output before returning
|
||||
3. **Handle edge cases** - Plan for invalid products, empty orders
|
||||
4. **Monitor usage** - Track API calls and response times
|
||||
5. **Rate limiting** - Implement rate limits for production
|
||||
6. **Secure endpoints** - Use authentication for production APIs
|
||||
7. **Log requests** - Maintain audit logs for debugging
|
||||
|
||||
---
|
||||
|
||||
## Deployment
|
||||
|
||||
### Environment Variables
|
||||
|
||||
```bash
|
||||
LLM_PROVIDER=openai
|
||||
LLM_API_KEY=sk-...
|
||||
LLM_MODEL=gpt-4
|
||||
API_RATE_LIMIT=100
|
||||
SESSION_TIMEOUT=3600
|
||||
```
|
||||
|
||||
### Docker Deployment
|
||||
|
||||
```dockerfile
|
||||
FROM generalbots/server:latest
|
||||
COPY llm-server.gbai /app/packages/
|
||||
ENV API_MODE=true
|
||||
EXPOSE 4242
|
||||
CMD ["npm", "start"]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Issue | Cause | Solution |
|
||||
|-------|-------|----------|
|
||||
| Empty responses | System prompt too restrictive | Adjust prompt guidelines |
|
||||
| Invalid JSON | LLM hallucination | Add JSON validation examples |
|
||||
| Session expired | Timeout reached | Implement session refresh |
|
||||
| Wrong products | Catalog not loaded | Verify products.csv path |
|
||||
| Slow responses | Large catalog | Optimize product filtering |
|
||||
|
||||
---
|
||||
|
||||
## Use Cases
|
||||
|
||||
- **Restaurant Ordering** - Process food orders via API
|
||||
- **Retail POS Integration** - AI-powered point of sale
|
||||
- **Chatbot Backend** - Headless chatbot for web/mobile apps
|
||||
- **Voice Assistant Backend** - Process voice-to-text commands
|
||||
- **Order Automation** - Automate order entry from various sources
|
||||
|
||||
---
|
||||
|
||||
## Related Templates
|
||||
|
||||
- [LLM Tools](./template-llm-tools.md) - LLM with tool/function calling
|
||||
- [Store](./template-store.md) - Full e-commerce with order processing
|
||||
- [API Client](./template-api-client.md) - API integration examples
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
- [Templates Reference](./templates.md) - Full template list
|
||||
- [Template Samples](./template-samples.md) - Example conversations
|
||||
- [gbdialog Reference](../chapter-06-gbdialog/README.md) - BASIC scripting guide
|
||||
450
docs/src/chapter-02/template-llm-tools.md
Normal file
450
docs/src/chapter-02/template-llm-tools.md
Normal file
|
|
@ -0,0 +1,450 @@
|
|||
# LLM Tools Template (llm-tools.gbai)
|
||||
|
||||
A General Bots template demonstrating how to create and register custom tools (functions) that LLMs can call during conversations.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
The LLM Tools template shows how to extend your bot's capabilities by creating tools that the AI can invoke automatically. Tools enable the LLM to perform actions like database lookups, API calls, calculations, and more—all triggered naturally through conversation.
|
||||
|
||||
## Features
|
||||
|
||||
- **Custom Tool Registration** - Define tools the LLM can call
|
||||
- **Parameter Validation** - Type-safe tool parameters with descriptions
|
||||
- **Knowledge Base Integration** - Combine tools with RAG
|
||||
- **Natural Interaction** - Users don't need to know tool names
|
||||
- **Extensible Architecture** - Easy to add new tools
|
||||
|
||||
---
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
llm-tools.gbai/
|
||||
├── llm-tools.gbdata/ # Data files for tools
|
||||
│ └── products.csv # Product catalog
|
||||
├── llm-tools.gbdialog/
|
||||
│ ├── start.bas # Main dialog with tool registration
|
||||
│ └── get-price.bas # Example tool implementation
|
||||
├── llm-tools.gbkb/ # Knowledge base
|
||||
│ └── products.gbkb/ # Product documentation
|
||||
└── llm-tools.gbot/
|
||||
└── config.csv # Bot configuration
|
||||
```
|
||||
|
||||
## Scripts
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `start.bas` | Registers tools, configures context, and sets system prompt |
|
||||
| `get-price.bas` | Example tool that looks up product prices |
|
||||
|
||||
---
|
||||
|
||||
## How Tools Work
|
||||
|
||||
### 1. Tool Registration
|
||||
|
||||
In `start.bas`, tools are registered with `ADD TOOL`:
|
||||
|
||||
```basic
|
||||
ADD TOOL "get-price"
|
||||
|
||||
USE KB "products.gbkb"
|
||||
|
||||
CLEAR SUGGESTIONS
|
||||
|
||||
ADD SUGGESTION "price" AS "Check product price"
|
||||
ADD SUGGESTION "products" AS "View products"
|
||||
ADD SUGGESTION "help" AS "How to use"
|
||||
|
||||
BEGIN TALK
|
||||
**Product Assistant**
|
||||
|
||||
I can help you check product prices and information.
|
||||
|
||||
Just ask me about any product and I'll look it up for you.
|
||||
END TALK
|
||||
|
||||
BEGIN SYSTEM PROMPT
|
||||
You are a product assistant with access to internal tools.
|
||||
|
||||
When get-price returns -1, the product does not exist.
|
||||
When asked about a price, use the get-price tool and return the result.
|
||||
|
||||
Do not expose tool names to users - just act on their requests naturally.
|
||||
END SYSTEM PROMPT
|
||||
```
|
||||
|
||||
### 2. Tool Implementation
|
||||
|
||||
Each tool is a separate `.bas` file with `PARAM` and `DESCRIPTION`:
|
||||
|
||||
```basic
|
||||
PARAM product AS STRING LIKE "fax" DESCRIPTION "Name of the product to get price for"
|
||||
|
||||
DESCRIPTION "Get the price of a product by name from the product catalog"
|
||||
|
||||
productRecord = FIND "products.csv", "name = ${product}"
|
||||
|
||||
IF productRecord THEN
|
||||
RETURN productRecord.price
|
||||
ELSE
|
||||
RETURN -1
|
||||
END IF
|
||||
```
|
||||
|
||||
### 3. LLM Invocation
|
||||
|
||||
When a user asks "How much is the fax machine?", the LLM:
|
||||
1. Recognizes this requires price information
|
||||
2. Calls `get-price` with `product="fax"`
|
||||
3. Receives the price (or -1 if not found)
|
||||
4. Formulates a natural response
|
||||
|
||||
---
|
||||
|
||||
## Sample Conversation
|
||||
|
||||
```
|
||||
User: How much does the wireless mouse cost?
|
||||
|
||||
Bot: [Calls get-price with product="wireless mouse"]
|
||||
The wireless mouse is $29.99.
|
||||
|
||||
User: What about the keyboard?
|
||||
|
||||
Bot: [Calls get-price with product="keyboard"]
|
||||
The standard keyboard is $49.99. We also have a
|
||||
mechanical keyboard for $89.99.
|
||||
|
||||
User: Is the laptop in stock and what's the price?
|
||||
|
||||
Bot: [Calls get-price with product="laptop"]
|
||||
[Calls check-inventory with sku="LAPTOP-001"]
|
||||
The laptop is $999. Good news - we have 12 units
|
||||
available in our main warehouse!
|
||||
|
||||
User: I want 3 monitors with my 20% employee discount
|
||||
|
||||
Bot: [Calls get-price with product="monitor"]
|
||||
[Calls calculate-discount with price=299, percent=20]
|
||||
Each monitor is $299, but with your 20% employee
|
||||
discount, you'll pay $239.20 each.
|
||||
For 3 monitors: $717.60 (saving $179.40)!
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Creating Custom Tools
|
||||
|
||||
### Tool Anatomy
|
||||
|
||||
Every tool needs:
|
||||
- **PARAM declarations** - Input parameters with types and examples
|
||||
- **DESCRIPTION** - What the tool does (for LLM understanding)
|
||||
- **Implementation** - The actual logic
|
||||
- **RETURN** - The output value
|
||||
|
||||
### Parameter Types
|
||||
|
||||
| Type | Description | Example |
|
||||
|------|-------------|---------|
|
||||
| `STRING` | Text input | `PARAM name AS STRING LIKE "John"` |
|
||||
| `NUMBER` | Numeric input | `PARAM quantity AS NUMBER LIKE 5` |
|
||||
| `INTEGER` | Whole numbers | `PARAM count AS INTEGER LIKE 10` |
|
||||
| `BOOLEAN` | True/false | `PARAM active AS BOOLEAN` |
|
||||
| `DATE` | Date values | `PARAM start AS DATE LIKE "2024-01-15"` |
|
||||
| `EMAIL` | Email addresses | `PARAM email AS EMAIL` |
|
||||
| `PHONE` | Phone numbers | `PARAM phone AS PHONE` |
|
||||
| `OBJECT` | JSON objects | `PARAM data AS OBJECT` |
|
||||
|
||||
---
|
||||
|
||||
## Example Tools
|
||||
|
||||
### Database Lookup Tool
|
||||
|
||||
```basic
|
||||
' lookup-customer.bas
|
||||
PARAM customer_id AS STRING LIKE "CUST-001" DESCRIPTION "Customer ID to look up"
|
||||
|
||||
DESCRIPTION "Retrieve customer information by ID"
|
||||
|
||||
customer = FIND "customers.csv", "id = ${customer_id}"
|
||||
|
||||
IF customer THEN
|
||||
WITH result
|
||||
name = customer.name
|
||||
email = customer.email
|
||||
status = customer.status
|
||||
since = customer.created_at
|
||||
END WITH
|
||||
RETURN result
|
||||
ELSE
|
||||
RETURN NULL
|
||||
END IF
|
||||
```
|
||||
|
||||
### Calculation Tool
|
||||
|
||||
```basic
|
||||
' calculate-discount.bas
|
||||
PARAM original_price AS NUMBER LIKE 100 DESCRIPTION "Original product price"
|
||||
PARAM discount_percent AS NUMBER LIKE 15 DESCRIPTION "Discount percentage"
|
||||
|
||||
DESCRIPTION "Calculate the final price after applying a discount"
|
||||
|
||||
discount_amount = original_price * (discount_percent / 100)
|
||||
final_price = original_price - discount_amount
|
||||
|
||||
WITH result
|
||||
original = original_price
|
||||
discount = discount_amount
|
||||
final = final_price
|
||||
savings = discount_percent + "% off"
|
||||
END WITH
|
||||
|
||||
RETURN result
|
||||
```
|
||||
|
||||
### API Integration Tool
|
||||
|
||||
```basic
|
||||
' check-inventory.bas
|
||||
PARAM sku AS STRING LIKE "SKU-12345" DESCRIPTION "Product SKU to check"
|
||||
PARAM warehouse AS STRING LIKE "main" DESCRIPTION "Warehouse location" OPTIONAL
|
||||
|
||||
DESCRIPTION "Check real-time inventory levels for a product"
|
||||
|
||||
IF NOT warehouse THEN
|
||||
warehouse = "main"
|
||||
END IF
|
||||
|
||||
SET HEADER "Authorization" AS "Bearer " + GET ENV "INVENTORY_API_KEY"
|
||||
response = GET "https://api.inventory.com/stock/" + sku + "?warehouse=" + warehouse
|
||||
|
||||
IF response.error THEN
|
||||
RETURN {"available": false, "error": response.error}
|
||||
END IF
|
||||
|
||||
WITH result
|
||||
sku = sku
|
||||
available = response.quantity > 0
|
||||
quantity = response.quantity
|
||||
warehouse = warehouse
|
||||
last_updated = response.timestamp
|
||||
END WITH
|
||||
|
||||
RETURN result
|
||||
```
|
||||
|
||||
### Email Sending Tool
|
||||
|
||||
```basic
|
||||
' send-notification.bas
|
||||
PARAM recipient AS EMAIL LIKE "user@example.com" DESCRIPTION "Email recipient"
|
||||
PARAM subject AS STRING LIKE "Order Confirmation" DESCRIPTION "Email subject"
|
||||
PARAM message AS STRING DESCRIPTION "Email body content"
|
||||
|
||||
DESCRIPTION "Send an email notification to a customer"
|
||||
|
||||
SEND EMAIL recipient, subject, message
|
||||
|
||||
WITH result
|
||||
sent = true
|
||||
recipient = recipient
|
||||
timestamp = NOW()
|
||||
END WITH
|
||||
|
||||
RETURN result
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Tool Registration Patterns
|
||||
|
||||
### Single Tool
|
||||
|
||||
```basic
|
||||
ADD TOOL "get-price"
|
||||
```
|
||||
|
||||
### Multiple Tools
|
||||
|
||||
```basic
|
||||
ADD TOOL "get-price"
|
||||
ADD TOOL "check-inventory"
|
||||
ADD TOOL "lookup-customer"
|
||||
ADD TOOL "calculate-discount"
|
||||
ADD TOOL "send-notification"
|
||||
```
|
||||
|
||||
### Conditional Tools
|
||||
|
||||
```basic
|
||||
user_role = GET SESSION "user_role"
|
||||
|
||||
ADD TOOL "get-price"
|
||||
ADD TOOL "check-inventory"
|
||||
|
||||
IF user_role = "admin" THEN
|
||||
ADD TOOL "update-price"
|
||||
ADD TOOL "delete-product"
|
||||
END IF
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## System Prompt Best Practices
|
||||
|
||||
Guide the LLM on when and how to use tools:
|
||||
|
||||
```basic
|
||||
BEGIN SYSTEM PROMPT
|
||||
You are a helpful product assistant with access to the following capabilities:
|
||||
|
||||
**Available Tools:**
|
||||
- get-price: Look up product prices by name
|
||||
- check-inventory: Check stock availability
|
||||
- calculate-discount: Calculate prices with discounts
|
||||
|
||||
**Guidelines:**
|
||||
1. When users ask about prices, use the get-price tool
|
||||
2. When asked about availability, use check-inventory
|
||||
3. If a tool returns an error, explain politely that the item wasn't found
|
||||
4. Never mention tool names to users - just provide the information naturally
|
||||
5. Combine multiple tool results when needed to answer complex questions
|
||||
|
||||
**Error Handling:**
|
||||
- If get-price returns -1, the product doesn't exist
|
||||
- If check-inventory shows quantity 0, inform the user it's out of stock
|
||||
END SYSTEM PROMPT
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
Configure in `llm-tools.gbot/config.csv`:
|
||||
|
||||
| Parameter | Description | Example |
|
||||
|-----------|-------------|---------|
|
||||
| `LLM Provider` | AI provider | `openai` |
|
||||
| `LLM Model` | Model for tool calls | `gpt-4` |
|
||||
| `Tool Timeout` | Max tool execution time | `30` |
|
||||
| `Max Tool Calls` | Limit per conversation | `10` |
|
||||
|
||||
---
|
||||
|
||||
## Error Handling
|
||||
|
||||
### In Tool Implementation
|
||||
|
||||
```basic
|
||||
' get-price.bas with error handling
|
||||
PARAM product AS STRING LIKE "laptop" DESCRIPTION "Product name"
|
||||
|
||||
DESCRIPTION "Get product price with error handling"
|
||||
|
||||
ON ERROR GOTO HandleError
|
||||
|
||||
productRecord = FIND "products.csv", "name LIKE '%" + product + "%'"
|
||||
|
||||
IF productRecord THEN
|
||||
RETURN productRecord.price
|
||||
ELSE
|
||||
RETURN {"error": "not_found", "message": "Product not in catalog"}
|
||||
END IF
|
||||
|
||||
HandleError:
|
||||
RETURN {"error": "system_error", "message": "Unable to look up price"}
|
||||
```
|
||||
|
||||
### In System Prompt
|
||||
|
||||
```basic
|
||||
BEGIN SYSTEM PROMPT
|
||||
When tools return errors:
|
||||
- "not_found": Apologize and suggest similar products
|
||||
- "out_of_stock": Offer to notify when back in stock
|
||||
- "system_error": Ask user to try again later
|
||||
END SYSTEM PROMPT
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Testing Tools
|
||||
|
||||
### Manual Testing
|
||||
|
||||
```basic
|
||||
' test-tools.bas
|
||||
result = CALL "get-price", {"product": "laptop"}
|
||||
TALK "Price result: " + JSON(result)
|
||||
|
||||
result = CALL "check-inventory", {"sku": "LAPTOP-001"}
|
||||
TALK "Inventory result: " + JSON(result)
|
||||
```
|
||||
|
||||
### Conversation Testing
|
||||
|
||||
Test various phrasings to ensure tool invocation:
|
||||
|
||||
- "What's the price of X?"
|
||||
- "How much does X cost?"
|
||||
- "Price for X please"
|
||||
- "X price?"
|
||||
- "Can you tell me what X costs?"
|
||||
|
||||
---
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Clear descriptions** - Help the LLM understand when to use each tool
|
||||
2. **Good examples** - LIKE clauses guide parameter format
|
||||
3. **Handle errors** - Always return meaningful error responses
|
||||
4. **Validate input** - Check parameters before processing
|
||||
5. **Log tool calls** - Track usage for debugging
|
||||
6. **Keep tools focused** - One tool, one purpose
|
||||
7. **Test thoroughly** - Various phrasings should trigger correct tools
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Issue | Cause | Solution |
|
||||
|-------|-------|----------|
|
||||
| Tool not called | Description unclear | Improve DESCRIPTION text |
|
||||
| Wrong parameters | Examples missing | Add LIKE examples |
|
||||
| Tool errors | Missing validation | Add error handling |
|
||||
| Slow responses | Complex tool logic | Optimize or cache |
|
||||
| Tool exposed to user | System prompt issue | Add "don't mention tools" |
|
||||
|
||||
---
|
||||
|
||||
## Use Cases
|
||||
|
||||
- **Product Lookup** - Price, availability, specifications
|
||||
- **Customer Service** - Order status, account info
|
||||
- **Calculations** - Quotes, discounts, shipping
|
||||
- **Integrations** - CRM, ERP, external APIs
|
||||
- **Data Access** - Database queries, report generation
|
||||
|
||||
---
|
||||
|
||||
## Related Templates
|
||||
|
||||
- [LLM Server](./template-llm-server.md) - Headless API with LLM processing
|
||||
- [CRM](./template-crm.md) - CRM with many tool examples
|
||||
- [Store](./template-store.md) - E-commerce with product tools
|
||||
- [Talk to Data](./template-talk-to-data.md) - Data query tools
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
- [Templates Reference](./templates.md) - Full template list
|
||||
- [Template Samples](./template-samples.md) - Example conversations
|
||||
- [gbdialog Reference](../chapter-06-gbdialog/README.md) - BASIC scripting guide
|
||||
446
docs/src/chapter-02/template-marketing.md
Normal file
446
docs/src/chapter-02/template-marketing.md
Normal file
|
|
@ -0,0 +1,446 @@
|
|||
# Marketing Automation Template (marketing.gbai)
|
||||
|
||||
A General Bots template for marketing campaign management, content creation, and multi-channel broadcast messaging.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
The Marketing template provides marketing automation capabilities including campaign management, content ideation, image generation, social media posting, and WhatsApp broadcast messaging. It enables marketing teams to create, schedule, and deliver campaigns through conversational AI.
|
||||
|
||||
## Features
|
||||
|
||||
- **Campaign Management** - Create and organize marketing campaigns
|
||||
- **Content Ideation** - AI-assisted content idea generation
|
||||
- **Image Generation** - AI-powered marketing visuals
|
||||
- **Social Media Posting** - Direct posting to Instagram and other platforms
|
||||
- **WhatsApp Broadcasts** - Mass messaging with template support
|
||||
- **Contact Segmentation** - Target specific audience segments
|
||||
- **Template Compliance** - META-approved template validation
|
||||
- **Broadcast Logging** - Track delivery and engagement
|
||||
|
||||
---
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
marketing.gbai/
|
||||
├── marketing.gbdialog/
|
||||
│ ├── add-new-idea.bas # Content ideation tool
|
||||
│ ├── broadcast.bas # WhatsApp broadcast messaging
|
||||
│ ├── get-image.bas # AI image generation
|
||||
│ ├── post-to-instagram.bas # Instagram posting
|
||||
│ ├── poster.bas # Marketing poster creation
|
||||
│ └── campaigns/ # Campaign templates
|
||||
└── marketing.gbot/
|
||||
└── config.csv # Bot configuration
|
||||
```
|
||||
|
||||
## Scripts
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `add-new-idea.bas` | Generate and save marketing content ideas |
|
||||
| `broadcast.bas` | Send WhatsApp broadcasts to contact lists |
|
||||
| `get-image.bas` | Generate marketing images with AI |
|
||||
| `post-to-instagram.bas` | Post content to Instagram |
|
||||
| `poster.bas` | Create marketing posters and visuals |
|
||||
|
||||
---
|
||||
|
||||
## WhatsApp Broadcast
|
||||
|
||||
The `broadcast.bas` script enables mass WhatsApp messaging with template support:
|
||||
|
||||
### Parameters
|
||||
|
||||
| Parameter | Type | Description | Example |
|
||||
|-----------|------|-------------|---------|
|
||||
| `message` | STRING | Message with variables | `"Olá {name}, confira nossas novidades!"` |
|
||||
| `template_file` | FILE | Header image for template | `header.jpg` |
|
||||
| `list_file` | FILE | Contact list with phone numbers | `contacts.xlsx` |
|
||||
| `filter` | STRING | Optional filter condition | `"Perfil=VIP"` |
|
||||
|
||||
### Template Compliance
|
||||
|
||||
The system validates messages for META WhatsApp template approval:
|
||||
|
||||
```basic
|
||||
report = LLM "Esta mensagem será aprovada pelo WhatsApp META como Template?
|
||||
Responda OK se sim, ou explique o problema: " + message
|
||||
|
||||
IF report <> "OK" THEN
|
||||
TALK "Atenção: " + report
|
||||
END IF
|
||||
```
|
||||
|
||||
### Broadcast Execution
|
||||
|
||||
```basic
|
||||
IF filter THEN
|
||||
list = FIND list_file, filter
|
||||
ELSE
|
||||
list = FIND list_file
|
||||
END IF
|
||||
|
||||
index = 1
|
||||
sent = 0
|
||||
|
||||
DO WHILE index < UBOUND(list)
|
||||
row = list[index]
|
||||
|
||||
SEND TEMPLATE TO row.telefone, template_file
|
||||
|
||||
WAIT 0.1 ' Rate limiting
|
||||
|
||||
' Log delivery
|
||||
WITH logEntry
|
||||
timestamp = NOW()
|
||||
phone = row.telefone
|
||||
name = row.name
|
||||
status = "sent"
|
||||
END WITH
|
||||
|
||||
SAVE "broadcast_log.csv", logEntry
|
||||
|
||||
sent = sent + 1
|
||||
index = index + 1
|
||||
LOOP
|
||||
|
||||
TALK "Broadcast enviado para " + sent + " contatos."
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Contact List Format
|
||||
|
||||
The contact file should include:
|
||||
|
||||
| Column | Required | Description |
|
||||
|--------|----------|-------------|
|
||||
| `telefone` | Yes | Phone number with country code |
|
||||
| `name` | No | Contact name for personalization |
|
||||
| `email` | No | Email address |
|
||||
| `Perfil` | No | Segment tag for filtering |
|
||||
|
||||
### Example contacts.xlsx
|
||||
|
||||
```csv
|
||||
telefone,name,email,Perfil
|
||||
+5511999999999,João Silva,joao@email.com,VIP
|
||||
+5511888888888,Maria Santos,maria@email.com,Regular
|
||||
+5511777777777,Pedro Costa,pedro@email.com,VIP
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Sample Conversations
|
||||
|
||||
### Creating a Broadcast
|
||||
|
||||
```
|
||||
User: Send a broadcast to VIP customers
|
||||
|
||||
Bot: I'll help you create a broadcast. What's the message?
|
||||
|
||||
User: Olá {name}, aproveite 20% de desconto esta semana!
|
||||
|
||||
Bot: Checking template compliance...
|
||||
✅ Message approved for WhatsApp template.
|
||||
|
||||
Do you have a header image?
|
||||
|
||||
User: Yes, use promo-banner.jpg
|
||||
|
||||
Bot: Which contact list should I use?
|
||||
|
||||
User: contacts.xlsx
|
||||
|
||||
Bot: 📤 Broadcast Preview:
|
||||
|
||||
Message: Olá {name}, aproveite 20% de desconto esta semana!
|
||||
Image: promo-banner.jpg
|
||||
Recipients: 127 VIP customers
|
||||
|
||||
Send now or schedule?
|
||||
|
||||
User: Send now
|
||||
|
||||
Bot: 📤 Broadcasting...
|
||||
✅ Broadcast complete! Sent to 127 contacts.
|
||||
|
||||
View delivery report in Analytics.
|
||||
```
|
||||
|
||||
### Content Ideation
|
||||
|
||||
```
|
||||
User: I need content ideas for our new product launch
|
||||
|
||||
Bot: What product are you launching?
|
||||
|
||||
User: Wireless headphones
|
||||
|
||||
Bot: What platform are you targeting?
|
||||
|
||||
User: Instagram
|
||||
|
||||
Bot: Here are 5 content ideas for your wireless headphones launch:
|
||||
|
||||
1. "Experience Sound Like Never Before 🎧"
|
||||
Key message: Premium audio quality
|
||||
CTA: Shop now, link in bio
|
||||
Hashtags: #WirelessFreedom #AudioExperience #NewLaunch
|
||||
|
||||
2. "Cut the Cord, Not the Quality"
|
||||
Key message: Freedom without compromise
|
||||
CTA: Pre-order today
|
||||
Hashtags: #WirelessAudio #TechLife #MusicLovers
|
||||
|
||||
3. "Your Music. Your Freedom."
|
||||
Key message: Lifestyle integration
|
||||
CTA: Discover more
|
||||
Hashtags: #OnTheGo #Wireless #Premium
|
||||
|
||||
4. "30 Hours of Pure Sound"
|
||||
Key message: Battery life
|
||||
CTA: Learn more
|
||||
Hashtags: #AllDayBattery #WirelessHeadphones
|
||||
|
||||
5. "Studio Sound, Everywhere"
|
||||
Key message: Professional quality
|
||||
CTA: Experience now
|
||||
Hashtags: #StudioQuality #Audiophile #TechGear
|
||||
|
||||
Would you like me to generate images for any of these?
|
||||
```
|
||||
|
||||
### Image Generation
|
||||
|
||||
```
|
||||
User: Generate an image for idea 1
|
||||
|
||||
Bot: Generating marketing image...
|
||||
|
||||
Prompt: "Premium wireless headphones floating in space with
|
||||
sound waves emanating, modern minimalist style, product
|
||||
photography, dark background with purple accent lighting"
|
||||
|
||||
[Generated Image]
|
||||
|
||||
✅ Image generated! Would you like to:
|
||||
1. Post to Instagram
|
||||
2. Use in a broadcast
|
||||
3. Generate variations
|
||||
4. Download
|
||||
|
||||
User: Post to Instagram
|
||||
|
||||
Bot: What caption should I use?
|
||||
|
||||
User: Experience Sound Like Never Before 🎧 #WirelessFreedom #NewLaunch
|
||||
|
||||
Bot: ✅ Posted to Instagram!
|
||||
|
||||
Post ID: 12345678
|
||||
Time: May 15, 2025 at 2:30 PM
|
||||
|
||||
Track engagement in Analytics.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Audience Segmentation
|
||||
|
||||
### Filter Examples
|
||||
|
||||
| Filter | Description |
|
||||
|--------|-------------|
|
||||
| `Perfil=VIP` | VIP customers only |
|
||||
| `Perfil=Regular AND compras>5` | Regular customers with 5+ purchases |
|
||||
| `ultima_compra>2024-01-01` | Recent purchasers |
|
||||
| `cidade=São Paulo` | Location-based |
|
||||
| `interesse=electronics` | Interest-based |
|
||||
|
||||
### Building Segments
|
||||
|
||||
```basic
|
||||
' Create reusable segments
|
||||
WITH segment
|
||||
id = "SEG-" + FORMAT(GUID())
|
||||
name = "VIP São Paulo"
|
||||
filter = "Perfil=VIP AND cidade=São Paulo"
|
||||
count = COUNT(FIND "contacts.xlsx", filter)
|
||||
created_at = NOW()
|
||||
END WITH
|
||||
|
||||
SAVE "segments.csv", segment
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
Configure in `marketing.gbot/config.csv`:
|
||||
|
||||
| Parameter | Description | Example |
|
||||
|-----------|-------------|---------|
|
||||
| `Brand Color` | Primary brand color | `#FF5722` |
|
||||
| `Logo File` | Company logo path | `logo.png` |
|
||||
| `Instagram Account` | Connected IG account | `@mycompany` |
|
||||
| `WhatsApp Business ID` | WA Business account | `123456789` |
|
||||
| `Default Template` | Default broadcast template | `marketing_update` |
|
||||
| `Rate Limit` | Messages per second | `10` |
|
||||
| `Max Broadcast Size` | Maximum recipients | `1000` |
|
||||
|
||||
---
|
||||
|
||||
## Analytics & Reporting
|
||||
|
||||
### Broadcast Analytics
|
||||
|
||||
```basic
|
||||
' Get broadcast statistics
|
||||
broadcast_id = "BROADCAST-20240115-1234"
|
||||
logs = FIND "broadcast_log.csv", "broadcast_id = '" + broadcast_id + "'"
|
||||
|
||||
total_sent = COUNT(logs)
|
||||
delivered = COUNT(FIND logs, "status = 'delivered'")
|
||||
read = COUNT(FIND logs, "status = 'read'")
|
||||
clicked = COUNT(FIND logs, "status = 'clicked'")
|
||||
|
||||
TALK "📊 Broadcast Report"
|
||||
TALK "Total Sent: " + total_sent
|
||||
TALK "Delivered: " + delivered + " (" + (delivered/total_sent*100) + "%)"
|
||||
TALK "Read: " + read + " (" + (read/total_sent*100) + "%)"
|
||||
TALK "Clicked: " + clicked + " (" + (clicked/total_sent*100) + "%)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Customization
|
||||
|
||||
### Adding Campaign Types
|
||||
|
||||
```basic
|
||||
' campaign-email.bas
|
||||
PARAM subject AS STRING DESCRIPTION "Email subject line"
|
||||
PARAM body AS STRING DESCRIPTION "Email body content"
|
||||
PARAM list_file AS FILE DESCRIPTION "Contact list"
|
||||
PARAM filter AS STRING DESCRIPTION "Segment filter" OPTIONAL
|
||||
|
||||
DESCRIPTION "Send email marketing campaign"
|
||||
|
||||
IF filter THEN
|
||||
contacts = FIND list_file, filter
|
||||
ELSE
|
||||
contacts = FIND list_file
|
||||
END IF
|
||||
|
||||
FOR EACH contact IN contacts
|
||||
personalized_body = REPLACE(body, "{name}", contact.name)
|
||||
SEND EMAIL contact.email, subject, personalized_body
|
||||
|
||||
WITH log
|
||||
campaign_id = campaign_id
|
||||
contact_email = contact.email
|
||||
sent_at = NOW()
|
||||
status = "sent"
|
||||
END WITH
|
||||
|
||||
SAVE "email_campaign_log.csv", log
|
||||
NEXT
|
||||
|
||||
TALK "Email campaign sent to " + UBOUND(contacts) + " recipients."
|
||||
```
|
||||
|
||||
### Social Media Scheduling
|
||||
|
||||
```basic
|
||||
' schedule-post.bas
|
||||
PARAM platform AS STRING LIKE "instagram" DESCRIPTION "Social platform"
|
||||
PARAM content AS STRING DESCRIPTION "Post content"
|
||||
PARAM image AS FILE DESCRIPTION "Post image" OPTIONAL
|
||||
PARAM schedule_time AS STRING DESCRIPTION "When to post"
|
||||
|
||||
DESCRIPTION "Schedule social media post"
|
||||
|
||||
WITH scheduled_post
|
||||
id = "POST-" + FORMAT(GUID())
|
||||
platform = platform
|
||||
content = content
|
||||
image = image
|
||||
scheduled_for = schedule_time
|
||||
status = "scheduled"
|
||||
created_at = NOW()
|
||||
END WITH
|
||||
|
||||
SAVE "scheduled_posts.csv", scheduled_post
|
||||
|
||||
SET SCHEDULE schedule_time, "execute-scheduled-post.bas"
|
||||
|
||||
TALK "Post scheduled for " + schedule_time + " on " + platform
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Template compliance** - Always validate templates before broadcast
|
||||
2. **Segment wisely** - Target relevant audiences to improve engagement
|
||||
3. **Rate limiting** - Respect platform rate limits to avoid blocks
|
||||
4. **Personalization** - Use variables for personalized messages
|
||||
5. **A/B testing** - Test different messages with small segments first
|
||||
6. **Timing** - Schedule broadcasts for optimal engagement times
|
||||
7. **Tracking** - Monitor delivery and engagement metrics
|
||||
8. **Opt-out handling** - Honor unsubscribe requests immediately
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Issue | Cause | Solution |
|
||||
|-------|-------|----------|
|
||||
| Template rejected | Non-compliant content | Review META guidelines |
|
||||
| Low delivery rate | Invalid phone numbers | Clean contact list |
|
||||
| Broadcast blocked | Rate limit exceeded | Reduce sending speed |
|
||||
| Images not generating | Invalid prompt | Simplify prompt text |
|
||||
| Instagram post failed | Auth expired | Reconnect account |
|
||||
|
||||
---
|
||||
|
||||
## Compliance Notes
|
||||
|
||||
- Ensure recipients have opted in to receive marketing messages
|
||||
- Honor unsubscribe requests within 24 hours
|
||||
- Follow META WhatsApp Business policies
|
||||
- Comply with GDPR/LGPD data protection requirements
|
||||
- Keep records of consent for audit purposes
|
||||
|
||||
---
|
||||
|
||||
## Use Cases
|
||||
|
||||
- **Product Launches** - Announce new products to customers
|
||||
- **Promotions** - Send special offers and discounts
|
||||
- **Events** - Promote webinars, sales, and events
|
||||
- **Newsletters** - Regular customer communications
|
||||
- **Re-engagement** - Win back inactive customers
|
||||
- **Social Media** - Automated content posting
|
||||
|
||||
---
|
||||
|
||||
## Related Templates
|
||||
|
||||
- [CRM](./template-crm.md) - Customer relationship management
|
||||
- [Contacts](./template-crm-contacts.md) - Contact list management
|
||||
- [Broadcast](./template-broadcast.md) - General message broadcasting
|
||||
- [Analytics](./template-analytics.md) - Marketing analytics
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
- [Templates Reference](./templates.md) - Full template list
|
||||
- [Template Samples](./template-samples.md) - Example conversations
|
||||
- [gbdialog Reference](../chapter-06-gbdialog/README.md) - BASIC scripting guide
|
||||
394
docs/src/chapter-02/template-office.md
Normal file
394
docs/src/chapter-02/template-office.md
Normal file
|
|
@ -0,0 +1,394 @@
|
|||
# Office Automation Template (office.gbai)
|
||||
|
||||
A General Bots template for role-based office productivity with department-specific knowledge bases and context-aware assistance.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
The Office template provides a multi-role office assistant that adapts its behavior, knowledge, and suggestions based on the user's role. Whether you're a manager, developer, customer support agent, HR professional, or finance team member, the bot tailors its responses and available resources accordingly.
|
||||
|
||||
## Features
|
||||
|
||||
- **Role-Based Access** - Different capabilities per user role
|
||||
- **Dynamic Knowledge Bases** - Automatically loads relevant KB per role
|
||||
- **Context-Aware Responses** - AI behavior adapts to role requirements
|
||||
- **Custom Suggestions** - Role-specific quick actions
|
||||
- **Tool Integration** - Calendar, tasks, documents, meetings, notes
|
||||
- **Persistent Role Memory** - Remembers user role across sessions
|
||||
|
||||
---
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
office.gbai/
|
||||
├── office.gbdialog/
|
||||
│ ├── start.bas # Role selection and configuration
|
||||
│ ├── api-integration.bas # External API connections
|
||||
│ ├── data-sync.bas # Data synchronization
|
||||
│ └── document-processor.bas # Document handling
|
||||
├── office.gbkb/ # Knowledge bases by role
|
||||
│ ├── management/
|
||||
│ ├── documentation/
|
||||
│ ├── products/
|
||||
│ ├── hr-policies/
|
||||
│ └── budgets/
|
||||
└── office.gbot/
|
||||
└── config.csv # Bot configuration
|
||||
```
|
||||
|
||||
## Scripts
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `start.bas` | Main entry with role selection and context setup |
|
||||
| `api-integration.bas` | Connect to external office systems |
|
||||
| `data-sync.bas` | Sync data across office applications |
|
||||
| `document-processor.bas` | Process and manage documents |
|
||||
|
||||
---
|
||||
|
||||
## Supported Roles
|
||||
|
||||
### Manager
|
||||
|
||||
- **Context**: Executive assistant for reports, team management, strategic decisions
|
||||
- **Knowledge Bases**: management, reports, team-policies
|
||||
- **Suggestions**: Team performance, Generate report, Schedule meeting
|
||||
|
||||
### Developer
|
||||
|
||||
- **Context**: Technical assistant for documentation, APIs, coding best practices
|
||||
- **Knowledge Bases**: documentation, apis, coding-standards
|
||||
- **Suggestions**: Search documentation, API reference, Code review checklist
|
||||
|
||||
### Customer Support
|
||||
|
||||
- **Context**: Customer service assistant focused on resolving issues
|
||||
- **Knowledge Bases**: products, support, faq
|
||||
- **Suggestions**: Track my order, Product information, Contact support
|
||||
|
||||
### HR
|
||||
|
||||
- **Context**: HR assistant for employee matters, policies, benefits
|
||||
- **Knowledge Bases**: hr-policies, benefits, onboarding
|
||||
- **Suggestions**: Employee handbook, Benefits overview, New hire checklist
|
||||
|
||||
### Finance
|
||||
|
||||
- **Context**: Finance assistant for budgets, expenses, financial reports
|
||||
- **Knowledge Bases**: budgets, expenses, financial-reports
|
||||
- **Suggestions**: Expense policy, Budget status, Approval workflow
|
||||
|
||||
---
|
||||
|
||||
## Available Tools
|
||||
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `calendar` | Schedule and manage appointments |
|
||||
| `tasks` | Create and track to-do items |
|
||||
| `documents` | Access and manage documents |
|
||||
| `meetings` | Schedule and join meetings |
|
||||
| `notes` | Create and search notes |
|
||||
|
||||
---
|
||||
|
||||
## Sample Conversation
|
||||
|
||||
### Role Selection
|
||||
|
||||
```
|
||||
Bot: Welcome to the Office Assistant!
|
||||
Please select your role:
|
||||
|
||||
User: manager
|
||||
|
||||
Bot: Welcome, Manager! I can help with reports, team
|
||||
management, and policies.
|
||||
|
||||
Quick Actions:
|
||||
• Team performance
|
||||
• Generate report
|
||||
• Schedule meeting
|
||||
```
|
||||
|
||||
### Manager Interaction
|
||||
|
||||
```
|
||||
User: I need to review my team's performance
|
||||
|
||||
Bot: I'll help you review team performance. Here's a summary:
|
||||
|
||||
📊 Team Performance Dashboard
|
||||
|
||||
Active Projects: 5
|
||||
Completed This Month: 3
|
||||
|
||||
Top Performers:
|
||||
• Sarah Chen: 12 tasks completed
|
||||
• Mike Johnson: 10 tasks completed
|
||||
|
||||
Pending Approvals: 2
|
||||
|
||||
Would you like a detailed report or to schedule 1:1s?
|
||||
```
|
||||
|
||||
### Developer Interaction
|
||||
|
||||
```
|
||||
User: How do I implement pagination in our API?
|
||||
|
||||
Bot: Based on our API documentation, here's the pagination pattern:
|
||||
|
||||
GET /api/v1/users?page=1&per_page=20
|
||||
|
||||
Response includes:
|
||||
• data: Array of results
|
||||
• meta.total: Total count
|
||||
• meta.page: Current page
|
||||
• links.next: Next page URL
|
||||
|
||||
Our coding standards recommend cursor-based pagination
|
||||
for large datasets.
|
||||
|
||||
📄 Source: docs/api/pagination.md
|
||||
```
|
||||
|
||||
### Customer Support Interaction
|
||||
|
||||
```
|
||||
User: Customer asking about order #12345
|
||||
|
||||
Bot: I found order #12345. Here are the details:
|
||||
|
||||
📦 Order Status: Shipped
|
||||
📅 Shipped: May 14, 2025
|
||||
🚚 Carrier: FedEx
|
||||
📍 Tracking: 7891234567890
|
||||
|
||||
Expected delivery: May 17, 2025
|
||||
|
||||
Would you like to:
|
||||
• Send tracking info to customer
|
||||
• Create a support ticket
|
||||
• Escalate to supervisor
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
Configure in `office.gbot/config.csv`:
|
||||
|
||||
| Parameter | Description | Example |
|
||||
|-----------|-------------|---------|
|
||||
| `Default Role` | Role when none selected | `customer` |
|
||||
| `Remember Role` | Persist role across sessions | `true` |
|
||||
| `Role Timeout` | Hours before re-asking role | `24` |
|
||||
| `Theme Color` | UI accent color | `blue` |
|
||||
|
||||
---
|
||||
|
||||
## How It Works
|
||||
|
||||
### Role Detection and Setup
|
||||
|
||||
```basic
|
||||
ADD TOOL "calendar"
|
||||
ADD TOOL "tasks"
|
||||
ADD TOOL "documents"
|
||||
ADD TOOL "meetings"
|
||||
ADD TOOL "notes"
|
||||
|
||||
role = GET role
|
||||
|
||||
IF NOT role THEN
|
||||
TALK "Welcome to the Office Assistant!"
|
||||
TALK "Please select your role:"
|
||||
HEAR role AS NAME
|
||||
role = LOWER(role)
|
||||
SET role, role
|
||||
END IF
|
||||
|
||||
SWITCH role
|
||||
CASE "manager"
|
||||
SET CONTEXT "You are an executive assistant helping managers..."
|
||||
USE KB "management"
|
||||
USE KB "reports"
|
||||
USE KB "team-policies"
|
||||
TALK "Welcome, Manager! I can help with reports and team management."
|
||||
|
||||
CASE "developer"
|
||||
SET CONTEXT "You are a technical assistant helping developers..."
|
||||
USE KB "documentation"
|
||||
USE KB "apis"
|
||||
USE KB "coding-standards"
|
||||
TALK "Welcome, Developer! I can help with documentation and APIs."
|
||||
|
||||
' ... more roles
|
||||
END SWITCH
|
||||
```
|
||||
|
||||
### Dynamic Suggestions
|
||||
|
||||
```basic
|
||||
CLEAR SUGGESTIONS
|
||||
|
||||
SWITCH role
|
||||
CASE "manager"
|
||||
ADD SUGGESTION "performance" AS "Team performance"
|
||||
ADD SUGGESTION "report" AS "Generate report"
|
||||
ADD SUGGESTION "meeting" AS "Schedule meeting"
|
||||
|
||||
CASE "developer"
|
||||
ADD SUGGESTION "docs" AS "Search documentation"
|
||||
ADD SUGGESTION "api" AS "API reference"
|
||||
ADD SUGGESTION "review" AS "Code review checklist"
|
||||
|
||||
CASE "customer"
|
||||
ADD SUGGESTION "order" AS "Track my order"
|
||||
ADD SUGGESTION "product" AS "Product information"
|
||||
ADD SUGGESTION "support" AS "Contact support"
|
||||
END SWITCH
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Customization
|
||||
|
||||
### Adding New Roles
|
||||
|
||||
Extend the `start.bas` file:
|
||||
|
||||
```basic
|
||||
CASE "sales"
|
||||
SET CONTEXT "You are a sales assistant helping with leads and deals."
|
||||
USE KB "sales-playbook"
|
||||
USE KB "pricing"
|
||||
USE KB "competitors"
|
||||
TALK "Welcome, Sales! I can help with leads, pricing, and proposals."
|
||||
|
||||
CLEAR SUGGESTIONS
|
||||
ADD SUGGESTION "leads" AS "View my leads"
|
||||
ADD SUGGESTION "quote" AS "Generate quote"
|
||||
ADD SUGGESTION "pipeline" AS "Pipeline status"
|
||||
```
|
||||
|
||||
### Custom Knowledge Bases
|
||||
|
||||
Create role-specific knowledge bases in `office.gbkb/`:
|
||||
|
||||
```
|
||||
office.gbkb/
|
||||
├── sales-playbook/
|
||||
│ ├── objection-handling.md
|
||||
│ ├── pricing-guide.md
|
||||
│ └── competitor-comparison.md
|
||||
```
|
||||
|
||||
### Role-Specific Tools
|
||||
|
||||
Register different tools per role:
|
||||
|
||||
```basic
|
||||
CASE "manager"
|
||||
ADD TOOL "calendar"
|
||||
ADD TOOL "tasks"
|
||||
ADD TOOL "team-report"
|
||||
ADD TOOL "approve-request"
|
||||
|
||||
CASE "developer"
|
||||
ADD TOOL "search-docs"
|
||||
ADD TOOL "api-tester"
|
||||
ADD TOOL "code-review"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Integration Examples
|
||||
|
||||
### With Calendar
|
||||
|
||||
```basic
|
||||
' Schedule meeting for manager
|
||||
IF role = "manager" THEN
|
||||
TALK "I'll schedule the team meeting."
|
||||
CREATE CALENDAR EVENT "Team Standup", tomorrow + " 9:00 AM", 30
|
||||
END IF
|
||||
```
|
||||
|
||||
### With Document System
|
||||
|
||||
```basic
|
||||
' Generate document based on role
|
||||
SWITCH role
|
||||
CASE "hr"
|
||||
template = "offer-letter-template.docx"
|
||||
CASE "sales"
|
||||
template = "proposal-template.docx"
|
||||
CASE "finance"
|
||||
template = "budget-template.xlsx"
|
||||
END SWITCH
|
||||
|
||||
document = GENERATE FROM TEMPLATE template WITH data
|
||||
```
|
||||
|
||||
### With Task Management
|
||||
|
||||
```basic
|
||||
' Create role-appropriate tasks
|
||||
IF role = "manager" THEN
|
||||
CREATE TASK "Review Q4 budget", "high", manager_email
|
||||
CREATE TASK "Approve team PTO requests", "medium", manager_email
|
||||
END IF
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Clear role definitions** - Define clear boundaries for each role
|
||||
2. **Relevant suggestions** - Keep quick actions useful for each role
|
||||
3. **Appropriate KBs** - Only load necessary knowledge bases
|
||||
4. **Security awareness** - Restrict sensitive data by role
|
||||
5. **Regular updates** - Keep knowledge bases current
|
||||
6. **Feedback loops** - Monitor which features each role uses
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Issue | Cause | Solution |
|
||||
|-------|-------|----------|
|
||||
| Wrong KB loaded | Role not set correctly | Check role detection logic |
|
||||
| Missing suggestions | Role not in switch | Add role to all switch blocks |
|
||||
| Context confusion | Multiple roles used | Clear context between role changes |
|
||||
| Slow responses | Too many KBs loaded | Load only essential KBs per role |
|
||||
|
||||
---
|
||||
|
||||
## Use Cases
|
||||
|
||||
- **Corporate Offices** - Multi-department support
|
||||
- **Startups** - Flexible role-based assistance
|
||||
- **Remote Teams** - Unified office assistant
|
||||
- **Enterprise** - Department-specific knowledge management
|
||||
|
||||
---
|
||||
|
||||
## Related Templates
|
||||
|
||||
- [Contacts](./template-crm-contacts.md) - Contact management
|
||||
- [Reminder](./template-reminder.md) - Task and reminder management
|
||||
- [CRM](./template-crm.md) - Full CRM for sales roles
|
||||
- [Analytics](./template-analytics.md) - Platform analytics for managers
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
- [Templates Reference](./templates.md) - Full template list
|
||||
- [Template Samples](./template-samples.md) - Example conversations
|
||||
- [gbdialog Reference](../chapter-06-gbdialog/README.md) - BASIC scripting guide
|
||||
417
docs/src/chapter-02/template-reminder.md
Normal file
417
docs/src/chapter-02/template-reminder.md
Normal file
|
|
@ -0,0 +1,417 @@
|
|||
# Reminder Template (reminder.gbai)
|
||||
|
||||
A General Bots template for managing personal and team reminders with multi-channel notifications.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
The Reminder template provides a complete reminder management system with natural language scheduling, multiple notification channels, and snooze capabilities. Users can create, view, manage, and receive reminders through conversational AI.
|
||||
|
||||
## Features
|
||||
|
||||
- **Natural Language Scheduling** - Create reminders using everyday language
|
||||
- **Multi-Channel Notifications** - Email, SMS, or chat notifications
|
||||
- **Reminder Management** - List, snooze, and delete reminders
|
||||
- **Scheduled Execution** - Background job checks and sends due reminders
|
||||
- **Smart Date Parsing** - Understands "tomorrow", "next week", "in 2 hours"
|
||||
- **Persistent Storage** - Reminders saved to CSV for reliability
|
||||
|
||||
---
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
reminder.gbai/
|
||||
├── reminder.gbdata/ # Data storage
|
||||
│ └── reminders.csv # Reminder records
|
||||
├── reminder.gbdialog/
|
||||
│ ├── start.bas # Main entry and tool registration
|
||||
│ ├── add-reminder.bas # Create new reminders
|
||||
│ └── reminder.bas # Scheduled job to send reminders
|
||||
└── reminder.gbot/
|
||||
└── config.csv # Bot configuration
|
||||
```
|
||||
|
||||
## Scripts
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `start.bas` | Registers tools, sets up suggestions, configures context |
|
||||
| `add-reminder.bas` | Creates new reminder records with notifications |
|
||||
| `reminder.bas` | Scheduled job that checks and sends due reminders |
|
||||
|
||||
---
|
||||
|
||||
## Available Tools
|
||||
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `add-reminder` | Create a new reminder |
|
||||
| `list-reminders` | View all pending reminders |
|
||||
| `delete-reminder` | Remove a reminder |
|
||||
| `snooze-reminder` | Postpone a reminder |
|
||||
|
||||
---
|
||||
|
||||
## Data Schema
|
||||
|
||||
### Reminders Table
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `id` | String | Unique identifier (REM-YYYYMMDD-XXXX) |
|
||||
| `remindAt` | DateTime | When to send the reminder |
|
||||
| `message` | String | Reminder content/subject |
|
||||
| `notifyBy` | String | Notification channel (email, sms, chat) |
|
||||
| `email` | Email | User's email address |
|
||||
| `phone` | Phone | User's phone number |
|
||||
| `created` | DateTime | Creation timestamp |
|
||||
| `status` | String | pending, sent, snoozed, deleted |
|
||||
|
||||
---
|
||||
|
||||
## Sample Conversation
|
||||
|
||||
### Creating Reminders
|
||||
|
||||
```
|
||||
User: Remind me to call John tomorrow at 9am
|
||||
|
||||
Bot: ✅ Reminder set: Call John
|
||||
When: Tomorrow at 9:00 AM
|
||||
Notification: chat
|
||||
|
||||
User: Set a reminder for next Monday at 2pm to submit the report
|
||||
|
||||
Bot: ✅ Reminder set: Submit the report
|
||||
When: Monday, May 19 at 2:00 PM
|
||||
Notification: chat
|
||||
|
||||
User: In 30 minutes remind me to take a break
|
||||
|
||||
Bot: ✅ Reminder set: Take a break
|
||||
When: in 30 minutes (2:45 PM)
|
||||
Notification: chat
|
||||
```
|
||||
|
||||
### Viewing Reminders
|
||||
|
||||
```
|
||||
User: Show my reminders
|
||||
|
||||
Bot: 📋 Your Reminders:
|
||||
|
||||
1. Call John
|
||||
📅 Tomorrow at 9:00 AM
|
||||
🔔 chat
|
||||
|
||||
2. Submit the report
|
||||
📅 Monday, May 19 at 2:00 PM
|
||||
🔔 chat
|
||||
|
||||
3. Take a break
|
||||
📅 Today at 2:45 PM
|
||||
🔔 chat
|
||||
```
|
||||
|
||||
### Managing Reminders
|
||||
|
||||
```
|
||||
User: Snooze my call reminder for 1 hour
|
||||
|
||||
Bot: ✅ Reminder snoozed. New time: Tomorrow at 10:00 AM
|
||||
|
||||
User: Delete the report reminder
|
||||
|
||||
Bot: ✅ Reminder deleted: Submit the report
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## How It Works
|
||||
|
||||
### Tool Registration
|
||||
|
||||
```basic
|
||||
ADD TOOL "add-reminder"
|
||||
ADD TOOL "list-reminders"
|
||||
ADD TOOL "delete-reminder"
|
||||
ADD TOOL "snooze-reminder"
|
||||
|
||||
USE KB "reminder.gbkb"
|
||||
|
||||
CLEAR SUGGESTIONS
|
||||
|
||||
ADD SUGGESTION "add" AS "Add a reminder"
|
||||
ADD SUGGESTION "list" AS "View my reminders"
|
||||
ADD SUGGESTION "today" AS "Today's reminders"
|
||||
ADD SUGGESTION "delete" AS "Delete a reminder"
|
||||
|
||||
SET CONTEXT "reminders" AS "You are a reminder assistant helping users manage their tasks and reminders."
|
||||
|
||||
BEGIN SYSTEM PROMPT
|
||||
You are a reminder AI assistant.
|
||||
|
||||
When creating reminders:
|
||||
- Parse natural language dates (tomorrow, next week, in 2 hours)
|
||||
- Confirm the reminder details before saving
|
||||
- Suggest appropriate times if not specified
|
||||
|
||||
When listing reminders:
|
||||
- Show upcoming reminders first
|
||||
- Highlight overdue items
|
||||
- Group by date when appropriate
|
||||
|
||||
Be concise and helpful.
|
||||
END SYSTEM PROMPT
|
||||
```
|
||||
|
||||
### Creating Reminders
|
||||
|
||||
```basic
|
||||
' add-reminder.bas
|
||||
PARAM when AS STRING LIKE "tomorrow at 9am" DESCRIPTION "When to send the reminder"
|
||||
PARAM subject AS STRING LIKE "Call John" DESCRIPTION "What to be reminded about"
|
||||
PARAM notify AS STRING LIKE "email" DESCRIPTION "Notification method" OPTIONAL
|
||||
|
||||
DESCRIPTION "Create a reminder for a specific date and time"
|
||||
|
||||
IF NOT notify THEN
|
||||
notify = "chat"
|
||||
END IF
|
||||
|
||||
reminderid = "REM-" + FORMAT(NOW(), "YYYYMMDD") + "-" + FORMAT(RANDOM(1000, 9999))
|
||||
useremail = GET "session.user_email"
|
||||
userphone = GET "session.user_phone"
|
||||
|
||||
WITH reminder
|
||||
id = reminderid
|
||||
remindAt = when
|
||||
message = subject
|
||||
notifyBy = notify
|
||||
email = useremail
|
||||
phone = userphone
|
||||
created = NOW()
|
||||
status = "pending"
|
||||
END WITH
|
||||
|
||||
SAVE "reminders.csv", reminder
|
||||
|
||||
SET BOT MEMORY "last_reminder", reminderid
|
||||
|
||||
TALK "Reminder set: " + subject
|
||||
TALK "When: " + when
|
||||
TALK "Notification: " + notify
|
||||
|
||||
RETURN reminderid
|
||||
```
|
||||
|
||||
### Scheduled Reminder Delivery
|
||||
|
||||
```basic
|
||||
' reminder.bas - runs on schedule
|
||||
REM SET SCHEDULER "1 * * * * "
|
||||
|
||||
data = FIND "reminder.csv", "when=" + hour
|
||||
|
||||
IF data THEN
|
||||
TALK TO admin, data.subject
|
||||
END IF
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Notification Channels
|
||||
|
||||
| Channel | Delivery Method |
|
||||
|---------|-----------------|
|
||||
| `chat` | Message in bot conversation |
|
||||
| `email` | Email to user's address |
|
||||
| `sms` | SMS to user's phone |
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
Configure in `reminder.gbot/config.csv`:
|
||||
|
||||
| Parameter | Description | Example |
|
||||
|-----------|-------------|---------|
|
||||
| `Default Notification` | Default channel | `chat` |
|
||||
| `Snooze Duration` | Default snooze time | `15` (minutes) |
|
||||
| `Check Interval` | How often to check | `1` (minute) |
|
||||
| `Timezone` | User timezone | `America/New_York` |
|
||||
| `Max Reminders` | Limit per user | `100` |
|
||||
|
||||
---
|
||||
|
||||
## Customization
|
||||
|
||||
### Custom Notification Channels
|
||||
|
||||
Add new notification types:
|
||||
|
||||
```basic
|
||||
' In add-reminder.bas
|
||||
SWITCH notify
|
||||
CASE "chat"
|
||||
' Default chat notification
|
||||
CASE "email"
|
||||
SEND EMAIL email, "Reminder: " + subject, message
|
||||
CASE "sms"
|
||||
SEND SMS phone, "Reminder: " + subject
|
||||
CASE "slack"
|
||||
POST "https://hooks.slack.com/...", {"text": "Reminder: " + subject}
|
||||
CASE "teams"
|
||||
POST "https://outlook.office.com/webhook/...", {"text": subject}
|
||||
END SWITCH
|
||||
```
|
||||
|
||||
### Recurring Reminders
|
||||
|
||||
Add support for recurring reminders:
|
||||
|
||||
```basic
|
||||
' add-recurring-reminder.bas
|
||||
PARAM subject AS STRING DESCRIPTION "What to remind about"
|
||||
PARAM schedule AS STRING LIKE "daily" DESCRIPTION "Frequency: daily, weekly, monthly"
|
||||
PARAM time AS STRING LIKE "9:00 AM" DESCRIPTION "Time of day"
|
||||
|
||||
DESCRIPTION "Create a recurring reminder"
|
||||
|
||||
SET SCHEDULE cron_expression, "send-recurring.bas"
|
||||
|
||||
WITH reminder
|
||||
id = "REC-" + FORMAT(GUID())
|
||||
message = subject
|
||||
frequency = schedule
|
||||
remindTime = time
|
||||
status = "active"
|
||||
END WITH
|
||||
|
||||
SAVE "recurring_reminders.csv", reminder
|
||||
```
|
||||
|
||||
### Priority Levels
|
||||
|
||||
Add priority support:
|
||||
|
||||
```basic
|
||||
PARAM priority AS STRING LIKE "high" DESCRIPTION "Priority: low, medium, high" OPTIONAL
|
||||
|
||||
IF priority = "high" THEN
|
||||
' Send via multiple channels
|
||||
SEND EMAIL email, "🔴 URGENT: " + subject, message
|
||||
SEND SMS phone, "URGENT: " + subject
|
||||
END IF
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Integration Examples
|
||||
|
||||
### With Calendar
|
||||
|
||||
```basic
|
||||
' Sync reminder to calendar
|
||||
IF reminder.notifyBy = "calendar" THEN
|
||||
CREATE CALENDAR EVENT reminder.message, reminder.remindAt, 15
|
||||
END IF
|
||||
```
|
||||
|
||||
### With Tasks
|
||||
|
||||
```basic
|
||||
' Convert reminder to task when due
|
||||
IF reminder.status = "sent" THEN
|
||||
CREATE TASK reminder.message, "medium", user_email
|
||||
END IF
|
||||
```
|
||||
|
||||
### With CRM
|
||||
|
||||
```basic
|
||||
' Add follow-up reminder from CRM
|
||||
PARAM contact_id AS STRING DESCRIPTION "Contact to follow up with"
|
||||
PARAM days AS INTEGER LIKE 7 DESCRIPTION "Days until follow-up"
|
||||
|
||||
contact = FIND "contacts.csv", "id = " + contact_id
|
||||
|
||||
WITH reminder
|
||||
id = FORMAT(GUID())
|
||||
message = "Follow up with " + contact.name
|
||||
remindAt = DATEADD(NOW(), days, "day")
|
||||
notifyBy = "chat"
|
||||
relatedTo = contact_id
|
||||
END WITH
|
||||
|
||||
SAVE "reminders.csv", reminder
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Date Parsing Examples
|
||||
|
||||
The LLM understands various date formats:
|
||||
|
||||
| Input | Parsed As |
|
||||
|-------|-----------|
|
||||
| "tomorrow" | Next day, 9:00 AM |
|
||||
| "tomorrow at 3pm" | Next day, 3:00 PM |
|
||||
| "in 2 hours" | Current time + 2 hours |
|
||||
| "next Monday" | Coming Monday, 9:00 AM |
|
||||
| "end of day" | Today, 5:00 PM |
|
||||
| "next week" | 7 days from now |
|
||||
| "January 15" | Jan 15, current year |
|
||||
| "1/15 at noon" | Jan 15, 12:00 PM |
|
||||
|
||||
---
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Be specific** - Include enough detail in reminder messages
|
||||
2. **Set appropriate times** - Don't set reminders for odd hours
|
||||
3. **Use the right channel** - Critical reminders via multiple channels
|
||||
4. **Clean up** - Delete completed reminders regularly
|
||||
5. **Review regularly** - Check reminder list to stay organized
|
||||
6. **Test notifications** - Verify each channel works before relying on it
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Issue | Cause | Solution |
|
||||
|-------|-------|----------|
|
||||
| Reminder not sent | Scheduler not running | Verify cron job is active |
|
||||
| Wrong time | Timezone mismatch | Configure correct timezone |
|
||||
| No notification | Missing contact info | Ensure email/phone is set |
|
||||
| Duplicate reminders | Created multiple times | Check for existing before adding |
|
||||
| Past date accepted | No validation | Add date validation logic |
|
||||
|
||||
---
|
||||
|
||||
## Use Cases
|
||||
|
||||
- **Personal Productivity** - Don't forget important tasks
|
||||
- **Team Coordination** - Remind team members of deadlines
|
||||
- **Customer Follow-ups** - Schedule sales and support follow-ups
|
||||
- **Meeting Prep** - Get reminded before meetings
|
||||
- **Health & Wellness** - Regular break and wellness reminders
|
||||
|
||||
---
|
||||
|
||||
## Related Templates
|
||||
|
||||
- [Office](./template-office.md) - Office productivity with task management
|
||||
- [CRM](./template-crm.md) - CRM with follow-up reminders
|
||||
- [Contacts](./template-crm-contacts.md) - Contact management with activity tracking
|
||||
- [Marketing](./template-marketing.md) - Marketing with scheduled broadcasts
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
- [Templates Reference](./templates.md) - Full template list
|
||||
- [Template Samples](./template-samples.md) - Example conversations
|
||||
- [gbdialog Reference](../chapter-06-gbdialog/README.md) - BASIC scripting guide
|
||||
352
docs/src/chapter-02/template-template.md
Normal file
352
docs/src/chapter-02/template-template.md
Normal file
|
|
@ -0,0 +1,352 @@
|
|||
# Template for Creating Templates (template.gbai)
|
||||
|
||||
A General Bots meta-template that serves as a starting point for creating new bot templates.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
The Template template (yes, it's a template for templates!) provides the essential structure and best practices for creating new General Bots templates. Use this as your foundation when building custom templates for specific use cases.
|
||||
|
||||
## Features
|
||||
|
||||
- **Standard Structure** - Pre-configured folder hierarchy
|
||||
- **Best Practices** - Follows General Bots conventions
|
||||
- **Documentation Ready** - Includes README template
|
||||
- **Quick Start** - Minimal setup required
|
||||
|
||||
---
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
template.gbai/
|
||||
├── README.md # Template documentation
|
||||
├── template.gbdialog/ # Dialog scripts
|
||||
│ └── send.bas # Example script (placeholder)
|
||||
├── template.gbdrive/ # File storage
|
||||
│ └── (your files here)
|
||||
├── template.gbkb/ # Knowledge base (optional)
|
||||
│ └── docs/
|
||||
└── template.gbot/ # Bot configuration
|
||||
└── config.csv
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Creating a New Template
|
||||
|
||||
### Step 1: Copy the Template
|
||||
|
||||
```bash
|
||||
cp -r templates/template.gbai templates/your-template.gbai
|
||||
```
|
||||
|
||||
### Step 2: Rename Internal Folders
|
||||
|
||||
Rename all internal folders to match your template name:
|
||||
|
||||
```bash
|
||||
cd templates/your-template.gbai
|
||||
mv template.gbdialog your-template.gbdialog
|
||||
mv template.gbdrive your-template.gbdrive
|
||||
mv template.gbot your-template.gbot
|
||||
```
|
||||
|
||||
### Step 3: Configure Your Bot
|
||||
|
||||
Edit `your-template.gbot/config.csv`:
|
||||
|
||||
```csv
|
||||
name,value
|
||||
Bot Name,Your Bot Name
|
||||
Theme Color,blue
|
||||
Answer Mode,default
|
||||
LLM Provider,openai
|
||||
```
|
||||
|
||||
### Step 4: Create Dialog Scripts
|
||||
|
||||
Add your BASIC scripts to `your-template.gbdialog/`:
|
||||
|
||||
```basic
|
||||
' start.bas - Main entry point
|
||||
ADD TOOL "your-tool"
|
||||
|
||||
USE KB "your-template.gbkb"
|
||||
|
||||
CLEAR SUGGESTIONS
|
||||
|
||||
ADD SUGGESTION "option1" AS "First Option"
|
||||
ADD SUGGESTION "option2" AS "Second Option"
|
||||
ADD SUGGESTION "help" AS "Get Help"
|
||||
|
||||
BEGIN TALK
|
||||
**Your Bot Name**
|
||||
|
||||
Welcome! I can help you with:
|
||||
• Feature 1
|
||||
• Feature 2
|
||||
• Feature 3
|
||||
|
||||
What would you like to do?
|
||||
END TALK
|
||||
|
||||
BEGIN SYSTEM PROMPT
|
||||
You are a helpful assistant for [your use case].
|
||||
|
||||
Guidelines:
|
||||
- Be helpful and concise
|
||||
- Use the available tools when appropriate
|
||||
- Ask clarifying questions when needed
|
||||
END SYSTEM PROMPT
|
||||
```
|
||||
|
||||
### Step 5: Add Tools
|
||||
|
||||
Create tool scripts with proper parameters:
|
||||
|
||||
```basic
|
||||
' your-tool.bas
|
||||
PARAM input AS STRING LIKE "example" DESCRIPTION "Description of this parameter"
|
||||
PARAM optional_param AS STRING DESCRIPTION "Optional parameter" OPTIONAL
|
||||
|
||||
DESCRIPTION "What this tool does - this helps the LLM decide when to use it"
|
||||
|
||||
' Your implementation here
|
||||
result = DO_SOMETHING(input)
|
||||
|
||||
IF result THEN
|
||||
RETURN result
|
||||
ELSE
|
||||
RETURN {"error": "Something went wrong"}
|
||||
END IF
|
||||
```
|
||||
|
||||
### Step 6: Add Knowledge Base (Optional)
|
||||
|
||||
If your template needs reference documentation:
|
||||
|
||||
```
|
||||
your-template.gbkb/
|
||||
└── docs/
|
||||
├── feature1.md
|
||||
├── feature2.md
|
||||
└── faq.md
|
||||
```
|
||||
|
||||
### Step 7: Update README
|
||||
|
||||
Replace the README with documentation for your template following the standard format.
|
||||
|
||||
---
|
||||
|
||||
## Template Checklist
|
||||
|
||||
Before publishing your template, ensure:
|
||||
|
||||
- [ ] All folders renamed to match template name
|
||||
- [ ] `config.csv` configured with appropriate defaults
|
||||
- [ ] `start.bas` provides clear entry point
|
||||
- [ ] All tools have `PARAM` and `DESCRIPTION`
|
||||
- [ ] System prompt guides LLM behavior
|
||||
- [ ] README documents all features
|
||||
- [ ] No hardcoded credentials or secrets
|
||||
- [ ] Error handling implemented
|
||||
- [ ] Example conversations documented
|
||||
|
||||
---
|
||||
|
||||
## Naming Conventions
|
||||
|
||||
| Item | Convention | Example |
|
||||
|------|------------|---------|
|
||||
| Template folder | `kebab-case.gbai` | `my-crm.gbai` |
|
||||
| Dialog scripts | `kebab-case.bas` | `add-contact.bas` |
|
||||
| Tools | `kebab-case` | `search-products` |
|
||||
| Config keys | `Title Case` | `Theme Color` |
|
||||
| Table names | `PascalCase` | `CustomerOrders` |
|
||||
|
||||
---
|
||||
|
||||
## File Templates
|
||||
|
||||
### config.csv Template
|
||||
|
||||
```csv
|
||||
name,value
|
||||
Bot Name,Your Bot Name
|
||||
Theme Color,blue
|
||||
Answer Mode,default
|
||||
LLM Provider,openai
|
||||
Admin Email,admin@company.com
|
||||
```
|
||||
|
||||
### start.bas Template
|
||||
|
||||
```basic
|
||||
' Register tools
|
||||
ADD TOOL "tool-name"
|
||||
|
||||
' Load knowledge base
|
||||
USE KB "your-template.gbkb"
|
||||
|
||||
' Configure suggestions
|
||||
CLEAR SUGGESTIONS
|
||||
ADD SUGGESTION "action" AS "Do Something"
|
||||
|
||||
' Welcome message
|
||||
BEGIN TALK
|
||||
**Bot Name**
|
||||
|
||||
Welcome message here.
|
||||
END TALK
|
||||
|
||||
' System prompt
|
||||
BEGIN SYSTEM PROMPT
|
||||
You are a helpful assistant.
|
||||
Define behavior and guidelines here.
|
||||
END SYSTEM PROMPT
|
||||
```
|
||||
|
||||
### Tool Template
|
||||
|
||||
```basic
|
||||
PARAM required_param AS STRING LIKE "example" DESCRIPTION "What this is"
|
||||
PARAM optional_param AS STRING DESCRIPTION "Optional input" OPTIONAL
|
||||
|
||||
DESCRIPTION "What this tool does"
|
||||
|
||||
' Implementation
|
||||
result = YOUR_LOGIC_HERE
|
||||
|
||||
IF result THEN
|
||||
RETURN result
|
||||
ELSE
|
||||
RETURN {"error": "Error message"}
|
||||
END IF
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Dialog Scripts
|
||||
|
||||
1. **Clear entry point** - `start.bas` should be the main entry
|
||||
2. **Register tools** - Use `ADD TOOL` for LLM-callable functions
|
||||
3. **Set context** - Use `SET CONTEXT` and `BEGIN SYSTEM PROMPT`
|
||||
4. **Add suggestions** - Guide users with quick actions
|
||||
5. **Welcome message** - Use `BEGIN TALK` for introduction
|
||||
|
||||
### Tools
|
||||
|
||||
1. **Descriptive names** - Tool names should indicate function
|
||||
2. **Parameter examples** - Use `LIKE` to show expected format
|
||||
3. **Clear descriptions** - Help LLM understand when to use
|
||||
4. **Return values** - Always return meaningful results
|
||||
5. **Error handling** - Handle edge cases gracefully
|
||||
|
||||
### Configuration
|
||||
|
||||
1. **Sensible defaults** - Work out of the box
|
||||
2. **Document options** - Explain each setting
|
||||
3. **No secrets** - Use environment variables for credentials
|
||||
4. **Flexible** - Allow customization without code changes
|
||||
|
||||
### Documentation
|
||||
|
||||
1. **Clear overview** - Explain what the template does
|
||||
2. **Feature list** - Highlight capabilities
|
||||
3. **Usage examples** - Show common scenarios
|
||||
4. **Configuration guide** - Document all settings
|
||||
5. **Troubleshooting** - Address common issues
|
||||
|
||||
---
|
||||
|
||||
## Publishing Your Template
|
||||
|
||||
1. **Test thoroughly** - Verify all features work
|
||||
2. **Document completely** - Users should be self-sufficient
|
||||
3. **Follow conventions** - Consistent with other templates
|
||||
4. **Update main README** - Add to templates list
|
||||
5. **Submit PR** - Include template and documentation
|
||||
|
||||
---
|
||||
|
||||
## Sample Conversation
|
||||
|
||||
```
|
||||
User: How do I create a new template?
|
||||
|
||||
Bot: To create a new template:
|
||||
|
||||
1. Copy the template.gbai folder
|
||||
2. Rename it to your-template.gbai
|
||||
3. Rename internal folders to match
|
||||
4. Edit config.csv with your settings
|
||||
5. Create your dialog scripts in .gbdialog
|
||||
6. Add tools as separate .bas files
|
||||
7. Update the README
|
||||
|
||||
Would you like help with any specific step?
|
||||
|
||||
User: How do I add a tool?
|
||||
|
||||
Bot: To add a tool, create a .bas file in your .gbdialog folder:
|
||||
|
||||
' my-tool.bas
|
||||
PARAM input AS STRING LIKE "example" DESCRIPTION "Input parameter"
|
||||
|
||||
DESCRIPTION "What this tool does"
|
||||
|
||||
' Your logic here
|
||||
result = PROCESS(input)
|
||||
RETURN result
|
||||
|
||||
Then register it in start.bas:
|
||||
|
||||
ADD TOOL "my-tool"
|
||||
|
||||
The LLM will automatically call your tool when appropriate
|
||||
based on the DESCRIPTION you provided.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Issue | Cause | Solution |
|
||||
|-------|-------|----------|
|
||||
| Tool not found | Not registered | Add `ADD TOOL "name"` in start.bas |
|
||||
| Tool not called | Poor description | Improve DESCRIPTION text |
|
||||
| Wrong folder structure | Names don't match | Ensure all folders use same prefix |
|
||||
| Config not loading | Wrong format | Check CSV syntax |
|
||||
| KB not found | Wrong path | Verify USE KB path matches folder |
|
||||
|
||||
---
|
||||
|
||||
## Related Resources
|
||||
|
||||
- [Templates Reference](./templates.md) - Full template list
|
||||
- [Template Samples](./template-samples.md) - Example conversations
|
||||
- [gbdialog Reference](../chapter-06-gbdialog/README.md) - BASIC scripting guide
|
||||
- [Bot Configuration](../chapter-08-config/README.md) - Configuration options
|
||||
|
||||
---
|
||||
|
||||
## Use Cases for Custom Templates
|
||||
|
||||
- **Industry-Specific** - Healthcare, legal, finance bots
|
||||
- **Department-Specific** - HR, IT, sales assistants
|
||||
- **Process Automation** - Workflow-specific bots
|
||||
- **Integration Templates** - Connect to specific APIs/systems
|
||||
- **Vertical Solutions** - Complete solutions for business needs
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
- [Templates Reference](./templates.md) - Full template list
|
||||
- [Template Samples](./template-samples.md) - Example conversations
|
||||
- [gbdialog Reference](../chapter-06-gbdialog/README.md) - BASIC scripting guide
|
||||
368
src/core/config/model_routing_config.rs
Normal file
368
src/core/config/model_routing_config.rs
Normal file
|
|
@ -0,0 +1,368 @@
|
|||
//! Model Routing Configuration
|
||||
//! Parameters: model-routing-strategy, model-default, model-fast, model-quality, model-code, model-fallback-enabled, model-fallback-order
|
||||
//!
|
||||
//! Config.csv properties:
|
||||
//! ```csv
|
||||
//! model-routing-strategy,default
|
||||
//! model-default,gpt-4o
|
||||
//! model-fast,gpt-4o-mini
|
||||
//! model-quality,gpt-4o
|
||||
//! model-code,gpt-4o
|
||||
//! model-fallback-enabled,true
|
||||
//! model-fallback-order,gpt-4o,gpt-4o-mini,gpt-3.5-turbo
|
||||
//! ```
|
||||
|
||||
use diesel::prelude::*;
|
||||
use log::{debug, warn};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::shared::utils::DbPool;
|
||||
|
||||
/// Routing strategy for model selection
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum RoutingStrategy {
|
||||
/// Always use the default model
|
||||
#[default]
|
||||
Default,
|
||||
/// Select model based on task complexity
|
||||
TaskBased,
|
||||
/// Round-robin across available models
|
||||
RoundRobin,
|
||||
/// Use fastest model for the task
|
||||
Latency,
|
||||
/// Use cheapest model that meets requirements
|
||||
Cost,
|
||||
/// Custom routing logic
|
||||
Custom,
|
||||
}
|
||||
|
||||
impl From<&str> for RoutingStrategy {
|
||||
fn from(s: &str) -> Self {
|
||||
match s.to_lowercase().as_str() {
|
||||
"task-based" | "taskbased" | "task" => RoutingStrategy::TaskBased,
|
||||
"round-robin" | "roundrobin" | "robin" => RoutingStrategy::RoundRobin,
|
||||
"latency" | "fast" | "speed" => RoutingStrategy::Latency,
|
||||
"cost" | "cheap" | "economy" => RoutingStrategy::Cost,
|
||||
"custom" => RoutingStrategy::Custom,
|
||||
_ => RoutingStrategy::Default,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for RoutingStrategy {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
RoutingStrategy::Default => write!(f, "default"),
|
||||
RoutingStrategy::TaskBased => write!(f, "task-based"),
|
||||
RoutingStrategy::RoundRobin => write!(f, "round-robin"),
|
||||
RoutingStrategy::Latency => write!(f, "latency"),
|
||||
RoutingStrategy::Cost => write!(f, "cost"),
|
||||
RoutingStrategy::Custom => write!(f, "custom"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Configuration for Model Routing
|
||||
///
|
||||
/// Model routing allows bots to intelligently select the appropriate LLM
|
||||
/// based on task requirements, cost constraints, or custom logic.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct ModelRoutingConfig {
|
||||
/// Strategy for selecting models
|
||||
pub routing_strategy: RoutingStrategy,
|
||||
/// Default model to use when no specific model is requested
|
||||
pub default_model: String,
|
||||
/// Model optimized for fast responses (simple tasks)
|
||||
pub fast_model: Option<String>,
|
||||
/// Model optimized for quality responses (complex tasks)
|
||||
pub quality_model: Option<String>,
|
||||
/// Model optimized for code generation tasks
|
||||
pub code_model: Option<String>,
|
||||
/// Whether fallback to alternative models is enabled
|
||||
pub fallback_enabled: bool,
|
||||
/// Ordered list of models to try if primary model fails
|
||||
pub fallback_order: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for ModelRoutingConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
routing_strategy: RoutingStrategy::Default,
|
||||
default_model: "gpt-4o".to_string(),
|
||||
fast_model: Some("gpt-4o-mini".to_string()),
|
||||
quality_model: Some("gpt-4o".to_string()),
|
||||
code_model: Some("gpt-4o".to_string()),
|
||||
fallback_enabled: true,
|
||||
fallback_order: vec![
|
||||
"gpt-4o".to_string(),
|
||||
"gpt-4o-mini".to_string(),
|
||||
"gpt-3.5-turbo".to_string(),
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ModelRoutingConfig {
|
||||
/// Load Model Routing configuration from bot_configuration table
|
||||
///
|
||||
/// Reads the following parameters:
|
||||
/// - `model-routing-strategy`: Routing strategy (default: "default")
|
||||
/// - `model-default`: Default model name (default: "gpt-4o")
|
||||
/// - `model-fast`: Fast/lightweight model (default: "gpt-4o-mini")
|
||||
/// - `model-quality`: High-quality model (default: "gpt-4o")
|
||||
/// - `model-code`: Code generation model (default: "gpt-4o")
|
||||
/// - `model-fallback-enabled`: Enable fallback (default: true)
|
||||
/// - `model-fallback-order`: Comma-separated fallback models
|
||||
/// Reads parameters: `model-routing-strategy`, `model-default`, `model-fast`, `model-quality`, `model-code`, `model-fallback-enabled`, `model-fallback-order`
|
||||
pub fn from_bot_config(pool: &DbPool, target_bot_id: &Uuid) -> Self {
|
||||
let mut config = Self::default();
|
||||
|
||||
let mut conn = match pool.get() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
warn!(
|
||||
"Failed to get database connection for Model Routing config: {}",
|
||||
e
|
||||
);
|
||||
return config;
|
||||
}
|
||||
};
|
||||
|
||||
#[derive(QueryableByName)]
|
||||
struct ConfigRow {
|
||||
#[diesel(sql_type = diesel::sql_types::Text)]
|
||||
config_key: String,
|
||||
#[diesel(sql_type = diesel::sql_types::Text)]
|
||||
config_value: String,
|
||||
}
|
||||
|
||||
let configs: Vec<ConfigRow> = diesel::sql_query(
|
||||
"SELECT config_key, config_value FROM bot_configuration \
|
||||
WHERE bot_id = $1 AND config_key LIKE 'model-%'",
|
||||
)
|
||||
.bind::<diesel::sql_types::Uuid, _>(target_bot_id)
|
||||
.load(&mut conn)
|
||||
.unwrap_or_default();
|
||||
|
||||
for row in configs {
|
||||
match row.config_key.as_str() {
|
||||
"model-routing-strategy" => {
|
||||
config.routing_strategy = RoutingStrategy::from(row.config_value.as_str());
|
||||
debug!("Model routing strategy: {}", config.routing_strategy);
|
||||
}
|
||||
"model-default" => {
|
||||
if !row.config_value.is_empty() {
|
||||
config.default_model = row.config_value;
|
||||
debug!("Default model: {}", config.default_model);
|
||||
}
|
||||
}
|
||||
"model-fast" => {
|
||||
config.fast_model = if row.config_value.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(row.config_value)
|
||||
};
|
||||
debug!("Fast model: {:?}", config.fast_model);
|
||||
}
|
||||
"model-quality" => {
|
||||
config.quality_model = if row.config_value.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(row.config_value)
|
||||
};
|
||||
debug!("Quality model: {:?}", config.quality_model);
|
||||
}
|
||||
"model-code" => {
|
||||
config.code_model = if row.config_value.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(row.config_value)
|
||||
};
|
||||
debug!("Code model: {:?}", config.code_model);
|
||||
}
|
||||
"model-fallback-enabled" => {
|
||||
config.fallback_enabled = row.config_value.to_lowercase() == "true";
|
||||
debug!("Model fallback enabled: {}", config.fallback_enabled);
|
||||
}
|
||||
"model-fallback-order" => {
|
||||
let models: Vec<String> = row
|
||||
.config_value
|
||||
.split(',')
|
||||
.map(|s| s.trim().to_string())
|
||||
.filter(|s| !s.is_empty())
|
||||
.collect();
|
||||
if !models.is_empty() {
|
||||
config.fallback_order = models;
|
||||
}
|
||||
debug!("Model fallback order: {:?}", config.fallback_order);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
config
|
||||
}
|
||||
|
||||
/// Get the appropriate model for a given task type
|
||||
pub fn get_model_for_task(&self, task_type: TaskType) -> &str {
|
||||
match self.routing_strategy {
|
||||
RoutingStrategy::Default => &self.default_model,
|
||||
RoutingStrategy::TaskBased => match task_type {
|
||||
TaskType::Simple => self.fast_model.as_deref().unwrap_or(&self.default_model),
|
||||
TaskType::Complex => self.quality_model.as_deref().unwrap_or(&self.default_model),
|
||||
TaskType::Code => self.code_model.as_deref().unwrap_or(&self.default_model),
|
||||
TaskType::Default => &self.default_model,
|
||||
},
|
||||
RoutingStrategy::Latency => self.fast_model.as_deref().unwrap_or(&self.default_model),
|
||||
RoutingStrategy::Cost => self.fast_model.as_deref().unwrap_or(&self.default_model),
|
||||
_ => &self.default_model,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the next fallback model after the given model
|
||||
pub fn get_fallback_model(&self, current_model: &str) -> Option<&str> {
|
||||
if !self.fallback_enabled {
|
||||
return None;
|
||||
}
|
||||
|
||||
let current_idx = self
|
||||
.fallback_order
|
||||
.iter()
|
||||
.position(|m| m == current_model)?;
|
||||
|
||||
self.fallback_order.get(current_idx + 1).map(|s| s.as_str())
|
||||
}
|
||||
|
||||
/// Get all available models in preference order
|
||||
pub fn get_all_models(&self) -> Vec<&str> {
|
||||
let mut models = vec![self.default_model.as_str()];
|
||||
|
||||
if let Some(ref fast) = self.fast_model {
|
||||
if !models.contains(&fast.as_str()) {
|
||||
models.push(fast.as_str());
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref quality) = self.quality_model {
|
||||
if !models.contains(&quality.as_str()) {
|
||||
models.push(quality.as_str());
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref code) = self.code_model {
|
||||
if !models.contains(&code.as_str()) {
|
||||
models.push(code.as_str());
|
||||
}
|
||||
}
|
||||
|
||||
for model in &self.fallback_order {
|
||||
if !models.contains(&model.as_str()) {
|
||||
models.push(model.as_str());
|
||||
}
|
||||
}
|
||||
|
||||
models
|
||||
}
|
||||
}
|
||||
|
||||
/// Task type for model selection
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum TaskType {
|
||||
/// Simple conversational tasks
|
||||
Simple,
|
||||
/// Complex reasoning tasks
|
||||
Complex,
|
||||
/// Code generation/analysis tasks
|
||||
Code,
|
||||
/// Default/unknown task type
|
||||
Default,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_default_config() {
|
||||
let config = ModelRoutingConfig::default();
|
||||
assert_eq!(config.routing_strategy, RoutingStrategy::Default);
|
||||
assert_eq!(config.default_model, "gpt-4o");
|
||||
assert!(config.fallback_enabled);
|
||||
assert!(!config.fallback_order.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_routing_strategy_from_str() {
|
||||
assert_eq!(RoutingStrategy::from("default"), RoutingStrategy::Default);
|
||||
assert_eq!(
|
||||
RoutingStrategy::from("task-based"),
|
||||
RoutingStrategy::TaskBased
|
||||
);
|
||||
assert_eq!(
|
||||
RoutingStrategy::from("round-robin"),
|
||||
RoutingStrategy::RoundRobin
|
||||
);
|
||||
assert_eq!(RoutingStrategy::from("latency"), RoutingStrategy::Latency);
|
||||
assert_eq!(RoutingStrategy::from("cost"), RoutingStrategy::Cost);
|
||||
assert_eq!(RoutingStrategy::from("custom"), RoutingStrategy::Custom);
|
||||
assert_eq!(RoutingStrategy::from("unknown"), RoutingStrategy::Default);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_model_for_task_default_strategy() {
|
||||
let config = ModelRoutingConfig::default();
|
||||
assert_eq!(config.get_model_for_task(TaskType::Simple), "gpt-4o");
|
||||
assert_eq!(config.get_model_for_task(TaskType::Complex), "gpt-4o");
|
||||
assert_eq!(config.get_model_for_task(TaskType::Code), "gpt-4o");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_model_for_task_based_strategy() {
|
||||
let config = ModelRoutingConfig {
|
||||
routing_strategy: RoutingStrategy::TaskBased,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(config.get_model_for_task(TaskType::Simple), "gpt-4o-mini");
|
||||
assert_eq!(config.get_model_for_task(TaskType::Complex), "gpt-4o");
|
||||
assert_eq!(config.get_model_for_task(TaskType::Code), "gpt-4o");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_fallback_model() {
|
||||
let config = ModelRoutingConfig::default();
|
||||
assert_eq!(config.get_fallback_model("gpt-4o"), Some("gpt-4o-mini"));
|
||||
assert_eq!(
|
||||
config.get_fallback_model("gpt-4o-mini"),
|
||||
Some("gpt-3.5-turbo")
|
||||
);
|
||||
assert_eq!(config.get_fallback_model("gpt-3.5-turbo"), None);
|
||||
assert_eq!(config.get_fallback_model("unknown-model"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_fallback_model_disabled() {
|
||||
let config = ModelRoutingConfig {
|
||||
fallback_enabled: false,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(config.get_fallback_model("gpt-4o"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get_all_models() {
|
||||
let config = ModelRoutingConfig::default();
|
||||
let models = config.get_all_models();
|
||||
assert!(models.contains(&"gpt-4o"));
|
||||
assert!(models.contains(&"gpt-4o-mini"));
|
||||
assert!(models.contains(&"gpt-3.5-turbo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_routing_strategy_display() {
|
||||
assert_eq!(format!("{}", RoutingStrategy::Default), "default");
|
||||
assert_eq!(format!("{}", RoutingStrategy::TaskBased), "task-based");
|
||||
assert_eq!(format!("{}", RoutingStrategy::RoundRobin), "round-robin");
|
||||
}
|
||||
}
|
||||
160
src/core/config/sse_config.rs
Normal file
160
src/core/config/sse_config.rs
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
//! SSE Configuration
|
||||
//! Parameters: sse-enabled, sse-heartbeat, sse-max-connections
|
||||
//!
|
||||
//! Config.csv properties:
|
||||
//! ```csv
|
||||
//! sse-enabled,true
|
||||
//! sse-heartbeat,30
|
||||
//! sse-max-connections,1000
|
||||
//! ```
|
||||
|
||||
use diesel::prelude::*;
|
||||
use log::{debug, warn};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::shared::utils::DbPool;
|
||||
|
||||
/// Configuration for Server-Sent Events (SSE)
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct SseConfig {
|
||||
/// Whether SSE is enabled for real-time updates
|
||||
pub enabled: bool,
|
||||
/// Heartbeat interval in seconds to keep connections alive
|
||||
pub heartbeat_seconds: u32,
|
||||
/// Maximum number of concurrent SSE connections per bot
|
||||
pub max_connections: u32,
|
||||
}
|
||||
|
||||
impl Default for SseConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
heartbeat_seconds: 30,
|
||||
max_connections: 1000,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SseConfig {
|
||||
/// Load SSE configuration from bot_configuration table
|
||||
///
|
||||
/// Reads the following parameters:
|
||||
/// - `sse-enabled`: Whether SSE is enabled (default: true)
|
||||
/// - `sse-heartbeat`: Heartbeat interval in seconds (default: 30)
|
||||
/// - `sse-max-connections`: Maximum concurrent connections (default: 1000)
|
||||
pub fn from_bot_config(pool: &DbPool, target_bot_id: &Uuid) -> Self {
|
||||
let mut config = Self::default();
|
||||
|
||||
let mut conn = match pool.get() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
warn!("Failed to get database connection for SSE config: {}", e);
|
||||
return config;
|
||||
}
|
||||
};
|
||||
|
||||
#[derive(QueryableByName)]
|
||||
struct ConfigRow {
|
||||
#[diesel(sql_type = diesel::sql_types::Text)]
|
||||
config_key: String,
|
||||
#[diesel(sql_type = diesel::sql_types::Text)]
|
||||
config_value: String,
|
||||
}
|
||||
|
||||
let configs: Vec<ConfigRow> = diesel::sql_query(
|
||||
"SELECT config_key, config_value FROM bot_configuration \
|
||||
WHERE bot_id = $1 AND config_key LIKE 'sse-%'",
|
||||
)
|
||||
.bind::<diesel::sql_types::Uuid, _>(target_bot_id)
|
||||
.load(&mut conn)
|
||||
.unwrap_or_default();
|
||||
|
||||
for row in configs {
|
||||
match row.config_key.as_str() {
|
||||
"sse-enabled" => {
|
||||
config.enabled = row.config_value.to_lowercase() == "true";
|
||||
debug!("SSE enabled: {}", config.enabled);
|
||||
}
|
||||
"sse-heartbeat" => {
|
||||
config.heartbeat_seconds = row.config_value.parse().unwrap_or(30);
|
||||
debug!("SSE heartbeat: {} seconds", config.heartbeat_seconds);
|
||||
}
|
||||
"sse-max-connections" => {
|
||||
config.max_connections = row.config_value.parse().unwrap_or(1000);
|
||||
debug!("SSE max connections: {}", config.max_connections);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// Validate configuration
|
||||
if config.heartbeat_seconds < 5 {
|
||||
warn!(
|
||||
"SSE heartbeat interval {} is too low, setting to minimum of 5 seconds",
|
||||
config.heartbeat_seconds
|
||||
);
|
||||
config.heartbeat_seconds = 5;
|
||||
}
|
||||
|
||||
if config.max_connections < 1 {
|
||||
warn!("SSE max connections must be at least 1, setting to default 1000");
|
||||
config.max_connections = 1000;
|
||||
}
|
||||
|
||||
config
|
||||
}
|
||||
|
||||
/// Check if more connections can be accepted
|
||||
pub fn can_accept_connection(&self, current_connections: u32) -> bool {
|
||||
self.enabled && current_connections < self.max_connections
|
||||
}
|
||||
|
||||
/// Get the heartbeat duration for SSE keep-alive
|
||||
pub fn heartbeat_duration(&self) -> std::time::Duration {
|
||||
std::time::Duration::from_secs(self.heartbeat_seconds as u64)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_default_config() {
|
||||
let config = SseConfig::default();
|
||||
assert!(config.enabled);
|
||||
assert_eq!(config.heartbeat_seconds, 30);
|
||||
assert_eq!(config.max_connections, 1000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_can_accept_connection() {
|
||||
let config = SseConfig::default();
|
||||
assert!(config.can_accept_connection(0));
|
||||
assert!(config.can_accept_connection(999));
|
||||
assert!(!config.can_accept_connection(1000));
|
||||
assert!(!config.can_accept_connection(1001));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_can_accept_connection_disabled() {
|
||||
let config = SseConfig {
|
||||
enabled: false,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!config.can_accept_connection(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_heartbeat_duration() {
|
||||
let config = SseConfig {
|
||||
heartbeat_seconds: 45,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
config.heartbeat_duration(),
|
||||
std::time::Duration::from_secs(45)
|
||||
);
|
||||
}
|
||||
}
|
||||
197
src/core/config/user_memory_config.rs
Normal file
197
src/core/config/user_memory_config.rs
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
//! User Memory Configuration
|
||||
//! Parameters: user-memory-enabled, user-memory-max-keys, user-memory-default-ttl
|
||||
//!
|
||||
//! Config.csv properties:
|
||||
//! ```csv
|
||||
//! user-memory-enabled,true
|
||||
//! user-memory-max-keys,100
|
||||
//! user-memory-default-ttl,86400
|
||||
//! ```
|
||||
|
||||
use diesel::prelude::*;
|
||||
use log::{debug, warn};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::shared::utils::DbPool;
|
||||
|
||||
/// Configuration for User Memory storage
|
||||
///
|
||||
/// User memory allows bots to store and retrieve key-value pairs
|
||||
/// associated with individual users for personalization and context retention.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct UserMemoryConfig {
|
||||
/// Whether user memory feature is enabled
|
||||
pub enabled: bool,
|
||||
/// Maximum number of keys that can be stored per user
|
||||
pub max_keys: u32,
|
||||
/// Default time-to-live for memory entries in seconds (0 = no expiration)
|
||||
pub default_ttl: u64,
|
||||
}
|
||||
|
||||
impl Default for UserMemoryConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
max_keys: 100,
|
||||
default_ttl: 86400, // 24 hours
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl UserMemoryConfig {
|
||||
/// Load User Memory configuration from bot_configuration table
|
||||
///
|
||||
/// Reads the following parameters:
|
||||
/// - `user-memory-enabled`: Whether user memory is enabled (default: true)
|
||||
/// - `user-memory-max-keys`: Maximum keys per user (default: 100)
|
||||
/// - `user-memory-default-ttl`: Default TTL in seconds (default: 86400)
|
||||
pub fn from_bot_config(pool: &DbPool, target_bot_id: &Uuid) -> Self {
|
||||
let mut config = Self::default();
|
||||
|
||||
let mut conn = match pool.get() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
warn!(
|
||||
"Failed to get database connection for User Memory config: {}",
|
||||
e
|
||||
);
|
||||
return config;
|
||||
}
|
||||
};
|
||||
|
||||
#[derive(QueryableByName)]
|
||||
struct ConfigRow {
|
||||
#[diesel(sql_type = diesel::sql_types::Text)]
|
||||
config_key: String,
|
||||
#[diesel(sql_type = diesel::sql_types::Text)]
|
||||
config_value: String,
|
||||
}
|
||||
|
||||
let configs: Vec<ConfigRow> = diesel::sql_query(
|
||||
"SELECT config_key, config_value FROM bot_configuration \
|
||||
WHERE bot_id = $1 AND config_key LIKE 'user-memory-%'",
|
||||
)
|
||||
.bind::<diesel::sql_types::Uuid, _>(target_bot_id)
|
||||
.load(&mut conn)
|
||||
.unwrap_or_default();
|
||||
|
||||
for row in configs {
|
||||
match row.config_key.as_str() {
|
||||
"user-memory-enabled" => {
|
||||
config.enabled = row.config_value.to_lowercase() == "true";
|
||||
debug!("User memory enabled: {}", config.enabled);
|
||||
}
|
||||
"user-memory-max-keys" => {
|
||||
config.max_keys = row.config_value.parse().unwrap_or(100);
|
||||
debug!("User memory max keys: {}", config.max_keys);
|
||||
}
|
||||
"user-memory-default-ttl" => {
|
||||
config.default_ttl = row.config_value.parse().unwrap_or(86400);
|
||||
debug!("User memory default TTL: {} seconds", config.default_ttl);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// Validate configuration
|
||||
if config.max_keys < 1 {
|
||||
warn!("User memory max keys must be at least 1, setting to default 100");
|
||||
config.max_keys = 100;
|
||||
}
|
||||
|
||||
if config.max_keys > 10000 {
|
||||
warn!(
|
||||
"User memory max keys {} exceeds recommended limit, capping at 10000",
|
||||
config.max_keys
|
||||
);
|
||||
config.max_keys = 10000;
|
||||
}
|
||||
|
||||
config
|
||||
}
|
||||
|
||||
/// Check if a new key can be added given the current count
|
||||
pub fn can_add_key(&self, current_key_count: u32) -> bool {
|
||||
self.enabled && current_key_count < self.max_keys
|
||||
}
|
||||
|
||||
/// Get the TTL duration, returns None if TTL is 0 (no expiration)
|
||||
pub fn ttl_duration(&self) -> Option<std::time::Duration> {
|
||||
if self.default_ttl == 0 {
|
||||
None
|
||||
} else {
|
||||
Some(std::time::Duration::from_secs(self.default_ttl))
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if entries should expire
|
||||
pub fn has_expiration(&self) -> bool {
|
||||
self.default_ttl > 0
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_default_config() {
|
||||
let config = UserMemoryConfig::default();
|
||||
assert!(config.enabled);
|
||||
assert_eq!(config.max_keys, 100);
|
||||
assert_eq!(config.default_ttl, 86400);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_can_add_key() {
|
||||
let config = UserMemoryConfig::default();
|
||||
assert!(config.can_add_key(0));
|
||||
assert!(config.can_add_key(99));
|
||||
assert!(!config.can_add_key(100));
|
||||
assert!(!config.can_add_key(101));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_can_add_key_disabled() {
|
||||
let config = UserMemoryConfig {
|
||||
enabled: false,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!config.can_add_key(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ttl_duration() {
|
||||
let config = UserMemoryConfig {
|
||||
default_ttl: 3600,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
config.ttl_duration(),
|
||||
Some(std::time::Duration::from_secs(3600))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ttl_duration_no_expiration() {
|
||||
let config = UserMemoryConfig {
|
||||
default_ttl: 0,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(config.ttl_duration(), None);
|
||||
assert!(!config.has_expiration());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_has_expiration() {
|
||||
let config = UserMemoryConfig::default();
|
||||
assert!(config.has_expiration());
|
||||
|
||||
let no_expiry = UserMemoryConfig {
|
||||
default_ttl: 0,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!no_expiry.has_expiration());
|
||||
}
|
||||
}
|
||||
352
src/vector-db/bm25_config.rs
Normal file
352
src/vector-db/bm25_config.rs
Normal file
|
|
@ -0,0 +1,352 @@
|
|||
//! BM25 Configuration for Tantivy-based sparse retrieval
|
||||
//!
|
||||
//! This module provides configuration for BM25 text search powered by Tantivy.
|
||||
//! Tantivy is a full-text search engine library (like Lucene) that implements
|
||||
//! the BM25 ranking algorithm.
|
||||
//!
|
||||
//! # Config.csv Parameters
|
||||
//!
|
||||
//! | Parameter | Default | Description |
|
||||
//! |-----------|---------|-------------|
|
||||
//! | `bm25-enabled` | `true` | Enable/disable BM25 sparse search |
|
||||
//! | `bm25-k1` | `1.2` | Term frequency saturation (0.5-3.0 typical) |
|
||||
//! | `bm25-b` | `0.75` | Document length normalization (0.0-1.0) |
|
||||
//! | `bm25-stemming` | `true` | Apply stemming to terms |
|
||||
//! | `bm25-stopwords` | `true` | Filter common stopwords |
|
||||
//!
|
||||
//! # Example config.csv
|
||||
//!
|
||||
//! ```csv
|
||||
//! bm25-enabled,true
|
||||
//! bm25-k1,1.2
|
||||
//! bm25-b,0.75
|
||||
//! bm25-stemming,true
|
||||
//! bm25-stopwords,true
|
||||
//! ```
|
||||
//!
|
||||
//! # Switching BM25 On/Off
|
||||
//!
|
||||
//! To **disable** BM25 sparse search (use only dense/embedding search):
|
||||
//! ```csv
|
||||
//! bm25-enabled,false
|
||||
//! ```
|
||||
//!
|
||||
//! To **enable** BM25 with custom tuning:
|
||||
//! ```csv
|
||||
//! bm25-enabled,true
|
||||
//! bm25-k1,1.5
|
||||
//! bm25-b,0.5
|
||||
//! ```
|
||||
//!
|
||||
//! # How It Works
|
||||
//!
|
||||
//! When `bm25-enabled=true`:
|
||||
//! - Hybrid search uses BOTH BM25 (keyword) + Qdrant (embedding) results
|
||||
//! - Results are merged using Reciprocal Rank Fusion (RRF)
|
||||
//! - Good for queries where exact keyword matches matter
|
||||
//!
|
||||
//! When `bm25-enabled=false`:
|
||||
//! - Only dense (embedding) search via Qdrant is used
|
||||
//! - Faster but may miss exact keyword matches
|
||||
//! - Better for semantic/conceptual queries
|
||||
|
||||
use diesel::prelude::*;
|
||||
use log::{debug, warn};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::shared::utils::DbPool;
|
||||
|
||||
/// Configuration for BM25 sparse retrieval (powered by Tantivy)
|
||||
///
|
||||
/// BM25 (Best Matching 25) is a ranking function used for information retrieval.
|
||||
/// This configuration controls the Tantivy-based BM25 implementation.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct Bm25Config {
|
||||
/// Whether BM25 sparse search is enabled
|
||||
/// When false, only dense (embedding) search is used
|
||||
pub enabled: bool,
|
||||
|
||||
/// Term frequency saturation parameter (typically 1.2-2.0)
|
||||
/// - Higher values: more weight to term frequency
|
||||
/// - Lower values: diminishing returns for repeated terms
|
||||
/// - Tantivy default: 1.2
|
||||
pub k1: f32,
|
||||
|
||||
/// Document length normalization parameter (0.0-1.0)
|
||||
/// - 0.0: no length normalization
|
||||
/// - 1.0: full length normalization (penalizes long documents)
|
||||
/// - Tantivy default: 0.75
|
||||
pub b: f32,
|
||||
|
||||
/// Whether to apply stemming to terms before indexing/searching
|
||||
/// Stemming reduces words to their root form (e.g., "running" → "run")
|
||||
pub stemming: bool,
|
||||
|
||||
/// Whether to filter out common stopwords (e.g., "the", "a", "is")
|
||||
pub stopwords: bool,
|
||||
}
|
||||
|
||||
impl Default for Bm25Config {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enabled: true,
|
||||
k1: 1.2,
|
||||
b: 0.75,
|
||||
stemming: true,
|
||||
stopwords: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Bm25Config {
|
||||
/// Load BM25 configuration from bot_configuration table
|
||||
///
|
||||
/// Reads parameters: `bm25-enabled`, `bm25-k1`, `bm25-b`, `bm25-stemming`, `bm25-stopwords`
|
||||
pub fn from_bot_config(pool: &DbPool, target_bot_id: &Uuid) -> Self {
|
||||
let mut config = Self::default();
|
||||
|
||||
let mut conn = match pool.get() {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
warn!("Failed to get database connection for BM25 config: {}", e);
|
||||
return config;
|
||||
}
|
||||
};
|
||||
|
||||
#[derive(QueryableByName)]
|
||||
struct ConfigRow {
|
||||
#[diesel(sql_type = diesel::sql_types::Text)]
|
||||
config_key: String,
|
||||
#[diesel(sql_type = diesel::sql_types::Text)]
|
||||
config_value: String,
|
||||
}
|
||||
|
||||
let configs: Vec<ConfigRow> = diesel::sql_query(
|
||||
"SELECT config_key, config_value FROM bot_configuration \
|
||||
WHERE bot_id = $1 AND config_key LIKE 'bm25-%'",
|
||||
)
|
||||
.bind::<diesel::sql_types::Uuid, _>(target_bot_id)
|
||||
.load(&mut conn)
|
||||
.unwrap_or_default();
|
||||
|
||||
for row in configs {
|
||||
match row.config_key.as_str() {
|
||||
"bm25-enabled" => {
|
||||
config.enabled = row.config_value.to_lowercase() == "true";
|
||||
debug!("BM25 enabled: {}", config.enabled);
|
||||
}
|
||||
"bm25-k1" => {
|
||||
config.k1 = row.config_value.parse().unwrap_or(1.2);
|
||||
debug!("BM25 k1: {}", config.k1);
|
||||
}
|
||||
"bm25-b" => {
|
||||
config.b = row.config_value.parse().unwrap_or(0.75);
|
||||
debug!("BM25 b: {}", config.b);
|
||||
}
|
||||
"bm25-stemming" => {
|
||||
config.stemming = row.config_value.to_lowercase() == "true";
|
||||
debug!("BM25 stemming: {}", config.stemming);
|
||||
}
|
||||
"bm25-stopwords" => {
|
||||
config.stopwords = row.config_value.to_lowercase() == "true";
|
||||
debug!("BM25 stopwords: {}", config.stopwords);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// Validate and clamp values
|
||||
config.validate();
|
||||
config
|
||||
}
|
||||
|
||||
/// Create config with BM25 disabled (dense-only search)
|
||||
pub fn disabled() -> Self {
|
||||
Self {
|
||||
enabled: false,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Create config with custom k1 and b parameters
|
||||
pub fn with_params(k1: f32, b: f32) -> Self {
|
||||
let mut config = Self {
|
||||
k1,
|
||||
b,
|
||||
..Default::default()
|
||||
};
|
||||
config.validate();
|
||||
config
|
||||
}
|
||||
|
||||
/// Validate and clamp configuration values to sensible ranges
|
||||
fn validate(&mut self) {
|
||||
// k1 should be positive, typically between 0.5 and 3.0
|
||||
if self.k1 < 0.0 {
|
||||
warn!("BM25 k1 cannot be negative, setting to default 1.2");
|
||||
self.k1 = 1.2;
|
||||
} else if self.k1 > 10.0 {
|
||||
warn!("BM25 k1 {} is unusually high, capping at 10.0", self.k1);
|
||||
self.k1 = 10.0;
|
||||
}
|
||||
|
||||
// b should be between 0.0 and 1.0
|
||||
if self.b < 0.0 {
|
||||
warn!("BM25 b cannot be negative, setting to 0.0");
|
||||
self.b = 0.0;
|
||||
} else if self.b > 1.0 {
|
||||
warn!("BM25 b cannot exceed 1.0, capping at 1.0");
|
||||
self.b = 1.0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if BM25 should be used in hybrid search
|
||||
pub fn is_enabled(&self) -> bool {
|
||||
self.enabled
|
||||
}
|
||||
|
||||
/// Check if text preprocessing is enabled
|
||||
pub fn has_preprocessing(&self) -> bool {
|
||||
self.stemming || self.stopwords
|
||||
}
|
||||
|
||||
/// Get a description of the current configuration
|
||||
pub fn describe(&self) -> String {
|
||||
if self.enabled {
|
||||
format!(
|
||||
"BM25(k1={}, b={}, stemming={}, stopwords={})",
|
||||
self.k1, self.b, self.stemming, self.stopwords
|
||||
)
|
||||
} else {
|
||||
"BM25(disabled)".to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Common English stopwords for filtering
|
||||
/// Used when `bm25-stopwords=true`
|
||||
pub const DEFAULT_STOPWORDS: &[&str] = &[
|
||||
"a", "an", "and", "are", "as", "at", "be", "by", "for", "from", "has", "he",
|
||||
"in", "is", "it", "its", "of", "on", "or", "that", "the", "to", "was", "were",
|
||||
"will", "with", "this", "but", "they", "have", "had", "what", "when", "where",
|
||||
"who", "which", "why", "how", "all", "each", "every", "both", "few", "more",
|
||||
"most", "other", "some", "such", "no", "nor", "not", "only", "own", "same",
|
||||
"so", "than", "too", "very", "just", "can", "should", "now", "do", "does",
|
||||
"did", "done", "been", "being", "would", "could", "might", "must", "shall",
|
||||
"may", "am", "your", "our", "their", "his", "her", "my", "me", "him", "them",
|
||||
"us", "you", "i", "we", "she", "if", "then", "else", "about", "into", "over",
|
||||
"after", "before", "between", "under", "again", "further", "once",
|
||||
];
|
||||
|
||||
/// Check if a word is a common stopword
|
||||
pub fn is_stopword(word: &str) -> bool {
|
||||
DEFAULT_STOPWORDS.contains(&word.to_lowercase().as_str())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_default_config() {
|
||||
let config = Bm25Config::default();
|
||||
assert!(config.enabled);
|
||||
assert!((config.k1 - 1.2).abs() < f32::EPSILON);
|
||||
assert!((config.b - 0.75).abs() < f32::EPSILON);
|
||||
assert!(config.stemming);
|
||||
assert!(config.stopwords);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_disabled_config() {
|
||||
let config = Bm25Config::disabled();
|
||||
assert!(!config.enabled);
|
||||
assert!(!config.is_enabled());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_with_params() {
|
||||
let config = Bm25Config::with_params(1.5, 0.5);
|
||||
assert!((config.k1 - 1.5).abs() < f32::EPSILON);
|
||||
assert!((config.b - 0.5).abs() < f32::EPSILON);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validation_negative_k1() {
|
||||
let mut config = Bm25Config {
|
||||
k1: -1.0,
|
||||
..Default::default()
|
||||
};
|
||||
config.validate();
|
||||
assert!((config.k1 - 1.2).abs() < f32::EPSILON);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validation_high_k1() {
|
||||
let mut config = Bm25Config {
|
||||
k1: 15.0,
|
||||
..Default::default()
|
||||
};
|
||||
config.validate();
|
||||
assert!((config.k1 - 10.0).abs() < f32::EPSILON);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_validation_b_range() {
|
||||
let mut config = Bm25Config {
|
||||
b: -0.5,
|
||||
..Default::default()
|
||||
};
|
||||
config.validate();
|
||||
assert!(config.b.abs() < f32::EPSILON);
|
||||
|
||||
let mut config2 = Bm25Config {
|
||||
b: 1.5,
|
||||
..Default::default()
|
||||
};
|
||||
config2.validate();
|
||||
assert!((config2.b - 1.0).abs() < f32::EPSILON);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_has_preprocessing() {
|
||||
let config = Bm25Config::default();
|
||||
assert!(config.has_preprocessing());
|
||||
|
||||
let no_preprocess = Bm25Config {
|
||||
stemming: false,
|
||||
stopwords: false,
|
||||
..Default::default()
|
||||
};
|
||||
assert!(!no_preprocess.has_preprocessing());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_describe() {
|
||||
let config = Bm25Config::default();
|
||||
let desc = config.describe();
|
||||
assert!(desc.contains("k1=1.2"));
|
||||
assert!(desc.contains("b=0.75"));
|
||||
|
||||
let disabled = Bm25Config::disabled();
|
||||
assert_eq!(disabled.describe(), "BM25(disabled)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_stopword() {
|
||||
assert!(is_stopword("the"));
|
||||
assert!(is_stopword("THE"));
|
||||
assert!(is_stopword("and"));
|
||||
assert!(is_stopword("is"));
|
||||
assert!(!is_stopword("algorithm"));
|
||||
assert!(!is_stopword("rust"));
|
||||
assert!(!is_stopword("tantivy"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_stopwords_list() {
|
||||
assert!(!DEFAULT_STOPWORDS.is_empty());
|
||||
assert!(DEFAULT_STOPWORDS.len() > 80);
|
||||
}
|
||||
}
|
||||
245
templates/bi.gbai/README.md
Normal file
245
templates/bi.gbai/README.md
Normal file
|
|
@ -0,0 +1,245 @@
|
|||
# Business Intelligence Template (bi.gbai)
|
||||
|
||||
A General Bots template for automated business intelligence reporting and data visualization.
|
||||
|
||||
## Overview
|
||||
|
||||
The BI template provides scheduled analytics reporting with automatic chart generation and delivery. It's designed for organizations that need automated consumption reports, category analysis, and customer-specific insights.
|
||||
|
||||
## Features
|
||||
|
||||
- **Scheduled Reporting** - Automated report generation on configurable schedules
|
||||
- **Time-Series Charts** - Monthly consumption trends visualization
|
||||
- **Category Analysis** - Product category breakdown with donut charts
|
||||
- **Per-Customer Reports** - Individual customer consumption analysis
|
||||
- **Multi-Channel Delivery** - Send reports via chat, email, or messaging platforms
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
bi.gbai/
|
||||
├── README.md
|
||||
└── bi.gbai/
|
||||
├── bi-admin.bas # Administrative scheduled reports
|
||||
└── bi-user.bas # Per-customer report generation
|
||||
```
|
||||
|
||||
## Scripts
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `bi-admin.bas` | Scheduled job for generating platform-wide analytics reports |
|
||||
| `bi-user.bas` | Loop through customers to generate individual consumption reports |
|
||||
|
||||
## Configuration
|
||||
|
||||
Configure the template in your bot's `config.csv`:
|
||||
|
||||
| Parameter | Description | Example |
|
||||
|-----------|-------------|---------|
|
||||
| `Schedule` | Cron expression for report timing | `1 * * * * *` |
|
||||
| `Data Source` | Table/view for billing data | `Orders` |
|
||||
|
||||
## Usage
|
||||
|
||||
### Administrative Reports
|
||||
|
||||
The `bi-admin.bas` script runs on a schedule and generates:
|
||||
|
||||
1. **Monthly Consumption Chart** - Time-series showing spending trends
|
||||
2. **Product Category Breakdown** - Donut chart of spending by category
|
||||
|
||||
```basic
|
||||
SET SCHEDULE "1 * * * * *"
|
||||
|
||||
billing = FIND "Orders"
|
||||
|
||||
' Monthly consumption
|
||||
data = SELECT SUM(UnitPrice * Quantity) as Value,
|
||||
MONTH(OrderDate)+'/'+YEAR(OrderDate)
|
||||
FROM billing
|
||||
GROUP BY MONTH(OrderDate), YEAR(OrderDate)
|
||||
|
||||
img = CHART "timeseries", data
|
||||
SEND FILE img, "Monthly Consumption"
|
||||
```
|
||||
|
||||
### Per-Customer Reports
|
||||
|
||||
The `bi-user.bas` script iterates through customers to generate personalized reports:
|
||||
|
||||
```basic
|
||||
customers = FIND "Customers"
|
||||
|
||||
FOR EACH c IN customers
|
||||
data = SELECT SUM(UnitPrice * Quantity) AS Value,
|
||||
MONTH(OrderDate)+'/'+YEAR(OrderDate)
|
||||
FROM billing
|
||||
JOIN Customers ON billing.CustomerID = Customers.CustomerID
|
||||
GROUP BY MONTH(OrderDate), YEAR(OrderDate)
|
||||
WHERE Customers.CustomerID = c.CustomerID
|
||||
|
||||
img = CHART "timeseries", data
|
||||
SEND FILE img, "Monthly Consumption"
|
||||
END FOR
|
||||
```
|
||||
|
||||
## Chart Types
|
||||
|
||||
The template supports various chart types:
|
||||
|
||||
| Type | Use Case |
|
||||
|------|----------|
|
||||
| `timeseries` | Trends over time (monthly, weekly, daily) |
|
||||
| `donut` | Category distribution |
|
||||
| `bar` | Comparative analysis |
|
||||
| `pie` | Percentage breakdowns |
|
||||
|
||||
## Data Requirements
|
||||
|
||||
### Orders Table Schema
|
||||
|
||||
The template expects a billing/orders data source with:
|
||||
|
||||
- `OrderDate` - Date of the transaction
|
||||
- `UnitPrice` - Price per unit
|
||||
- `Quantity` - Number of units
|
||||
- `ProductID` - Foreign key to products
|
||||
- `CustomerID` - Foreign key to customers
|
||||
|
||||
### Products Table Schema
|
||||
|
||||
- `ProductID` - Primary key
|
||||
- `CategoryID` - Foreign key to categories
|
||||
- `ProductName` - Product name
|
||||
|
||||
### Categories Table Schema
|
||||
|
||||
- `CategoryID` - Primary key
|
||||
- `CategoryName` - Category display name
|
||||
|
||||
## Example Output
|
||||
|
||||
### Monthly Consumption Report
|
||||
```
|
||||
📊 Monthly Consumption Report
|
||||
-----------------------------
|
||||
Generated: 2024-01-15 08:00
|
||||
|
||||
[Time Series Chart Image]
|
||||
|
||||
Total Revenue: $125,430
|
||||
Top Month: December ($18,500)
|
||||
Growth Rate: +12% MoM
|
||||
```
|
||||
|
||||
### Category Breakdown
|
||||
```
|
||||
📊 Product Category Distribution
|
||||
--------------------------------
|
||||
|
||||
[Donut Chart Image]
|
||||
|
||||
Electronics: 35%
|
||||
Clothing: 28%
|
||||
Home & Garden: 22%
|
||||
Other: 15%
|
||||
```
|
||||
|
||||
## Customization
|
||||
|
||||
### Adding New Reports
|
||||
|
||||
Create additional `.bas` files in the `bi.gbai` folder:
|
||||
|
||||
```basic
|
||||
' sales-by-region.bas
|
||||
SET SCHEDULE "0 9 * * 1" ' Every Monday at 9 AM
|
||||
|
||||
data = SELECT Region, SUM(Amount) as Total
|
||||
FROM Sales
|
||||
GROUP BY Region
|
||||
|
||||
img = CHART "bar", data
|
||||
SEND FILE img, "Weekly Regional Sales"
|
||||
```
|
||||
|
||||
### Customizing Delivery
|
||||
|
||||
Send reports to specific users or channels:
|
||||
|
||||
```basic
|
||||
' Send to specific user
|
||||
SEND FILE img TO "manager@company.com", "Weekly Report"
|
||||
|
||||
' Send to WhatsApp
|
||||
SEND FILE img TO "+1234567890", "Your monthly report"
|
||||
|
||||
' Send to team channel
|
||||
TALK TO "sales-team", img
|
||||
```
|
||||
|
||||
## Scheduling Options
|
||||
|
||||
| Schedule | Cron Expression | Description |
|
||||
|----------|-----------------|-------------|
|
||||
| Every minute | `1 * * * * *` | Testing/real-time |
|
||||
| Hourly | `0 0 * * * *` | Frequent updates |
|
||||
| Daily 8 AM | `0 0 8 * * *` | Morning reports |
|
||||
| Weekly Monday | `0 0 9 * * 1` | Weekly summaries |
|
||||
| Monthly 1st | `0 0 8 1 * *` | Monthly reports |
|
||||
|
||||
## Integration
|
||||
|
||||
### With CRM
|
||||
|
||||
```basic
|
||||
' Combine with CRM data
|
||||
opportunities = FIND "opportunities.csv"
|
||||
revenue = SELECT stage, SUM(amount) FROM opportunities GROUP BY stage
|
||||
|
||||
img = CHART "funnel", revenue
|
||||
SEND FILE img, "Sales Pipeline"
|
||||
```
|
||||
|
||||
### With ERP
|
||||
|
||||
```basic
|
||||
' Inventory analysis
|
||||
inventory = FIND "inventory.csv"
|
||||
low_stock = SELECT product, quantity FROM inventory WHERE quantity < reorder_level
|
||||
|
||||
img = CHART "bar", low_stock
|
||||
SEND FILE img, "Low Stock Alert"
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Schedule appropriately** - Don't run heavy reports too frequently
|
||||
2. **Filter data** - Use date ranges to limit data volume
|
||||
3. **Cache results** - Store computed metrics for faster access
|
||||
4. **Log activities** - Track report generation for auditing
|
||||
5. **Handle errors** - Wrap queries in error handling
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Issue | Solution |
|
||||
|-------|----------|
|
||||
| Empty charts | Verify data source has records |
|
||||
| Schedule not running | Check cron syntax |
|
||||
| Slow reports | Add date filters, optimize queries |
|
||||
| Missing data | Verify JOIN conditions |
|
||||
|
||||
## Related Templates
|
||||
|
||||
- `analytics.gbai` - Platform analytics
|
||||
- `talk-to-data.gbai` - Natural language data queries
|
||||
- `crm.gbai` - CRM with built-in reporting
|
||||
|
||||
## License
|
||||
|
||||
AGPL-3.0 - Part of General Bots Open Source Platform.
|
||||
|
||||
---
|
||||
|
||||
**Pragmatismo** - General Bots
|
||||
275
templates/crawler.gbai/README.md
Normal file
275
templates/crawler.gbai/README.md
Normal file
|
|
@ -0,0 +1,275 @@
|
|||
# Web Crawler Template (crawler.gbai)
|
||||
|
||||
A General Bots template for automated web crawling and content extraction for knowledge base population.
|
||||
|
||||
## Overview
|
||||
|
||||
The Crawler template enables your bot to automatically fetch, parse, and index web content. It's designed for building knowledge bases from websites, monitoring web pages for changes, and extracting structured data from online sources.
|
||||
|
||||
## Features
|
||||
|
||||
- **Automated Web Scraping** - Fetch and parse web pages automatically
|
||||
- **Document Mode** - Answer questions based on crawled content
|
||||
- **Configurable Depth** - Control how many pages to crawl
|
||||
- **Content Indexing** - Automatically add content to knowledge base
|
||||
- **LLM Integration** - Use AI to understand and summarize crawled content
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
crawler.gbai/
|
||||
├── README.md
|
||||
├── crawler.gbkb/ # Knowledge base for crawled content
|
||||
│ └── docs/ # Indexed documents
|
||||
└── crawler.gbot/
|
||||
└── config.csv # Crawler configuration
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
Configure the crawler in `crawler.gbot/config.csv`:
|
||||
|
||||
| Parameter | Description | Example |
|
||||
|-----------|-------------|---------|
|
||||
| `Website` | Target URL to crawl | `https://pragmatismo.com.br/` |
|
||||
| `website Max Documents` | Maximum pages to crawl | `2` |
|
||||
| `Answer Mode` | How to respond to queries | `document` |
|
||||
| `Theme Color` | UI theme color | `purple` |
|
||||
| `LLM Provider` | AI provider for processing | `openai` |
|
||||
|
||||
### Example config.csv
|
||||
|
||||
```csv
|
||||
name,value
|
||||
Website,https://pragmatismo.com.br/
|
||||
website Max Documents,2
|
||||
Answer Mode,document
|
||||
Theme Color,purple
|
||||
LLM Provider,openai
|
||||
```
|
||||
|
||||
## How It Works
|
||||
|
||||
1. **Initialization** - Bot reads the target website from configuration
|
||||
2. **Crawling** - Fetches pages starting from the root URL
|
||||
3. **Extraction** - Parses HTML and extracts meaningful text content
|
||||
4. **Indexing** - Stores content in the knowledge base for RAG
|
||||
5. **Q&A** - Users can ask questions about the crawled content
|
||||
|
||||
## Usage
|
||||
|
||||
### Basic Setup
|
||||
|
||||
1. Copy the template to your bot's packages directory:
|
||||
|
||||
```bash
|
||||
cp -r templates/crawler.gbai /path/to/your/bot/packages/
|
||||
```
|
||||
|
||||
2. Edit `crawler.gbot/config.csv` with your target website:
|
||||
|
||||
```csv
|
||||
name,value
|
||||
Website,https://your-website.com/
|
||||
website Max Documents,10
|
||||
Answer Mode,document
|
||||
```
|
||||
|
||||
3. Deploy and the bot will automatically crawl the configured site.
|
||||
|
||||
### Querying Crawled Content
|
||||
|
||||
Once crawled, users can ask questions naturally:
|
||||
|
||||
- "What services does the company offer?"
|
||||
- "Tell me about the pricing"
|
||||
- "Summarize the about page"
|
||||
- "What are the main features?"
|
||||
|
||||
### Answer Modes
|
||||
|
||||
| Mode | Behavior |
|
||||
|------|----------|
|
||||
| `document` | Answers strictly based on crawled content |
|
||||
| `hybrid` | Combines crawled content with general knowledge |
|
||||
| `summary` | Provides concise summaries of relevant pages |
|
||||
|
||||
## Advanced Configuration
|
||||
|
||||
### Limiting Crawl Scope
|
||||
|
||||
Control which pages are crawled:
|
||||
|
||||
```csv
|
||||
name,value
|
||||
Website,https://example.com/docs/
|
||||
website Max Documents,50
|
||||
Website Include Pattern,/docs/*
|
||||
Website Exclude Pattern,/docs/archive/*
|
||||
```
|
||||
|
||||
### Scheduling Recrawls
|
||||
|
||||
Set up periodic recrawling to keep content fresh:
|
||||
|
||||
```csv
|
||||
name,value
|
||||
Website Refresh Schedule,0 0 * * 0
|
||||
```
|
||||
|
||||
This example recrawls every Sunday at midnight.
|
||||
|
||||
### Authentication
|
||||
|
||||
For sites requiring authentication:
|
||||
|
||||
```csv
|
||||
name,value
|
||||
Website Auth Type,basic
|
||||
Website Username,user
|
||||
Website Password,secret
|
||||
```
|
||||
|
||||
## Customization
|
||||
|
||||
### Creating Custom Crawl Logic
|
||||
|
||||
Create a BASIC dialog for custom crawling:
|
||||
|
||||
```basic
|
||||
' custom-crawl.bas
|
||||
urls = ["https://site1.com", "https://site2.com", "https://site3.com"]
|
||||
|
||||
FOR EACH url IN urls
|
||||
content = GET url
|
||||
|
||||
IF content THEN
|
||||
SAVE "crawled_pages.csv", url, content, NOW()
|
||||
SET CONTEXT content
|
||||
END IF
|
||||
NEXT
|
||||
|
||||
TALK "Crawled " + UBOUND(urls) + " pages successfully."
|
||||
```
|
||||
|
||||
### Processing Crawled Content
|
||||
|
||||
Use LLM to process and structure crawled data:
|
||||
|
||||
```basic
|
||||
' process-crawled.bas
|
||||
pages = FIND "crawled_pages.csv"
|
||||
|
||||
FOR EACH page IN pages
|
||||
summary = LLM "Summarize this content in 3 bullet points: " + page.content
|
||||
|
||||
WITH processed
|
||||
url = page.url
|
||||
summary = summary
|
||||
processed_at = NOW()
|
||||
END WITH
|
||||
|
||||
SAVE "processed_content.csv", processed
|
||||
NEXT
|
||||
```
|
||||
|
||||
### Extracting Structured Data
|
||||
|
||||
Extract specific information from pages:
|
||||
|
||||
```basic
|
||||
' extract-products.bas
|
||||
SET CONTEXT "You are a data extraction assistant. Extract product information as JSON."
|
||||
|
||||
page_content = GET "https://store.example.com/products"
|
||||
|
||||
products = LLM "Extract all products with name, price, and description as JSON array: " + page_content
|
||||
|
||||
SAVE "products.json", products
|
||||
```
|
||||
|
||||
## Integration Examples
|
||||
|
||||
### With Knowledge Base
|
||||
|
||||
```basic
|
||||
' Add crawled content to KB
|
||||
content = GET "https://docs.example.com/api"
|
||||
|
||||
IF content THEN
|
||||
USE KB "api-docs.gbkb"
|
||||
ADD TO KB content, "API Documentation"
|
||||
END IF
|
||||
```
|
||||
|
||||
### With Notifications
|
||||
|
||||
```basic
|
||||
' Monitor for changes
|
||||
previous = GET BOT MEMORY "last_content"
|
||||
current = GET "https://news.example.com"
|
||||
|
||||
IF current <> previous THEN
|
||||
SEND EMAIL "admin@company.com", "Website Changed", "The monitored page has been updated."
|
||||
SET BOT MEMORY "last_content", current
|
||||
END IF
|
||||
```
|
||||
|
||||
### With Data Analysis
|
||||
|
||||
```basic
|
||||
' Analyze competitor pricing
|
||||
competitor_page = GET "https://competitor.com/pricing"
|
||||
|
||||
analysis = LLM "Compare this pricing to our prices and identify opportunities: " + competitor_page
|
||||
|
||||
TALK analysis
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Respect robots.txt** - Only crawl pages allowed by the site's robots.txt
|
||||
2. **Rate limiting** - Don't overwhelm target servers with requests
|
||||
3. **Set reasonable limits** - Start with low `Max Documents` values
|
||||
4. **Monitor content quality** - Review crawled content for accuracy
|
||||
5. **Keep content fresh** - Schedule periodic recrawls for dynamic sites
|
||||
6. **Handle errors gracefully** - Implement retry logic for failed requests
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Issue | Cause | Solution |
|
||||
|-------|-------|----------|
|
||||
| No content indexed | Invalid URL | Verify the Website URL is accessible |
|
||||
| Partial content | Max Documents too low | Increase the limit in config |
|
||||
| Stale answers | Content not refreshed | Set up scheduled recrawls |
|
||||
| Authentication errors | Missing credentials | Add auth settings to config |
|
||||
| Timeout errors | Slow target site | Increase timeout settings |
|
||||
|
||||
## Limitations
|
||||
|
||||
- JavaScript-rendered content may not be fully captured
|
||||
- Some sites block automated crawlers
|
||||
- Large sites may take significant time to fully crawl
|
||||
- Dynamic content may require special handling
|
||||
|
||||
## Related Templates
|
||||
|
||||
- `ai-search.gbai` - AI-powered document search
|
||||
- `talk-to-data.gbai` - Natural language data queries
|
||||
- `law.gbai` - Legal document processing with similar RAG approach
|
||||
|
||||
## Use Cases
|
||||
|
||||
- **Documentation Bots** - Index product docs for support
|
||||
- **Competitive Intelligence** - Monitor competitor websites
|
||||
- **News Aggregation** - Collect news from multiple sources
|
||||
- **Research Assistants** - Build knowledge bases from academic sources
|
||||
- **FAQ Generators** - Extract FAQs from help sites
|
||||
|
||||
## License
|
||||
|
||||
AGPL-3.0 - Part of General Bots Open Source Platform.
|
||||
|
||||
---
|
||||
|
||||
**Pragmatismo** - General Bots
|
||||
307
templates/crm/contacts.gbai/README.md
Normal file
307
templates/crm/contacts.gbai/README.md
Normal file
|
|
@ -0,0 +1,307 @@
|
|||
# CRM Contacts Template (contacts.gbai)
|
||||
|
||||
A General Bots template for managing contact directories with search, add, update, and company management capabilities.
|
||||
|
||||
## Overview
|
||||
|
||||
The Contacts template provides a complete contact management system with natural language interaction. Users can add new contacts, search the directory, manage company records, and track contact history through conversational AI.
|
||||
|
||||
## Features
|
||||
|
||||
- **Contact Management** - Add, update, search, and delete contacts
|
||||
- **Company Records** - Automatic company creation and association
|
||||
- **Flexible Search** - Search by name, email, company, or phone
|
||||
- **Activity Tracking** - Log all contact interactions
|
||||
- **Tag System** - Organize contacts with custom tags
|
||||
- **Export Capabilities** - Export contact lists in various formats
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
contacts.gbai/
|
||||
├── README.md
|
||||
├── contacts.gbdialog/
|
||||
│ ├── start.bas # Main entry point and tool registration
|
||||
│ ├── add-contact.bas # Add new contacts
|
||||
│ └── search-contact.bas # Search contact directory
|
||||
├── contacts.gbkb/ # Knowledge base for contact help
|
||||
└── contacts.gbot/
|
||||
└── config.csv # Bot configuration
|
||||
```
|
||||
|
||||
## Scripts
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `start.bas` | Initializes tools, sets context, and displays welcome menu |
|
||||
| `add-contact.bas` | Creates new contact records with validation |
|
||||
| `search-contact.bas` | Searches directory by multiple fields |
|
||||
|
||||
## Available Tools
|
||||
|
||||
The template registers these tools for LLM access:
|
||||
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `add-contact` | Add a new contact to the directory |
|
||||
| `search-contact` | Search contacts by any field |
|
||||
| `update-contact` | Modify existing contact information |
|
||||
| `list-contacts` | List all contacts with optional filters |
|
||||
| `add-company` | Create a new company record |
|
||||
| `contact-history` | View interaction history for a contact |
|
||||
|
||||
## Data Schema
|
||||
|
||||
### Contacts Table
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `contactid` | String | Unique identifier (CON-YYYYMMDD-XXXX) |
|
||||
| `firstname` | String | Contact's first name |
|
||||
| `lastname` | String | Contact's last name |
|
||||
| `fullname` | String | Combined full name |
|
||||
| `email` | Email | Email address |
|
||||
| `phone` | Phone | Phone number |
|
||||
| `companyname` | String | Associated company |
|
||||
| `jobtitle` | String | Job title or role |
|
||||
| `tags` | String | Comma-separated tags |
|
||||
| `notes` | String | Additional notes |
|
||||
| `createdby` | String | User who created the record |
|
||||
| `createdat` | DateTime | Creation timestamp |
|
||||
|
||||
### Companies Table
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `companyid` | String | Unique identifier |
|
||||
| `name` | String | Company name |
|
||||
| `createdat` | DateTime | Creation timestamp |
|
||||
|
||||
### Activities Table
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `contactid` | String | Related contact ID |
|
||||
| `action` | String | Action description |
|
||||
| `createdby` | String | User who performed action |
|
||||
| `createdat` | DateTime | Activity timestamp |
|
||||
|
||||
## Usage
|
||||
|
||||
### Adding a Contact
|
||||
|
||||
Users can add contacts naturally:
|
||||
|
||||
- "Add John Smith from Acme Corp"
|
||||
- "Create a new contact for jane@company.com"
|
||||
- "Add contact: Mike Johnson, Sales Manager at TechCo"
|
||||
|
||||
Or provide structured input:
|
||||
|
||||
```
|
||||
First Name: John
|
||||
Last Name: Smith
|
||||
Email: john.smith@acme.com
|
||||
Phone: +1-555-123-4567
|
||||
Company: Acme Corporation
|
||||
Job Title: VP of Sales
|
||||
Tags: customer, vip
|
||||
Notes: Met at trade show
|
||||
```
|
||||
|
||||
### Searching Contacts
|
||||
|
||||
Search using natural language:
|
||||
|
||||
- "Find contacts at Acme"
|
||||
- "Search for John"
|
||||
- "Look up john.smith@acme.com"
|
||||
- "Find all VIP contacts"
|
||||
|
||||
Search filters:
|
||||
|
||||
| Filter | Example |
|
||||
|--------|---------|
|
||||
| By name | "search John Smith" |
|
||||
| By email | "search john@company.com" |
|
||||
| By company | "find contacts at Microsoft" |
|
||||
| By phone | "lookup +1-555-1234" |
|
||||
| By tag | "show all VIP contacts" |
|
||||
|
||||
### Managing Companies
|
||||
|
||||
Companies are auto-created when adding contacts:
|
||||
|
||||
```basic
|
||||
' When adding a contact with a new company
|
||||
IF companyname THEN
|
||||
existingcompany = FIND "companies.csv", "name=" + companyname
|
||||
IF COUNT(existingcompany) = 0 THEN
|
||||
' Auto-create company record
|
||||
SAVE "companies.csv", companyid, companyname, createdat
|
||||
END IF
|
||||
END IF
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
Configure in `contacts.gbot/config.csv`:
|
||||
|
||||
| Parameter | Description | Example |
|
||||
|-----------|-------------|---------|
|
||||
| `Theme Color` | UI accent color | `blue` |
|
||||
| `Default Tags` | Auto-applied tags | `new,prospect` |
|
||||
| `Require Email` | Email required? | `true` |
|
||||
| `Duplicate Check` | Check for duplicates | `true` |
|
||||
|
||||
## Customization
|
||||
|
||||
### Adding Custom Fields
|
||||
|
||||
Extend the contact schema in `add-contact.bas`:
|
||||
|
||||
```basic
|
||||
PARAM department AS STRING LIKE "Engineering" DESCRIPTION "Department name" OPTIONAL
|
||||
PARAM linkedin AS STRING LIKE "linkedin.com/in/john" DESCRIPTION "LinkedIn profile" OPTIONAL
|
||||
|
||||
' Include in save
|
||||
SAVE "contacts.csv", contactid, firstname, lastname, fullname, email, phone,
|
||||
companyname, jobtitle, department, linkedin, tags, notes, createdby, createdat
|
||||
```
|
||||
|
||||
### Custom Search Filters
|
||||
|
||||
Add specialized search in `search-contact.bas`:
|
||||
|
||||
```basic
|
||||
IF searchby = "department" THEN
|
||||
results = FIND "contacts.csv", "department LIKE " + searchterm
|
||||
END IF
|
||||
|
||||
IF searchby = "recent" THEN
|
||||
cutoff = DATEADD(NOW(), -7, "day")
|
||||
results = FIND "contacts.csv", "createdat >= " + cutoff
|
||||
END IF
|
||||
```
|
||||
|
||||
### Integration with Email
|
||||
|
||||
Send welcome emails to new contacts:
|
||||
|
||||
```basic
|
||||
' In add-contact.bas after SAVE
|
||||
IF email THEN
|
||||
subject = "Thank you for connecting!"
|
||||
body = "Hi " + firstname + ", we look forward to working with you."
|
||||
SEND EMAIL email, subject, body
|
||||
END IF
|
||||
```
|
||||
|
||||
### Integration with CRM Pipeline
|
||||
|
||||
Connect contacts to leads:
|
||||
|
||||
```basic
|
||||
' Convert contact to lead
|
||||
PARAM convert_to_lead AS BOOLEAN DESCRIPTION "Create lead from contact" OPTIONAL
|
||||
|
||||
IF convert_to_lead THEN
|
||||
WITH new_lead
|
||||
id = FORMAT(GUID())
|
||||
name = fullname
|
||||
email = email
|
||||
phone = phone
|
||||
company = companyname
|
||||
source = "contact_conversion"
|
||||
status = "new"
|
||||
created_at = NOW()
|
||||
END WITH
|
||||
|
||||
SAVE "leads.csv", new_lead
|
||||
TALK "Lead created from contact: " + fullname
|
||||
END IF
|
||||
```
|
||||
|
||||
## Example Conversations
|
||||
|
||||
### Adding a Contact
|
||||
```
|
||||
User: Add a new contact
|
||||
Bot: I'll help you add a new contact. What is their first name?
|
||||
User: Sarah
|
||||
Bot: And their last name?
|
||||
User: Johnson
|
||||
Bot: What is Sarah's email address?
|
||||
User: sarah.johnson@techstartup.io
|
||||
Bot: Phone number? (optional)
|
||||
User: 555-987-6543
|
||||
Bot: What company does Sarah work for?
|
||||
User: TechStartup Inc
|
||||
Bot: What is her job title?
|
||||
User: CTO
|
||||
Bot: ✅ Contact added: Sarah Johnson
|
||||
ID: CON-20240115-4821
|
||||
Email: sarah.johnson@techstartup.io
|
||||
Phone: 555-987-6543
|
||||
Company: TechStartup Inc
|
||||
Title: CTO
|
||||
```
|
||||
|
||||
### Searching Contacts
|
||||
```
|
||||
User: Find contacts at TechStartup
|
||||
Bot: Found 2 contact(s):
|
||||
---
|
||||
**Sarah Johnson**
|
||||
sarah.johnson@techstartup.io
|
||||
555-987-6543
|
||||
TechStartup Inc
|
||||
CTO
|
||||
ID: CON-20240115-4821
|
||||
---
|
||||
**Mike Chen**
|
||||
mike.chen@techstartup.io
|
||||
TechStartup Inc
|
||||
Developer
|
||||
ID: CON-20240110-3392
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Validate input** - Use `PARAM` type validation for email and phone
|
||||
2. **Check duplicates** - Search before creating to avoid duplicates
|
||||
3. **Log activities** - Track all changes for audit trail
|
||||
4. **Use tags** - Organize contacts with meaningful tags
|
||||
5. **Keep notes** - Add context about how/where you met contacts
|
||||
6. **Regular cleanup** - Archive inactive contacts periodically
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Issue | Solution |
|
||||
|-------|----------|
|
||||
| Duplicate contacts | Enable duplicate checking in config |
|
||||
| Search returns nothing | Try broader search terms |
|
||||
| Company not linked | Ensure company name matches exactly |
|
||||
| Missing activities | Check activity logging is enabled |
|
||||
|
||||
## Related Templates
|
||||
|
||||
- `crm.gbai` - Full CRM with leads, opportunities, and pipeline
|
||||
- `marketing.gbai` - Marketing automation with contact segmentation
|
||||
- `office.gbai` - Office productivity with contact directory
|
||||
|
||||
## Use Cases
|
||||
|
||||
- **Sales Teams** - Manage prospect and customer contacts
|
||||
- **HR Departments** - Employee and candidate directories
|
||||
- **Event Management** - Attendee and speaker contacts
|
||||
- **Networking** - Professional contact management
|
||||
- **Customer Support** - Customer contact lookup
|
||||
|
||||
## License
|
||||
|
||||
AGPL-3.0 - Part of General Bots Open Source Platform.
|
||||
|
||||
---
|
||||
|
||||
**Pragmatismo** - General Bots
|
||||
425
templates/integration/api-client.gbai/README.md
Normal file
425
templates/integration/api-client.gbai/README.md
Normal file
|
|
@ -0,0 +1,425 @@
|
|||
# API Client Template (api-client.gbai)
|
||||
|
||||
A General Bots template demonstrating REST API integration patterns for connecting to external services and data sources.
|
||||
|
||||
## Overview
|
||||
|
||||
The API Client template provides examples and patterns for integrating General Bots with external REST APIs. It includes examples for weather services, Microsoft Partner Center integration, and general HTTP request patterns that can be adapted for any API.
|
||||
|
||||
## Features
|
||||
|
||||
- **REST API Integration** - GET, POST, PUT, DELETE request patterns
|
||||
- **Authentication** - OAuth, Bearer tokens, API keys
|
||||
- **Header Management** - Custom headers for API requirements
|
||||
- **Pagination Support** - Handle paginated API responses
|
||||
- **Data Synchronization** - Sync external data to local tables
|
||||
- **Scheduled Jobs** - Automated API polling and sync
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
api-client.gbai/
|
||||
├── README.md
|
||||
├── api-client.gbdialog/
|
||||
│ ├── climate.bas # Weather API example
|
||||
│ └── msft-partner-center.bas # Microsoft Partner Center integration
|
||||
└── api-client.gbot/
|
||||
└── config.csv # Bot configuration
|
||||
```
|
||||
|
||||
## Scripts
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `climate.bas` | Weather API tool for getting current conditions |
|
||||
| `msft-partner-center.bas` | Full Microsoft Partner Center billing sync |
|
||||
|
||||
## Basic API Patterns
|
||||
|
||||
### Simple GET Request
|
||||
|
||||
```basic
|
||||
' Get data from an API
|
||||
response = GET "https://api.example.com/data"
|
||||
|
||||
IF response THEN
|
||||
TALK "Data received: " + response.value
|
||||
ELSE
|
||||
TALK "Failed to fetch data"
|
||||
END IF
|
||||
```
|
||||
|
||||
### POST Request with Body
|
||||
|
||||
```basic
|
||||
' Send data to an API
|
||||
SET HEADER "Content-Type" AS "application/json"
|
||||
|
||||
payload = {"name": "John", "email": "john@example.com"}
|
||||
response = POST "https://api.example.com/users", payload
|
||||
|
||||
IF response.id THEN
|
||||
TALK "User created with ID: " + response.id
|
||||
END IF
|
||||
```
|
||||
|
||||
### PUT Request for Updates
|
||||
|
||||
```basic
|
||||
' Update existing resource
|
||||
SET HEADER "Content-Type" AS "application/json"
|
||||
|
||||
updates = {"status": "active", "role": "admin"}
|
||||
response = PUT "https://api.example.com/users/123", updates
|
||||
|
||||
TALK "User updated: " + response.status
|
||||
```
|
||||
|
||||
### DELETE Request
|
||||
|
||||
```basic
|
||||
' Delete a resource
|
||||
response = DELETE "https://api.example.com/users/123"
|
||||
|
||||
IF response.deleted THEN
|
||||
TALK "User deleted successfully"
|
||||
END IF
|
||||
```
|
||||
|
||||
## Authentication Patterns
|
||||
|
||||
### API Key Authentication
|
||||
|
||||
```basic
|
||||
SET HEADER "X-API-Key" AS "your-api-key-here"
|
||||
|
||||
response = GET "https://api.example.com/protected-resource"
|
||||
```
|
||||
|
||||
### Bearer Token Authentication
|
||||
|
||||
```basic
|
||||
SET HEADER "Authorization" AS "Bearer " + access_token
|
||||
|
||||
response = GET "https://api.example.com/user/profile"
|
||||
```
|
||||
|
||||
### OAuth 2.0 Token Exchange
|
||||
|
||||
```basic
|
||||
' Get OAuth token
|
||||
SET HEADER "Content-Type" AS "application/x-www-form-urlencoded"
|
||||
|
||||
tokenResponse = POST "https://auth.example.com/oauth/token",
|
||||
"grant_type=client_credentials&client_id=" + clientId +
|
||||
"&client_secret=" + clientSecret
|
||||
|
||||
access_token = tokenResponse.access_token
|
||||
|
||||
' Use token for API calls
|
||||
SET HEADER "Authorization" AS "Bearer " + access_token
|
||||
data = GET "https://api.example.com/resources"
|
||||
```
|
||||
|
||||
### Basic Authentication
|
||||
|
||||
```basic
|
||||
credentials = BASE64(username + ":" + password)
|
||||
SET HEADER "Authorization" AS "Basic " + credentials
|
||||
|
||||
response = GET "https://api.example.com/secure-endpoint"
|
||||
```
|
||||
|
||||
## Weather API Example
|
||||
|
||||
The `climate.bas` tool demonstrates a simple API integration:
|
||||
|
||||
```basic
|
||||
PARAM location AS "The city and state, e.g. San Francisco, CA"
|
||||
PARAM unit AS "celsius", "fahrenheit"
|
||||
|
||||
DESCRIPTION "Get the current weather in a given location"
|
||||
|
||||
' Implementation would call weather API
|
||||
' response = GET "https://api.weather.com/current?location=" + location
|
||||
|
||||
RETURN weather_info
|
||||
```
|
||||
|
||||
### Usage
|
||||
|
||||
```
|
||||
User: What's the weather in New York?
|
||||
Bot: [Calls climate tool with location="New York"]
|
||||
Bot: It's currently 72°F and sunny in New York, NY.
|
||||
```
|
||||
|
||||
## Microsoft Partner Center Integration
|
||||
|
||||
The `msft-partner-center.bas` demonstrates a complex enterprise API integration:
|
||||
|
||||
### Features
|
||||
|
||||
- OAuth token authentication with Azure AD
|
||||
- Multi-resource synchronization (Customers, Subscriptions, Billing)
|
||||
- Scheduled execution
|
||||
- Pagination handling
|
||||
- Database table management
|
||||
|
||||
### Configuration
|
||||
|
||||
```basic
|
||||
' Required parameters
|
||||
tenantId = GET ENV "AZURE_TENANT_ID"
|
||||
clientId = GET ENV "AZURE_CLIENT_ID"
|
||||
clientSecret = GET ENV "AZURE_CLIENT_SECRET"
|
||||
host = "https://api.partnercenter.microsoft.com"
|
||||
```
|
||||
|
||||
### Scheduled Sync
|
||||
|
||||
```basic
|
||||
SET SCHEDULE "1 * * * * *" ' Run periodically
|
||||
|
||||
' Set required headers
|
||||
SET HEADER "MS-Contract-Version" AS "v1"
|
||||
SET HEADER "MS-CorrelationId" AS UUID()
|
||||
SET HEADER "MS-RequestId" AS UUID()
|
||||
SET HEADER "MS-PartnerCenter-Application" AS "General Bots"
|
||||
SET HEADER "X-Locale" AS "en-US"
|
||||
```
|
||||
|
||||
### Sync Customers and Subscriptions
|
||||
|
||||
```basic
|
||||
SET PAGE MODE "none"
|
||||
customers = GET host + "/v1/customers?size=20000"
|
||||
|
||||
MERGE "Customers" WITH customers.items BY "Id"
|
||||
|
||||
FOR EACH customer IN customers
|
||||
subs = GET host + "/v1/customers/" + customer.id + "/subscriptions"
|
||||
MERGE "Subscriptions" WITH subs.items BY "Id"
|
||||
END FOR
|
||||
```
|
||||
|
||||
### Billing Data Sync
|
||||
|
||||
```basic
|
||||
SET PAGE MODE "auto"
|
||||
billingItems = GET host + "/v1/invoices/unbilled/lineitems" +
|
||||
"?provider=onetime&invoicelineitemtype=usagelineitems¤cycode=USD"
|
||||
|
||||
FOR EACH item IN billingItems
|
||||
SAVE "Billing", item.alternateId, item.customerId, item.productName,
|
||||
item.quantity, item.unitPrice, item.subtotal, item.chargeStartDate
|
||||
END FOR
|
||||
```
|
||||
|
||||
### Table Definitions
|
||||
|
||||
```basic
|
||||
TABLE Billing
|
||||
CustomerId Customers
|
||||
ResourceGroup string(200)
|
||||
CustomerName string(400)
|
||||
ProductName string(400)
|
||||
Quantity double
|
||||
UnitPrice double
|
||||
Subtotal double
|
||||
ChargeStartDate date
|
||||
ChargeEndDate date
|
||||
END TABLE
|
||||
|
||||
TABLE Customers
|
||||
TenantId guid
|
||||
CompanyName string(100)
|
||||
Id guid
|
||||
END TABLE
|
||||
|
||||
TABLE Subscriptions
|
||||
CustomerId Customers
|
||||
Id guid
|
||||
OfferName string(50)
|
||||
END TABLE
|
||||
```
|
||||
|
||||
## Custom API Integration
|
||||
|
||||
### Creating Your Own API Client
|
||||
|
||||
```basic
|
||||
' my-api-client.bas
|
||||
PARAM resource AS STRING LIKE "users" DESCRIPTION "API resource to fetch"
|
||||
PARAM filters AS STRING LIKE "status=active" DESCRIPTION "Query filters" OPTIONAL
|
||||
|
||||
DESCRIPTION "Fetch data from custom API"
|
||||
|
||||
' Configuration
|
||||
api_base = GET ENV "MY_API_BASE_URL"
|
||||
api_key = GET ENV "MY_API_KEY"
|
||||
|
||||
' Set authentication
|
||||
SET HEADER "Authorization" AS "Bearer " + api_key
|
||||
SET HEADER "Content-Type" AS "application/json"
|
||||
|
||||
' Build URL
|
||||
url = api_base + "/" + resource
|
||||
IF filters THEN
|
||||
url = url + "?" + filters
|
||||
END IF
|
||||
|
||||
' Make request
|
||||
response = GET url
|
||||
|
||||
IF response.error THEN
|
||||
RETURN {"success": false, "error": response.error}
|
||||
END IF
|
||||
|
||||
RETURN {"success": true, "data": response.data, "count": UBOUND(response.data)}
|
||||
```
|
||||
|
||||
### Handling Pagination
|
||||
|
||||
```basic
|
||||
' paginated-fetch.bas
|
||||
PARAM endpoint AS STRING DESCRIPTION "API endpoint"
|
||||
|
||||
DESCRIPTION "Fetch all pages from a paginated API"
|
||||
|
||||
all_results = []
|
||||
page = 1
|
||||
has_more = true
|
||||
|
||||
DO WHILE has_more
|
||||
response = GET endpoint + "?page=" + page + "&per_page=100"
|
||||
|
||||
IF response.data THEN
|
||||
all_results = MERGE all_results, response.data
|
||||
|
||||
IF UBOUND(response.data) < 100 THEN
|
||||
has_more = false
|
||||
ELSE
|
||||
page = page + 1
|
||||
END IF
|
||||
ELSE
|
||||
has_more = false
|
||||
END IF
|
||||
LOOP
|
||||
|
||||
RETURN all_results
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
|
||||
```basic
|
||||
' api-with-retry.bas
|
||||
PARAM url AS STRING DESCRIPTION "API URL to call"
|
||||
PARAM max_retries AS INTEGER LIKE 3 DESCRIPTION "Maximum retry attempts"
|
||||
|
||||
DESCRIPTION "API call with automatic retry on failure"
|
||||
|
||||
retries = 0
|
||||
success = false
|
||||
|
||||
DO WHILE retries < max_retries AND NOT success
|
||||
response = GET url
|
||||
|
||||
IF response.error THEN
|
||||
retries = retries + 1
|
||||
WAIT retries * 2 ' Exponential backoff
|
||||
ELSE
|
||||
success = true
|
||||
END IF
|
||||
LOOP
|
||||
|
||||
IF success THEN
|
||||
RETURN response
|
||||
ELSE
|
||||
RETURN {"error": "Max retries exceeded", "last_error": response.error}
|
||||
END IF
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
Configure in `api-client.gbot/config.csv`:
|
||||
|
||||
| Parameter | Description | Example |
|
||||
|-----------|-------------|---------|
|
||||
| `API Base URL` | Default API endpoint | `https://api.example.com` |
|
||||
| `API Timeout` | Request timeout in seconds | `30` |
|
||||
| `Retry Count` | Number of retry attempts | `3` |
|
||||
| `Log Requests` | Enable request logging | `true` |
|
||||
|
||||
### Environment Variables
|
||||
|
||||
Store sensitive values as environment variables:
|
||||
|
||||
```bash
|
||||
MY_API_KEY=your-api-key
|
||||
MY_API_SECRET=your-secret
|
||||
AZURE_TENANT_ID=your-tenant-id
|
||||
AZURE_CLIENT_ID=your-client-id
|
||||
AZURE_CLIENT_SECRET=your-client-secret
|
||||
```
|
||||
|
||||
Access in BASIC:
|
||||
|
||||
```basic
|
||||
api_key = GET ENV "MY_API_KEY"
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Secure credentials** - Never hardcode API keys; use environment variables
|
||||
2. **Handle errors** - Always check for error responses
|
||||
3. **Rate limiting** - Respect API rate limits with delays
|
||||
4. **Pagination** - Handle paginated responses properly
|
||||
5. **Logging** - Log API calls for debugging
|
||||
6. **Timeouts** - Set appropriate timeout values
|
||||
7. **Retries** - Implement retry logic for transient failures
|
||||
8. **Caching** - Cache responses when appropriate
|
||||
|
||||
## Common HTTP Headers
|
||||
|
||||
| Header | Purpose | Example |
|
||||
|--------|---------|---------|
|
||||
| `Content-Type` | Request body format | `application/json` |
|
||||
| `Accept` | Expected response format | `application/json` |
|
||||
| `Authorization` | Authentication | `Bearer token` |
|
||||
| `X-API-Key` | API key auth | `your-key` |
|
||||
| `User-Agent` | Client identification | `GeneralBots/1.0` |
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Issue | Cause | Solution |
|
||||
|-------|-------|----------|
|
||||
| 401 Unauthorized | Invalid credentials | Check API key/token |
|
||||
| 403 Forbidden | Missing permissions | Verify API access rights |
|
||||
| 404 Not Found | Wrong endpoint | Verify URL path |
|
||||
| 429 Too Many Requests | Rate limited | Add delays between requests |
|
||||
| 500 Server Error | API issue | Retry with backoff |
|
||||
| Timeout | Slow API | Increase timeout setting |
|
||||
|
||||
## Related Templates
|
||||
|
||||
- `public-apis.gbai` - Pre-built integrations for public APIs
|
||||
- `bling.gbai` - ERP API integration example
|
||||
- `llm-server.gbai` - Building your own API endpoints
|
||||
- `crm.gbai` - CRM with external API sync
|
||||
|
||||
## Use Cases
|
||||
|
||||
- **Data Synchronization** - Sync data from external systems
|
||||
- **Service Integration** - Connect to SaaS platforms
|
||||
- **Automation** - Automate cross-system workflows
|
||||
- **Monitoring** - Poll external systems for changes
|
||||
- **Reporting** - Aggregate data from multiple APIs
|
||||
|
||||
## License
|
||||
|
||||
AGPL-3.0 - Part of General Bots Open Source Platform.
|
||||
|
||||
---
|
||||
|
||||
**Pragmatismo** - General Bots
|
||||
316
templates/law.gbai/README.md
Normal file
316
templates/law.gbai/README.md
Normal file
|
|
@ -0,0 +1,316 @@
|
|||
# Legal Document Processing Template (law.gbai)
|
||||
|
||||
A General Bots template for legal case management, document analysis, and AI-powered legal Q&A.
|
||||
|
||||
## Overview
|
||||
|
||||
The Law template enables legal professionals to load case documents, query case information using natural language, and get AI-assisted analysis of legal materials. It's designed for law firms, legal departments, and compliance teams who need efficient document-based legal research.
|
||||
|
||||
## Features
|
||||
|
||||
- **Case Document Loading** - Load and index PDF case files by case number
|
||||
- **Document Q&A** - Ask questions about loaded legal documents
|
||||
- **Context-Aware Responses** - AI responses grounded in actual case content
|
||||
- **Case Summarization** - Generate summaries of case documents
|
||||
- **Multi-Document Support** - Work with multiple cases simultaneously
|
||||
- **Audit Trail** - Track all document access and queries
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
law.gbai/
|
||||
├── README.md
|
||||
├── law.gbdialog/
|
||||
│ └── case.bas # Case loading and query handler
|
||||
├── law.gbdrive/ # Case document storage
|
||||
│ └── (case-*.pdf) # Case PDF files
|
||||
├── law.gbkb/ # Knowledge base for legal reference
|
||||
└── law.gbot/
|
||||
└── config.csv # Bot configuration
|
||||
```
|
||||
|
||||
## Scripts
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `case.bas` | Loads case documents by number and enables document-based Q&A |
|
||||
|
||||
## How It Works
|
||||
|
||||
### Case Loading Flow
|
||||
|
||||
1. User provides a case number (e.g., "12345")
|
||||
2. Bot searches for `case-12345.pdf` in the drive
|
||||
3. Document content is extracted and set as context
|
||||
4. Answer mode switches to "document" for grounded responses
|
||||
5. User can ask questions about the loaded case
|
||||
|
||||
### Code Example
|
||||
|
||||
```basic
|
||||
PARAM cod AS STRING LIKE "12345" DESCRIPTION "Case number to load and query"
|
||||
|
||||
DESCRIPTION "Load a legal case document by case number for Q&A and analysis"
|
||||
|
||||
text = GET "case-" + cod + ".pdf"
|
||||
|
||||
IF text THEN
|
||||
SET CONTEXT "Based on this document, answer the person's questions:\n\n" + text
|
||||
SET ANSWER MODE "document"
|
||||
TALK "Case ${cod} loaded. Ask me anything about the case or request a summary."
|
||||
ELSE
|
||||
TALK "Case not found. Please check the case number."
|
||||
END IF
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
Configure in `law.gbot/config.csv`:
|
||||
|
||||
| Parameter | Description | Example |
|
||||
|-----------|-------------|---------|
|
||||
| `Answer Mode` | Response grounding mode | `document` |
|
||||
| `Theme Color` | UI accent color | `navy` |
|
||||
| `LLM Provider` | AI provider | `openai` |
|
||||
| `Document Retention` | Days to keep loaded docs | `30` |
|
||||
| `Require Authentication` | Require user login | `true` |
|
||||
|
||||
## Usage
|
||||
|
||||
### Loading a Case
|
||||
|
||||
```
|
||||
User: Load case 12345
|
||||
Bot: Case 12345 loaded. Ask me anything about the case or request a summary.
|
||||
```
|
||||
|
||||
### Querying Case Content
|
||||
|
||||
```
|
||||
User: What are the main claims in this case?
|
||||
Bot: Based on the document, the main claims are:
|
||||
1. Breach of contract regarding the delivery terms in Section 3.2
|
||||
2. Failure to meet quality standards as specified in Exhibit A
|
||||
3. Request for damages in the amount of $250,000
|
||||
|
||||
User: Summarize the defendant's response
|
||||
Bot: The defendant argues that:
|
||||
- Delivery delays were caused by force majeure events
|
||||
- Quality standards were met according to third-party inspection
|
||||
- Damages claimed are excessive and not substantiated
|
||||
```
|
||||
|
||||
### Multiple Cases
|
||||
|
||||
```
|
||||
User: Load case 67890
|
||||
Bot: Case 67890 loaded. Previous case context cleared.
|
||||
|
||||
User: Compare this with case 12345
|
||||
Bot: I can only analyze the currently loaded case (67890).
|
||||
To compare cases, please use the case comparison feature.
|
||||
```
|
||||
|
||||
## Document Naming Convention
|
||||
|
||||
Case documents should follow this naming pattern:
|
||||
|
||||
```
|
||||
case-{case_number}.pdf
|
||||
```
|
||||
|
||||
Examples:
|
||||
- `case-12345.pdf`
|
||||
- `case-2024-CV-0001.pdf`
|
||||
- `case-APPEAL-789.pdf`
|
||||
|
||||
## Customization
|
||||
|
||||
### Adding Case Search
|
||||
|
||||
```basic
|
||||
' search-cases.bas
|
||||
PARAM query AS STRING DESCRIPTION "Search term for finding cases"
|
||||
|
||||
DESCRIPTION "Search for cases by party name, date, or keywords"
|
||||
|
||||
cases = FIND "case_index.csv", "content LIKE '%" + query + "%'"
|
||||
|
||||
IF UBOUND(cases) > 0 THEN
|
||||
TALK "Found " + UBOUND(cases) + " matching cases:"
|
||||
|
||||
FOR EACH c IN cases
|
||||
TALK "- Case " + c.case_number + ": " + c.title
|
||||
NEXT
|
||||
ELSE
|
||||
TALK "No cases found matching: " + query
|
||||
END IF
|
||||
```
|
||||
|
||||
### Case Summarization
|
||||
|
||||
```basic
|
||||
' summarize-case.bas
|
||||
PARAM cod AS STRING DESCRIPTION "Case number to summarize"
|
||||
|
||||
DESCRIPTION "Generate an executive summary of a legal case"
|
||||
|
||||
text = GET "case-" + cod + ".pdf"
|
||||
|
||||
IF text THEN
|
||||
summary = LLM "As a legal professional, provide an executive summary of this case including:
|
||||
1. Parties involved
|
||||
2. Key facts
|
||||
3. Legal issues
|
||||
4. Current status
|
||||
5. Next steps
|
||||
|
||||
Document: " + text
|
||||
|
||||
TALK "## Case " + cod + " Summary\n\n" + summary
|
||||
|
||||
' Save summary for future reference
|
||||
SAVE "case_summaries.csv", cod, summary, NOW()
|
||||
ELSE
|
||||
TALK "Case not found."
|
||||
END IF
|
||||
```
|
||||
|
||||
### Adding Document Types
|
||||
|
||||
Support additional legal document types:
|
||||
|
||||
```basic
|
||||
' load-document.bas
|
||||
PARAM doc_type AS STRING LIKE "contract" DESCRIPTION "Type: case, contract, brief, motion"
|
||||
PARAM doc_id AS STRING DESCRIPTION "Document identifier"
|
||||
|
||||
DESCRIPTION "Load various legal document types"
|
||||
|
||||
filename = doc_type + "-" + doc_id + ".pdf"
|
||||
text = GET filename
|
||||
|
||||
IF text THEN
|
||||
SET CONTEXT "This is a legal " + doc_type + ". Answer questions based on its content:\n\n" + text
|
||||
SET ANSWER MODE "document"
|
||||
TALK "Loaded " + doc_type + " " + doc_id + ". Ready for questions."
|
||||
ELSE
|
||||
TALK "Document not found: " + filename
|
||||
END IF
|
||||
```
|
||||
|
||||
### Compliance Logging
|
||||
|
||||
```basic
|
||||
' Add audit logging to case.bas
|
||||
IF text THEN
|
||||
' Log access for compliance
|
||||
WITH audit_entry
|
||||
timestamp = NOW()
|
||||
user = GET SESSION "user_email"
|
||||
case_number = cod
|
||||
action = "document_access"
|
||||
ip_address = GET SESSION "client_ip"
|
||||
END WITH
|
||||
|
||||
SAVE "legal_audit_log.csv", audit_entry
|
||||
|
||||
SET CONTEXT "Based on this document..." + text
|
||||
END IF
|
||||
```
|
||||
|
||||
## Integration Examples
|
||||
|
||||
### With Calendar
|
||||
|
||||
```basic
|
||||
' Schedule case deadlines
|
||||
deadline = LLM "Extract the next deadline date from this case: " + text
|
||||
|
||||
IF deadline THEN
|
||||
CREATE CALENDAR EVENT "Case " + cod + " Deadline", deadline
|
||||
TALK "Deadline added to calendar: " + deadline
|
||||
END IF
|
||||
```
|
||||
|
||||
### With Email
|
||||
|
||||
```basic
|
||||
' Email case summary to team
|
||||
summary = LLM "Summarize the key points of this case in 3 paragraphs: " + text
|
||||
|
||||
SEND EMAIL "legal-team@firm.com", "Case " + cod + " Summary", summary
|
||||
TALK "Summary sent to legal team."
|
||||
```
|
||||
|
||||
### With Document Generation
|
||||
|
||||
```basic
|
||||
' Generate response document
|
||||
response = LLM "Draft a formal response letter addressing the claims in this case: " + text
|
||||
|
||||
CREATE DRAFT response, "Response to Case " + cod
|
||||
TALK "Draft response created. Review in your documents."
|
||||
```
|
||||
|
||||
## Security Considerations
|
||||
|
||||
1. **Access Control** - Implement role-based access for sensitive cases
|
||||
2. **Audit Logging** - Log all document access for compliance
|
||||
3. **Data Encryption** - Enable encryption for stored documents
|
||||
4. **Session Timeout** - Configure appropriate session timeouts
|
||||
5. **Authentication** - Require strong authentication for legal systems
|
||||
6. **Data Retention** - Follow legal data retention requirements
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Organize documents** - Use consistent naming conventions
|
||||
2. **Index cases** - Maintain a searchable case index
|
||||
3. **Regular backups** - Back up case documents frequently
|
||||
4. **Version control** - Track document versions
|
||||
5. **Clear context** - Clear previous case context before loading new cases
|
||||
6. **Verify AI responses** - Always verify AI-generated legal content
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Issue | Cause | Solution |
|
||||
|-------|-------|----------|
|
||||
| Case not found | Wrong filename | Check naming convention |
|
||||
| Empty responses | Document not parsed | Verify PDF is text-based |
|
||||
| Slow loading | Large document | Consider document chunking |
|
||||
| Context errors | Multiple cases loaded | Clear context between cases |
|
||||
| Access denied | Missing permissions | Check user authentication |
|
||||
|
||||
## Limitations
|
||||
|
||||
- PDF documents must be text-based (not scanned images)
|
||||
- Very large documents may require chunking
|
||||
- Complex legal analysis should be verified by professionals
|
||||
- AI responses are assistive, not legal advice
|
||||
|
||||
## Related Templates
|
||||
|
||||
- `compliance/privacy.gbai` - Privacy and data protection
|
||||
- `compliance/hipaa-medical.gbai` - Healthcare compliance
|
||||
- `talk-to-data.gbai` - Natural language document queries
|
||||
- `ai-search.gbai` - AI-powered document search
|
||||
|
||||
## Use Cases
|
||||
|
||||
- **Case Research** - Quickly find relevant information in case files
|
||||
- **Document Review** - AI-assisted document analysis
|
||||
- **Client Communication** - Generate case status summaries
|
||||
- **Deadline Tracking** - Extract and track important dates
|
||||
- **Knowledge Management** - Build searchable legal knowledge bases
|
||||
|
||||
## Disclaimer
|
||||
|
||||
This template provides AI-assisted document analysis tools. It does not constitute legal advice. All AI-generated content should be reviewed by qualified legal professionals. Users are responsible for ensuring compliance with applicable legal and ethical standards.
|
||||
|
||||
## License
|
||||
|
||||
AGPL-3.0 - Part of General Bots Open Source Platform.
|
||||
|
||||
---
|
||||
|
||||
**Pragmatismo** - General Bots
|
||||
417
templates/llm-tools.gbai/README.md
Normal file
417
templates/llm-tools.gbai/README.md
Normal file
|
|
@ -0,0 +1,417 @@
|
|||
# LLM Tools Template (llm-tools.gbai)
|
||||
|
||||
A General Bots template demonstrating how to create and register custom tools (functions) that LLMs can call during conversations.
|
||||
|
||||
## Overview
|
||||
|
||||
The LLM Tools template shows how to extend your bot's capabilities by creating tools that the AI can invoke automatically. Tools enable the LLM to perform actions like database lookups, API calls, calculations, and more—all triggered naturally through conversation.
|
||||
|
||||
## Features
|
||||
|
||||
- **Custom Tool Registration** - Define tools the LLM can call
|
||||
- **Parameter Validation** - Type-safe tool parameters with descriptions
|
||||
- **Knowledge Base Integration** - Combine tools with RAG
|
||||
- **Natural Interaction** - Users don't need to know tool names
|
||||
- **Extensible Architecture** - Easy to add new tools
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
llm-tools.gbai/
|
||||
├── README.md
|
||||
├── llm-tools.gbdata/ # Data files for tools
|
||||
│ └── products.csv # Product catalog
|
||||
├── llm-tools.gbdialog/
|
||||
│ ├── start.bas # Main dialog with tool registration
|
||||
│ └── get-price.bas # Example tool implementation
|
||||
├── llm-tools.gbkb/ # Knowledge base
|
||||
│ └── products.gbkb/ # Product documentation
|
||||
└── llm-tools.gbot/
|
||||
└── config.csv # Bot configuration
|
||||
```
|
||||
|
||||
## Scripts
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `start.bas` | Registers tools, configures context, and sets system prompt |
|
||||
| `get-price.bas` | Example tool that looks up product prices |
|
||||
|
||||
## How Tools Work
|
||||
|
||||
### 1. Tool Registration
|
||||
|
||||
In `start.bas`, tools are registered with `ADD TOOL`:
|
||||
|
||||
```basic
|
||||
ADD TOOL "get-price"
|
||||
|
||||
USE KB "products.gbkb"
|
||||
|
||||
CLEAR SUGGESTIONS
|
||||
|
||||
ADD SUGGESTION "price" AS "Check product price"
|
||||
ADD SUGGESTION "products" AS "View products"
|
||||
ADD SUGGESTION "help" AS "How to use"
|
||||
|
||||
BEGIN TALK
|
||||
**Product Assistant**
|
||||
|
||||
I can help you check product prices and information.
|
||||
|
||||
Just ask me about any product and I'll look it up for you.
|
||||
END TALK
|
||||
|
||||
BEGIN SYSTEM PROMPT
|
||||
You are a product assistant with access to internal tools.
|
||||
|
||||
When get-price returns -1, the product does not exist.
|
||||
When asked about a price, use the get-price tool and return the result.
|
||||
|
||||
Do not expose tool names to users - just act on their requests naturally.
|
||||
END SYSTEM PROMPT
|
||||
```
|
||||
|
||||
### 2. Tool Implementation
|
||||
|
||||
Each tool is a separate `.bas` file with `PARAM` and `DESCRIPTION`:
|
||||
|
||||
```basic
|
||||
PARAM product AS STRING LIKE "fax" DESCRIPTION "Name of the product to get price for"
|
||||
|
||||
DESCRIPTION "Get the price of a product by name from the product catalog"
|
||||
|
||||
productRecord = FIND "products.csv", "name = ${product}"
|
||||
|
||||
IF productRecord THEN
|
||||
RETURN productRecord.price
|
||||
ELSE
|
||||
RETURN -1
|
||||
END IF
|
||||
```
|
||||
|
||||
### 3. LLM Invocation
|
||||
|
||||
When a user asks "How much is the fax machine?", the LLM:
|
||||
1. Recognizes this requires price information
|
||||
2. Calls `get-price` with `product="fax"`
|
||||
3. Receives the price (or -1 if not found)
|
||||
4. Formulates a natural response
|
||||
|
||||
## Creating Custom Tools
|
||||
|
||||
### Tool Anatomy
|
||||
|
||||
Every tool needs:
|
||||
- **PARAM declarations** - Input parameters with types and examples
|
||||
- **DESCRIPTION** - What the tool does (for LLM understanding)
|
||||
- **Implementation** - The actual logic
|
||||
- **RETURN** - The output value
|
||||
|
||||
### Parameter Types
|
||||
|
||||
| Type | Description | Example |
|
||||
|------|-------------|---------|
|
||||
| `STRING` | Text input | `PARAM name AS STRING LIKE "John"` |
|
||||
| `NUMBER` | Numeric input | `PARAM quantity AS NUMBER LIKE 5` |
|
||||
| `INTEGER` | Whole numbers | `PARAM count AS INTEGER LIKE 10` |
|
||||
| `BOOLEAN` | True/false | `PARAM active AS BOOLEAN` |
|
||||
| `DATE` | Date values | `PARAM start AS DATE LIKE "2024-01-15"` |
|
||||
| `EMAIL` | Email addresses | `PARAM email AS EMAIL` |
|
||||
| `PHONE` | Phone numbers | `PARAM phone AS PHONE` |
|
||||
| `OBJECT` | JSON objects | `PARAM data AS OBJECT` |
|
||||
|
||||
### Example Tools
|
||||
|
||||
#### Database Lookup Tool
|
||||
|
||||
```basic
|
||||
' lookup-customer.bas
|
||||
PARAM customer_id AS STRING LIKE "CUST-001" DESCRIPTION "Customer ID to look up"
|
||||
|
||||
DESCRIPTION "Retrieve customer information by ID"
|
||||
|
||||
customer = FIND "customers.csv", "id = ${customer_id}"
|
||||
|
||||
IF customer THEN
|
||||
WITH result
|
||||
name = customer.name
|
||||
email = customer.email
|
||||
status = customer.status
|
||||
since = customer.created_at
|
||||
END WITH
|
||||
RETURN result
|
||||
ELSE
|
||||
RETURN NULL
|
||||
END IF
|
||||
```
|
||||
|
||||
#### Calculation Tool
|
||||
|
||||
```basic
|
||||
' calculate-discount.bas
|
||||
PARAM original_price AS NUMBER LIKE 100 DESCRIPTION "Original product price"
|
||||
PARAM discount_percent AS NUMBER LIKE 15 DESCRIPTION "Discount percentage"
|
||||
|
||||
DESCRIPTION "Calculate the final price after applying a discount"
|
||||
|
||||
discount_amount = original_price * (discount_percent / 100)
|
||||
final_price = original_price - discount_amount
|
||||
|
||||
WITH result
|
||||
original = original_price
|
||||
discount = discount_amount
|
||||
final = final_price
|
||||
savings = discount_percent + "% off"
|
||||
END WITH
|
||||
|
||||
RETURN result
|
||||
```
|
||||
|
||||
#### API Integration Tool
|
||||
|
||||
```basic
|
||||
' check-inventory.bas
|
||||
PARAM sku AS STRING LIKE "SKU-12345" DESCRIPTION "Product SKU to check"
|
||||
PARAM warehouse AS STRING LIKE "main" DESCRIPTION "Warehouse location" OPTIONAL
|
||||
|
||||
DESCRIPTION "Check real-time inventory levels for a product"
|
||||
|
||||
IF NOT warehouse THEN
|
||||
warehouse = "main"
|
||||
END IF
|
||||
|
||||
SET HEADER "Authorization" AS "Bearer " + GET ENV "INVENTORY_API_KEY"
|
||||
response = GET "https://api.inventory.com/stock/" + sku + "?warehouse=" + warehouse
|
||||
|
||||
IF response.error THEN
|
||||
RETURN {"available": false, "error": response.error}
|
||||
END IF
|
||||
|
||||
WITH result
|
||||
sku = sku
|
||||
available = response.quantity > 0
|
||||
quantity = response.quantity
|
||||
warehouse = warehouse
|
||||
last_updated = response.timestamp
|
||||
END WITH
|
||||
|
||||
RETURN result
|
||||
```
|
||||
|
||||
#### Email Sending Tool
|
||||
|
||||
```basic
|
||||
' send-notification.bas
|
||||
PARAM recipient AS EMAIL LIKE "user@example.com" DESCRIPTION "Email recipient"
|
||||
PARAM subject AS STRING LIKE "Order Confirmation" DESCRIPTION "Email subject"
|
||||
PARAM message AS STRING DESCRIPTION "Email body content"
|
||||
|
||||
DESCRIPTION "Send an email notification to a customer"
|
||||
|
||||
SEND EMAIL recipient, subject, message
|
||||
|
||||
WITH result
|
||||
sent = true
|
||||
recipient = recipient
|
||||
timestamp = NOW()
|
||||
END WITH
|
||||
|
||||
RETURN result
|
||||
```
|
||||
|
||||
## Tool Registration Patterns
|
||||
|
||||
### Single Tool
|
||||
|
||||
```basic
|
||||
ADD TOOL "get-price"
|
||||
```
|
||||
|
||||
### Multiple Tools
|
||||
|
||||
```basic
|
||||
ADD TOOL "get-price"
|
||||
ADD TOOL "check-inventory"
|
||||
ADD TOOL "lookup-customer"
|
||||
ADD TOOL "calculate-discount"
|
||||
ADD TOOL "send-notification"
|
||||
```
|
||||
|
||||
### Conditional Tools
|
||||
|
||||
```basic
|
||||
user_role = GET SESSION "user_role"
|
||||
|
||||
ADD TOOL "get-price"
|
||||
ADD TOOL "check-inventory"
|
||||
|
||||
IF user_role = "admin" THEN
|
||||
ADD TOOL "update-price"
|
||||
ADD TOOL "delete-product"
|
||||
END IF
|
||||
```
|
||||
|
||||
## System Prompt Best Practices
|
||||
|
||||
Guide the LLM on when and how to use tools:
|
||||
|
||||
```basic
|
||||
BEGIN SYSTEM PROMPT
|
||||
You are a helpful product assistant with access to the following capabilities:
|
||||
|
||||
**Available Tools:**
|
||||
- get-price: Look up product prices by name
|
||||
- check-inventory: Check stock availability
|
||||
- calculate-discount: Calculate prices with discounts
|
||||
|
||||
**Guidelines:**
|
||||
1. When users ask about prices, use the get-price tool
|
||||
2. When asked about availability, use check-inventory
|
||||
3. If a tool returns an error, explain politely that the item wasn't found
|
||||
4. Never mention tool names to users - just provide the information naturally
|
||||
5. Combine multiple tool results when needed to answer complex questions
|
||||
|
||||
**Error Handling:**
|
||||
- If get-price returns -1, the product doesn't exist
|
||||
- If check-inventory shows quantity 0, inform the user it's out of stock
|
||||
END SYSTEM PROMPT
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
Configure in `llm-tools.gbot/config.csv`:
|
||||
|
||||
| Parameter | Description | Example |
|
||||
|-----------|-------------|---------|
|
||||
| `LLM Provider` | AI provider | `openai` |
|
||||
| `LLM Model` | Model for tool calls | `gpt-4` |
|
||||
| `Tool Timeout` | Max tool execution time | `30` |
|
||||
| `Max Tool Calls` | Limit per conversation | `10` |
|
||||
|
||||
## Example Conversations
|
||||
|
||||
### Price Lookup
|
||||
|
||||
```
|
||||
User: How much does the wireless mouse cost?
|
||||
Bot: [Calls get-price with product="wireless mouse"]
|
||||
Bot: The wireless mouse is $29.99.
|
||||
|
||||
User: What about the keyboard?
|
||||
Bot: [Calls get-price with product="keyboard"]
|
||||
Bot: The standard keyboard is $49.99. We also have a mechanical
|
||||
keyboard for $89.99.
|
||||
```
|
||||
|
||||
### Combined Tool Use
|
||||
|
||||
```
|
||||
User: Is the laptop in stock and what's the price?
|
||||
Bot: [Calls get-price with product="laptop"]
|
||||
Bot: [Calls check-inventory with sku="LAPTOP-001"]
|
||||
Bot: The laptop is $999. Good news - we have 12 units available
|
||||
in our main warehouse and can ship today!
|
||||
```
|
||||
|
||||
### With Calculations
|
||||
|
||||
```
|
||||
User: I want to buy 3 monitors with my 20% employee discount
|
||||
Bot: [Calls get-price with product="monitor"]
|
||||
Bot: [Calls calculate-discount with original_price=299, discount_percent=20]
|
||||
Bot: Each monitor is $299, but with your 20% employee discount,
|
||||
you'll pay $239.20 each. For 3 monitors, your total would be $717.60
|
||||
(saving $179.40)!
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
### In Tool Implementation
|
||||
|
||||
```basic
|
||||
' get-price.bas with error handling
|
||||
PARAM product AS STRING LIKE "laptop" DESCRIPTION "Product name"
|
||||
|
||||
DESCRIPTION "Get product price with error handling"
|
||||
|
||||
ON ERROR GOTO HandleError
|
||||
|
||||
productRecord = FIND "products.csv", "name LIKE '%" + product + "%'"
|
||||
|
||||
IF productRecord THEN
|
||||
RETURN productRecord.price
|
||||
ELSE
|
||||
RETURN {"error": "not_found", "message": "Product not in catalog"}
|
||||
END IF
|
||||
|
||||
HandleError:
|
||||
RETURN {"error": "system_error", "message": "Unable to look up price"}
|
||||
```
|
||||
|
||||
### In System Prompt
|
||||
|
||||
```basic
|
||||
BEGIN SYSTEM PROMPT
|
||||
When tools return errors:
|
||||
- "not_found": Apologize and suggest similar products
|
||||
- "out_of_stock": Offer to notify when back in stock
|
||||
- "system_error": Ask user to try again later
|
||||
END SYSTEM PROMPT
|
||||
```
|
||||
|
||||
## Testing Tools
|
||||
|
||||
### Manual Testing
|
||||
|
||||
```basic
|
||||
' test-tools.bas
|
||||
result = CALL "get-price", {"product": "laptop"}
|
||||
TALK "Price result: " + JSON(result)
|
||||
|
||||
result = CALL "check-inventory", {"sku": "LAPTOP-001"}
|
||||
TALK "Inventory result: " + JSON(result)
|
||||
```
|
||||
|
||||
### Conversation Testing
|
||||
|
||||
Test various phrasings to ensure tool invocation:
|
||||
|
||||
- "What's the price of X?"
|
||||
- "How much does X cost?"
|
||||
- "Price for X please"
|
||||
- "X price?"
|
||||
- "Can you tell me what X costs?"
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Clear descriptions** - Help the LLM understand when to use each tool
|
||||
2. **Good examples** - LIKE clauses guide parameter format
|
||||
3. **Handle errors** - Always return meaningful error responses
|
||||
4. **Validate input** - Check parameters before processing
|
||||
5. **Log tool calls** - Track usage for debugging
|
||||
6. **Keep tools focused** - One tool, one purpose
|
||||
7. **Test thoroughly** - Various phrasings should trigger correct tools
|
||||
|
||||
## Related Templates
|
||||
|
||||
- `llm-server.gbai` - Headless API with LLM processing
|
||||
- `crm.gbai` - CRM with many tool examples
|
||||
- `store.gbai` - E-commerce with product tools
|
||||
- `talk-to-data.gbai` - Data query tools
|
||||
|
||||
## Use Cases
|
||||
|
||||
- **Product Lookup** - Price, availability, specifications
|
||||
- **Customer Service** - Order status, account info
|
||||
- **Calculations** - Quotes, discounts, shipping
|
||||
- **Integrations** - CRM, ERP, external APIs
|
||||
- **Data Access** - Database queries, report generation
|
||||
|
||||
## License
|
||||
|
||||
AGPL-3.0 - Part of General Bots Open Source Platform.
|
||||
|
||||
---
|
||||
|
||||
**Pragmatismo** - General Bots
|
||||
364
templates/platform/analytics.gbai/README.md
Normal file
364
templates/platform/analytics.gbai/README.md
Normal file
|
|
@ -0,0 +1,364 @@
|
|||
# Platform Analytics Template (analytics.gbai)
|
||||
|
||||
A General Bots template for platform metrics, performance monitoring, and custom report generation.
|
||||
|
||||
## Overview
|
||||
|
||||
The Analytics template provides comprehensive platform analytics capabilities, allowing administrators and stakeholders to monitor usage, track performance, analyze trends, and generate custom reports through conversational AI.
|
||||
|
||||
## Features
|
||||
|
||||
- **Platform Overview** - Key metrics summary with trend analysis
|
||||
- **Message Analytics** - Conversation statistics by channel and bot
|
||||
- **User Analytics** - Active users, sessions, and engagement
|
||||
- **Performance Metrics** - Response times and throughput monitoring
|
||||
- **LLM Usage Tracking** - Token consumption and cost analysis
|
||||
- **Storage Analytics** - Disk usage and file statistics
|
||||
- **Error Analysis** - Error patterns and troubleshooting insights
|
||||
- **Custom Report Generator** - Build and schedule personalized reports
|
||||
- **AI-Powered Insights** - Automatic trend analysis and recommendations
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
analytics.gbai/
|
||||
├── README.md
|
||||
├── analytics.gbdialog/
|
||||
│ ├── start.bas # Main menu and navigation
|
||||
│ ├── platform-overview.bas # Key metrics dashboard
|
||||
│ └── custom-report.bas # Custom report builder
|
||||
└── analytics.gbot/
|
||||
└── config.csv # Bot configuration
|
||||
```
|
||||
|
||||
## Scripts
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `start.bas` | Main entry point with analytics menu options |
|
||||
| `platform-overview.bas` | Platform-wide metrics with trends and export |
|
||||
| `custom-report.bas` | Interactive custom report generator with scheduling |
|
||||
|
||||
## Available Analytics
|
||||
|
||||
### 1. Platform Overview
|
||||
|
||||
High-level metrics summary including:
|
||||
- Total messages and trend percentage
|
||||
- Average active sessions
|
||||
- Response time performance
|
||||
- Error rates
|
||||
- LLM token consumption
|
||||
|
||||
### 2. Message Analytics
|
||||
|
||||
- Message volume by time period
|
||||
- Breakdown by channel (WhatsApp, Web, API)
|
||||
- Bot-specific conversation stats
|
||||
- Peak usage times
|
||||
|
||||
### 3. User Analytics
|
||||
|
||||
- Active users (daily, weekly, monthly)
|
||||
- Session duration analysis
|
||||
- User retention rates
|
||||
- Geographic distribution
|
||||
|
||||
### 4. Performance Metrics
|
||||
|
||||
- Average response time
|
||||
- Response time distribution
|
||||
- Throughput (messages per second)
|
||||
- Latency percentiles (p50, p95, p99)
|
||||
|
||||
### 5. LLM Usage
|
||||
|
||||
- Token consumption by model
|
||||
- Cost analysis
|
||||
- Usage patterns
|
||||
- Optimization recommendations
|
||||
|
||||
### 6. Storage Analytics
|
||||
|
||||
- Disk usage trends
|
||||
- File count and types
|
||||
- Storage by bot/package
|
||||
- Cleanup recommendations
|
||||
|
||||
### 7. Error Analysis
|
||||
|
||||
- Error frequency and patterns
|
||||
- Error categorization
|
||||
- Root cause analysis
|
||||
- Resolution suggestions
|
||||
|
||||
### 8. Custom Reports
|
||||
|
||||
- Select metrics to include
|
||||
- Choose time ranges
|
||||
- Set grouping intervals
|
||||
- Export in multiple formats
|
||||
- Schedule automatic delivery
|
||||
|
||||
## Usage
|
||||
|
||||
### Starting Analytics
|
||||
|
||||
```
|
||||
User: Show me analytics
|
||||
Bot: Welcome to the Analytics Center. I can help you understand your platform metrics and generate reports.
|
||||
|
||||
What would you like to analyze?
|
||||
1. Platform Overview - Key metrics summary
|
||||
2. Message Analytics - Conversation statistics
|
||||
3. User Analytics - Active users and sessions
|
||||
4. Performance Metrics - Response times and throughput
|
||||
5. LLM Usage - Token consumption and costs
|
||||
6. Storage Analytics - Disk usage and file statistics
|
||||
7. Error Analysis - Error patterns and trends
|
||||
8. Generate Custom Report
|
||||
```
|
||||
|
||||
### Platform Overview
|
||||
|
||||
```
|
||||
User: 1
|
||||
Bot: Generating platform overview...
|
||||
Select time range (1h, 6h, 24h, 7d, 30d): 24h
|
||||
|
||||
Platform Overview for 24h
|
||||
|
||||
📊 Messages
|
||||
Total: 15,432
|
||||
Trend: +12.5%
|
||||
|
||||
👥 Sessions
|
||||
Average Active: 234
|
||||
Trend: +5.2%
|
||||
|
||||
⚡ Performance
|
||||
Avg Response Time: 145 ms
|
||||
|
||||
❌ Errors
|
||||
Total: 23
|
||||
Error Rate: 0.15%
|
||||
|
||||
🤖 LLM Usage
|
||||
Total Tokens: 1,245,678
|
||||
```
|
||||
|
||||
### Custom Report Generation
|
||||
|
||||
```
|
||||
User: I need a custom report
|
||||
Bot: Custom Report Generator
|
||||
What would you like to name this report?
|
||||
|
||||
User: Weekly Performance Summary
|
||||
|
||||
Bot: Select the time range for your report:
|
||||
1. Last Hour
|
||||
2. Last 24 Hours
|
||||
3. Last 7 Days
|
||||
4. Last 30 Days
|
||||
5. Last 90 Days
|
||||
6. Custom Range
|
||||
|
||||
User: 3
|
||||
|
||||
Bot: Select metrics to include (enter numbers separated by commas):
|
||||
1. Message Volume
|
||||
2. Active Sessions
|
||||
3. Response Time
|
||||
4. LLM Token Usage
|
||||
5. Error Rate
|
||||
...
|
||||
|
||||
User: 1,3,4,5
|
||||
|
||||
Bot: Select grouping interval:
|
||||
1. Hourly
|
||||
2. Daily
|
||||
3. Weekly
|
||||
4. Monthly
|
||||
|
||||
User: 2
|
||||
|
||||
Bot: Generating your custom report...
|
||||
|
||||
Report generated successfully.
|
||||
Report Name: Weekly Performance Summary
|
||||
Time Range: Last 7 Days
|
||||
Download: https://example.com/reports/report_xxx.pdf
|
||||
|
||||
Would you like to receive this report via email?
|
||||
```
|
||||
|
||||
## Metrics Query System
|
||||
|
||||
The template uses a metrics query system:
|
||||
|
||||
```basic
|
||||
' Query metrics for a time range
|
||||
messages = QUERY METRICS "messages" FOR "24h"
|
||||
totalMessages = SUM(messages, "count")
|
||||
|
||||
' Query with grouping
|
||||
hourlyMessages = QUERY METRICS "messages" FOR "24h" BY "1h"
|
||||
|
||||
' Query with offset for comparison
|
||||
prevMessages = QUERY METRICS "messages" FOR "24h" OFFSET 1
|
||||
trend = ((totalMessages - SUM(prevMessages, "count")) / SUM(prevMessages, "count")) * 100
|
||||
```
|
||||
|
||||
## Export Formats
|
||||
|
||||
Reports can be exported in multiple formats:
|
||||
|
||||
| Format | Description |
|
||||
|--------|-------------|
|
||||
| PDF | Formatted report with charts |
|
||||
| XLSX | Excel spreadsheet |
|
||||
| CSV | Raw data export |
|
||||
| JSON | Structured data format |
|
||||
|
||||
## Scheduled Reports
|
||||
|
||||
Configure automatic report delivery:
|
||||
|
||||
| Schedule | Cron Expression | Description |
|
||||
|----------|-----------------|-------------|
|
||||
| Daily | `0 8 * * *` | Every day at 8 AM |
|
||||
| Weekly | `0 8 * * 1` | Monday at 8 AM |
|
||||
| Monthly | `0 8 1 * *` | 1st of month at 8 AM |
|
||||
|
||||
```basic
|
||||
SET SCHEDULE "0 8 * * 1", "generate-scheduled-report.bas"
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
Configure in `analytics.gbot/config.csv`:
|
||||
|
||||
| Parameter | Description | Example |
|
||||
|-----------|-------------|---------|
|
||||
| `Default Time Range` | Default period for queries | `7d` |
|
||||
| `Data Retention Days` | How long to keep metrics | `90` |
|
||||
| `Admin Email` | Email for scheduled reports | `admin@company.com` |
|
||||
| `Enable AI Insights` | Auto-generate insights | `true` |
|
||||
| `Export Path` | Report storage location | `/reports/` |
|
||||
|
||||
## Customization
|
||||
|
||||
### Adding Custom Metrics
|
||||
|
||||
```basic
|
||||
' Track custom events
|
||||
INSERT INTO "custom_metrics" VALUES {
|
||||
"name": "feature_usage",
|
||||
"value": 1,
|
||||
"tags": {"feature": "chat", "plan": "pro"},
|
||||
"timestamp": NOW()
|
||||
}
|
||||
|
||||
' Query custom metrics
|
||||
usage = QUERY METRICS "feature_usage" FOR "30d" WHERE tags.feature = "chat"
|
||||
```
|
||||
|
||||
### Custom Dashboard Widgets
|
||||
|
||||
```basic
|
||||
' Add to start.bas
|
||||
TALK "Custom Metrics:"
|
||||
TALK "9. Feature Usage"
|
||||
TALK "10. Revenue Analytics"
|
||||
TALK "11. Customer Health Score"
|
||||
|
||||
' Handle custom options
|
||||
CASE 9
|
||||
CALL "feature-usage.bas"
|
||||
CASE 10
|
||||
CALL "revenue-analytics.bas"
|
||||
```
|
||||
|
||||
### AI-Powered Insights
|
||||
|
||||
```basic
|
||||
' Generate AI insights from metrics
|
||||
SET CONTEXT "You are an analytics expert. Generate executive insights from this data."
|
||||
|
||||
insights = LLM "Analyze this platform data and provide 3-5 key insights: " + JSON(report_data)
|
||||
```
|
||||
|
||||
## Integration
|
||||
|
||||
### With Alerting
|
||||
|
||||
```basic
|
||||
' Set up alerts based on metrics
|
||||
errorRate = SUM(errors, "count") / SUM(messages, "count") * 100
|
||||
|
||||
IF errorRate > 5 THEN
|
||||
SEND EMAIL admin_email, "High Error Rate Alert",
|
||||
"Error rate is " + errorRate + "%, above 5% threshold."
|
||||
END IF
|
||||
```
|
||||
|
||||
### With External BI Tools
|
||||
|
||||
```basic
|
||||
' Export data for external tools
|
||||
data = QUERY METRICS "messages" FOR "30d" BY "1d"
|
||||
WRITE "analytics_export.csv", CSV(data)
|
||||
|
||||
' Or send to webhook
|
||||
POST "https://bi-tool.example.com/webhook", data
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Set appropriate time ranges** - Don't query more data than needed
|
||||
2. **Use caching** - Cache expensive queries
|
||||
3. **Schedule off-peak** - Run heavy reports during low traffic
|
||||
4. **Monitor the monitor** - Track analytics query performance
|
||||
5. **Archive old data** - Move historical data to cold storage
|
||||
6. **Validate insights** - Review AI-generated insights for accuracy
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Issue | Cause | Solution |
|
||||
|-------|-------|----------|
|
||||
| Slow queries | Large time range | Reduce time range or add filters |
|
||||
| Missing data | Metrics not being collected | Verify instrumentation |
|
||||
| Export fails | Large report size | Export in chunks or use CSV |
|
||||
| Stale data | Cache not refreshed | Clear cache or reduce TTL |
|
||||
| Incorrect trends | Insufficient historical data | Wait for more data collection |
|
||||
|
||||
## Related Templates
|
||||
|
||||
- `bi.gbai` - Business Intelligence reporting
|
||||
- `talk-to-data.gbai` - Natural language data queries
|
||||
- `crm.gbai` - CRM analytics and pipeline reports
|
||||
|
||||
## Use Cases
|
||||
|
||||
- **Operations Teams** - Monitor platform health and performance
|
||||
- **Product Managers** - Track feature usage and engagement
|
||||
- **Executives** - High-level KPI dashboards
|
||||
- **Support Teams** - Identify error patterns
|
||||
- **Finance** - LLM cost tracking and optimization
|
||||
|
||||
## Data Privacy
|
||||
|
||||
- Analytics data is aggregated and anonymized
|
||||
- User-level data requires appropriate permissions
|
||||
- Respect data retention policies
|
||||
- Comply with GDPR/CCPA as applicable
|
||||
|
||||
## License
|
||||
|
||||
AGPL-3.0 - Part of General Bots Open Source Platform.
|
||||
|
||||
---
|
||||
|
||||
**Pragmatismo** - General Bots
|
||||
326
templates/productivity/office.gbai/README.md
Normal file
326
templates/productivity/office.gbai/README.md
Normal file
|
|
@ -0,0 +1,326 @@
|
|||
# Office Automation Template (office.gbai)
|
||||
|
||||
A General Bots template for role-based office productivity with department-specific knowledge bases and context-aware assistance.
|
||||
|
||||
## Overview
|
||||
|
||||
The Office template provides a multi-role office assistant that adapts its behavior, knowledge, and suggestions based on the user's role. Whether you're a manager, developer, customer support agent, HR professional, or finance team member, the bot tailors its responses and available resources accordingly.
|
||||
|
||||
## Features
|
||||
|
||||
- **Role-Based Access** - Different capabilities per user role
|
||||
- **Dynamic Knowledge Bases** - Automatically loads relevant KB per role
|
||||
- **Context-Aware Responses** - AI behavior adapts to role requirements
|
||||
- **Custom Suggestions** - Role-specific quick actions
|
||||
- **Tool Integration** - Calendar, tasks, documents, meetings, notes
|
||||
- **Persistent Role Memory** - Remembers user role across sessions
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
office.gbai/
|
||||
├── README.md
|
||||
├── office.gbdialog/
|
||||
│ ├── start.bas # Role selection and configuration
|
||||
│ ├── api-integration.bas # External API connections
|
||||
│ ├── data-sync.bas # Data synchronization
|
||||
│ └── document-processor.bas # Document handling
|
||||
├── office.gbkb/ # Knowledge bases by role
|
||||
│ ├── management/
|
||||
│ ├── documentation/
|
||||
│ ├── products/
|
||||
│ ├── hr-policies/
|
||||
│ └── budgets/
|
||||
└── office.gbot/
|
||||
└── config.csv # Bot configuration
|
||||
```
|
||||
|
||||
## Scripts
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `start.bas` | Main entry with role selection and context setup |
|
||||
| `api-integration.bas` | Connect to external office systems |
|
||||
| `data-sync.bas` | Sync data across office applications |
|
||||
| `document-processor.bas` | Process and manage documents |
|
||||
|
||||
## Supported Roles
|
||||
|
||||
### Manager
|
||||
|
||||
- **Context**: Executive assistant for reports, team management, strategic decisions
|
||||
- **Knowledge Bases**: management, reports, team-policies
|
||||
- **Suggestions**: Team performance, Generate report, Schedule meeting
|
||||
|
||||
### Developer
|
||||
|
||||
- **Context**: Technical assistant for documentation, APIs, coding best practices
|
||||
- **Knowledge Bases**: documentation, apis, coding-standards
|
||||
- **Suggestions**: Search documentation, API reference, Code review checklist
|
||||
|
||||
### Customer Support
|
||||
|
||||
- **Context**: Customer service assistant focused on resolving issues
|
||||
- **Knowledge Bases**: products, support, faq
|
||||
- **Suggestions**: Track my order, Product information, Contact support
|
||||
|
||||
### HR
|
||||
|
||||
- **Context**: HR assistant for employee matters, policies, benefits
|
||||
- **Knowledge Bases**: hr-policies, benefits, onboarding
|
||||
- **Suggestions**: Employee handbook, Benefits overview, New hire checklist
|
||||
|
||||
### Finance
|
||||
|
||||
- **Context**: Finance assistant for budgets, expenses, financial reports
|
||||
- **Knowledge Bases**: budgets, expenses, financial-reports
|
||||
- **Suggestions**: Expense policy, Budget status, Approval workflow
|
||||
|
||||
## Available Tools
|
||||
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `calendar` | Schedule and manage appointments |
|
||||
| `tasks` | Create and track to-do items |
|
||||
| `documents` | Access and manage documents |
|
||||
| `meetings` | Schedule and join meetings |
|
||||
| `notes` | Create and search notes |
|
||||
|
||||
## Usage
|
||||
|
||||
### First-Time Setup
|
||||
|
||||
```
|
||||
Bot: Welcome to the Office Assistant!
|
||||
Please select your role:
|
||||
|
||||
User: manager
|
||||
|
||||
Bot: Welcome, Manager! I can help with reports, team management, and policies.
|
||||
```
|
||||
|
||||
### Role-Based Interaction
|
||||
|
||||
**Manager:**
|
||||
```
|
||||
User: Generate a team performance report
|
||||
Bot: [Uses management KB and context]
|
||||
I'll generate the team performance report. What time period?
|
||||
```
|
||||
|
||||
**Developer:**
|
||||
```
|
||||
User: How do I authenticate with the payment API?
|
||||
Bot: [Uses documentation and apis KB]
|
||||
According to our API documentation, payment API authentication
|
||||
uses OAuth 2.0. Here's how to implement it...
|
||||
```
|
||||
|
||||
**Customer Support:**
|
||||
```
|
||||
User: Customer asking about order #12345
|
||||
Bot: [Uses products and support KB]
|
||||
I found order #12345. It was shipped yesterday and should
|
||||
arrive by Thursday. Would you like the tracking number?
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
Configure in `office.gbot/config.csv`:
|
||||
|
||||
| Parameter | Description | Example |
|
||||
|-----------|-------------|---------|
|
||||
| `Default Role` | Role when none selected | `customer` |
|
||||
| `Remember Role` | Persist role across sessions | `true` |
|
||||
| `Role Timeout` | Hours before re-asking role | `24` |
|
||||
| `Theme Color` | UI accent color | `blue` |
|
||||
|
||||
## Customization
|
||||
|
||||
### Adding New Roles
|
||||
|
||||
Extend the `start.bas` file:
|
||||
|
||||
```basic
|
||||
CASE "sales"
|
||||
SET CONTEXT "You are a sales assistant helping with leads, opportunities, and closing deals."
|
||||
USE KB "sales-playbook"
|
||||
USE KB "pricing"
|
||||
USE KB "competitors"
|
||||
TALK "Welcome, Sales! I can help with leads, pricing, and proposals."
|
||||
|
||||
CLEAR SUGGESTIONS
|
||||
ADD SUGGESTION "leads" AS "View my leads"
|
||||
ADD SUGGESTION "quote" AS "Generate quote"
|
||||
ADD SUGGESTION "pipeline" AS "Pipeline status"
|
||||
```
|
||||
|
||||
### Custom Knowledge Bases
|
||||
|
||||
Create role-specific knowledge bases in `office.gbkb/`:
|
||||
|
||||
```
|
||||
office.gbkb/
|
||||
├── sales-playbook/
|
||||
│ ├── objection-handling.md
|
||||
│ ├── pricing-guide.md
|
||||
│ └── competitor-comparison.md
|
||||
```
|
||||
|
||||
### Role-Specific Tools
|
||||
|
||||
Register different tools per role:
|
||||
|
||||
```basic
|
||||
CASE "manager"
|
||||
ADD TOOL "calendar"
|
||||
ADD TOOL "tasks"
|
||||
ADD TOOL "team-report"
|
||||
ADD TOOL "approve-request"
|
||||
|
||||
CASE "developer"
|
||||
ADD TOOL "search-docs"
|
||||
ADD TOOL "api-tester"
|
||||
ADD TOOL "code-review"
|
||||
```
|
||||
|
||||
### Custom System Prompts
|
||||
|
||||
Extend the system prompt per role:
|
||||
|
||||
```basic
|
||||
BEGIN SYSTEM PROMPT
|
||||
You are a role-based office assistant.
|
||||
|
||||
Current user role: ${role}
|
||||
|
||||
Role-specific guidelines:
|
||||
- Manager: Focus on strategic decisions, delegation, and KPIs
|
||||
- Developer: Be technical, reference documentation, suggest best practices
|
||||
- Customer: Be empathetic, focus on resolution, escalate when needed
|
||||
- HR: Maintain confidentiality, be policy-aware, supportive
|
||||
- Finance: Be precise with numbers, follow approval processes
|
||||
|
||||
Adapt your responses and suggestions based on the user's role.
|
||||
END SYSTEM PROMPT
|
||||
```
|
||||
|
||||
## Integration Examples
|
||||
|
||||
### With Calendar
|
||||
|
||||
```basic
|
||||
' Schedule meeting for manager
|
||||
IF role = "manager" THEN
|
||||
TALK "I'll schedule the team meeting."
|
||||
CREATE CALENDAR EVENT "Team Standup", tomorrow + " 9:00 AM", 30
|
||||
END IF
|
||||
```
|
||||
|
||||
### With Document System
|
||||
|
||||
```basic
|
||||
' Generate document based on role
|
||||
SWITCH role
|
||||
CASE "hr"
|
||||
template = "offer-letter-template.docx"
|
||||
CASE "sales"
|
||||
template = "proposal-template.docx"
|
||||
CASE "finance"
|
||||
template = "budget-template.xlsx"
|
||||
END SWITCH
|
||||
|
||||
document = GENERATE FROM TEMPLATE template WITH data
|
||||
```
|
||||
|
||||
### With Task Management
|
||||
|
||||
```basic
|
||||
' Create role-appropriate tasks
|
||||
IF role = "manager" THEN
|
||||
CREATE TASK "Review Q4 budget", "high", manager_email
|
||||
CREATE TASK "Approve team PTO requests", "medium", manager_email
|
||||
END IF
|
||||
```
|
||||
|
||||
## Example Conversations
|
||||
|
||||
### Manager Role
|
||||
|
||||
```
|
||||
User: I need to review my team's performance
|
||||
Bot: I'll help you review team performance. Here's a summary:
|
||||
|
||||
📊 Team Performance Dashboard
|
||||
|
||||
Active Projects: 5
|
||||
Completed This Month: 3
|
||||
|
||||
Top Performers:
|
||||
- Sarah Chen: 12 tasks completed
|
||||
- Mike Johnson: 10 tasks completed
|
||||
|
||||
Pending Approvals: 2
|
||||
|
||||
Would you like a detailed report or to schedule 1:1s?
|
||||
```
|
||||
|
||||
### Developer Role
|
||||
|
||||
```
|
||||
User: How do I implement pagination in our API?
|
||||
Bot: Based on our API documentation, here's the pagination pattern:
|
||||
|
||||
```javascript
|
||||
GET /api/v1/users?page=1&per_page=20
|
||||
```
|
||||
|
||||
Response includes:
|
||||
- `data`: Array of results
|
||||
- `meta.total`: Total count
|
||||
- `meta.page`: Current page
|
||||
- `links.next`: Next page URL
|
||||
|
||||
Our coding standards recommend cursor-based pagination
|
||||
for large datasets. See: docs/api/pagination.md
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Clear role definitions** - Define clear boundaries for each role
|
||||
2. **Relevant suggestions** - Keep quick actions useful for each role
|
||||
3. **Appropriate KBs** - Only load necessary knowledge bases
|
||||
4. **Security awareness** - Restrict sensitive data by role
|
||||
5. **Regular updates** - Keep knowledge bases current
|
||||
6. **Feedback loops** - Monitor which features each role uses
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Issue | Cause | Solution |
|
||||
|-------|-------|----------|
|
||||
| Wrong KB loaded | Role not set correctly | Check role detection logic |
|
||||
| Missing suggestions | Role not in switch statement | Add role to all switch blocks |
|
||||
| Context confusion | Multiple roles used | Clear context between role changes |
|
||||
| Slow responses | Too many KBs loaded | Load only essential KBs per role |
|
||||
|
||||
## Related Templates
|
||||
|
||||
- `contacts.gbai` - Contact management
|
||||
- `reminder.gbai` - Task and reminder management
|
||||
- `crm.gbai` - Full CRM for sales roles
|
||||
- `analytics.gbai` - Platform analytics for managers
|
||||
|
||||
## Use Cases
|
||||
|
||||
- **Corporate Offices** - Multi-department support
|
||||
- **Startups** - Flexible role-based assistance
|
||||
- **Remote Teams** - Unified office assistant
|
||||
- **Enterprise** - Department-specific knowledge management
|
||||
|
||||
## License
|
||||
|
||||
AGPL-3.0 - Part of General Bots Open Source Platform.
|
||||
|
||||
---
|
||||
|
||||
**Pragmatismo** - General Bots
|
||||
368
templates/productivity/reminder.gbai/README.md
Normal file
368
templates/productivity/reminder.gbai/README.md
Normal file
|
|
@ -0,0 +1,368 @@
|
|||
# Reminder Template (reminder.gbai)
|
||||
|
||||
A General Bots template for managing personal and team reminders with multi-channel notifications.
|
||||
|
||||
## Overview
|
||||
|
||||
The Reminder template provides a complete reminder management system with natural language scheduling, multiple notification channels, and snooze capabilities. Users can create, view, manage, and receive reminders through conversational AI.
|
||||
|
||||
## Features
|
||||
|
||||
- **Natural Language Scheduling** - Create reminders using everyday language
|
||||
- **Multi-Channel Notifications** - Email, SMS, or chat notifications
|
||||
- **Reminder Management** - List, snooze, and delete reminders
|
||||
- **Scheduled Execution** - Background job checks and sends due reminders
|
||||
- **Smart Date Parsing** - Understands "tomorrow", "next week", "in 2 hours"
|
||||
- **Persistent Storage** - Reminders saved to CSV for reliability
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
reminder.gbai/
|
||||
├── README.md
|
||||
├── reminder.gbdata/ # Data storage
|
||||
│ └── reminders.csv # Reminder records
|
||||
├── reminder.gbdialog/
|
||||
│ ├── start.bas # Main entry and tool registration
|
||||
│ ├── add-reminder.bas # Create new reminders
|
||||
│ └── reminder.bas # Scheduled job to send reminders
|
||||
└── reminder.gbot/
|
||||
└── config.csv # Bot configuration
|
||||
```
|
||||
|
||||
## Scripts
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `start.bas` | Registers tools, sets up suggestions, configures context |
|
||||
| `add-reminder.bas` | Creates new reminder records with notifications |
|
||||
| `reminder.bas` | Scheduled job that checks and sends due reminders |
|
||||
|
||||
## Available Tools
|
||||
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `add-reminder` | Create a new reminder |
|
||||
| `list-reminders` | View all pending reminders |
|
||||
| `delete-reminder` | Remove a reminder |
|
||||
| `snooze-reminder` | Postpone a reminder |
|
||||
|
||||
## Data Schema
|
||||
|
||||
### Reminders Table
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `id` | String | Unique identifier (REM-YYYYMMDD-XXXX) |
|
||||
| `remindAt` | DateTime | When to send the reminder |
|
||||
| `message` | String | Reminder content/subject |
|
||||
| `notifyBy` | String | Notification channel (email, sms, chat) |
|
||||
| `email` | Email | User's email address |
|
||||
| `phone` | Phone | User's phone number |
|
||||
| `created` | DateTime | Creation timestamp |
|
||||
| `status` | String | pending, sent, snoozed, deleted |
|
||||
|
||||
## Usage
|
||||
|
||||
### Creating Reminders
|
||||
|
||||
**Natural Language:**
|
||||
```
|
||||
User: Remind me to call John tomorrow at 9am
|
||||
Bot: ✅ Reminder set: Call John
|
||||
When: tomorrow at 9am
|
||||
Notification: chat
|
||||
```
|
||||
|
||||
**With Parameters:**
|
||||
```
|
||||
User: Set a reminder
|
||||
Bot: When should I remind you?
|
||||
User: Next Monday at 2pm
|
||||
Bot: What should I remind you about?
|
||||
User: Submit the quarterly report
|
||||
Bot: How should I notify you? (email, sms, or chat)
|
||||
User: email
|
||||
Bot: ✅ Reminder set: Submit the quarterly report
|
||||
When: Next Monday at 2pm
|
||||
Notification: email
|
||||
```
|
||||
|
||||
### Viewing Reminders
|
||||
|
||||
```
|
||||
User: Show my reminders
|
||||
Bot: 📋 Your Reminders:
|
||||
|
||||
1. Call John
|
||||
📅 Tomorrow at 9:00 AM
|
||||
🔔 chat
|
||||
|
||||
2. Submit quarterly report
|
||||
📅 Monday, Jan 22 at 2:00 PM
|
||||
🔔 email
|
||||
|
||||
3. Team meeting prep
|
||||
📅 Friday at 3:30 PM
|
||||
🔔 chat
|
||||
```
|
||||
|
||||
### Managing Reminders
|
||||
|
||||
**Snooze:**
|
||||
```
|
||||
User: Snooze my call reminder for 1 hour
|
||||
Bot: ✅ Reminder snoozed. New time: Today at 10:00 AM
|
||||
```
|
||||
|
||||
**Delete:**
|
||||
```
|
||||
User: Delete the quarterly report reminder
|
||||
Bot: ✅ Reminder deleted: Submit the quarterly report
|
||||
```
|
||||
|
||||
## Scheduled Reminder Delivery
|
||||
|
||||
The `reminder.bas` script runs on a schedule to check and send due reminders:
|
||||
|
||||
```basic
|
||||
REM SET SCHEDULER "1 * * * * "
|
||||
|
||||
data = FIND "reminder.csv", "when=" + hour
|
||||
|
||||
IF data THEN
|
||||
TALK TO admin, data.subject
|
||||
END IF
|
||||
```
|
||||
|
||||
### Notification Channels
|
||||
|
||||
| Channel | Delivery Method |
|
||||
|---------|-----------------|
|
||||
| `chat` | Message in bot conversation |
|
||||
| `email` | Email to user's address |
|
||||
| `sms` | SMS to user's phone |
|
||||
|
||||
## Configuration
|
||||
|
||||
Configure in `reminder.gbot/config.csv`:
|
||||
|
||||
| Parameter | Description | Example |
|
||||
|-----------|-------------|---------|
|
||||
| `Default Notification` | Default channel | `chat` |
|
||||
| `Snooze Duration` | Default snooze time | `15` (minutes) |
|
||||
| `Check Interval` | How often to check | `1` (minute) |
|
||||
| `Timezone` | User timezone | `America/New_York` |
|
||||
| `Max Reminders` | Limit per user | `100` |
|
||||
|
||||
## Customization
|
||||
|
||||
### Custom Notification Channels
|
||||
|
||||
Add new notification types:
|
||||
|
||||
```basic
|
||||
' In add-reminder.bas
|
||||
SWITCH notify
|
||||
CASE "chat"
|
||||
' Default chat notification
|
||||
CASE "email"
|
||||
SEND EMAIL email, "Reminder: " + subject, message
|
||||
CASE "sms"
|
||||
SEND SMS phone, "Reminder: " + subject
|
||||
CASE "slack"
|
||||
POST "https://hooks.slack.com/...", {"text": "Reminder: " + subject}
|
||||
CASE "teams"
|
||||
POST "https://outlook.office.com/webhook/...", {"text": subject}
|
||||
END SWITCH
|
||||
```
|
||||
|
||||
### Recurring Reminders
|
||||
|
||||
Add support for recurring reminders:
|
||||
|
||||
```basic
|
||||
' add-recurring-reminder.bas
|
||||
PARAM subject AS STRING DESCRIPTION "What to remind about"
|
||||
PARAM schedule AS STRING LIKE "daily" DESCRIPTION "Frequency: daily, weekly, monthly"
|
||||
PARAM time AS STRING LIKE "9:00 AM" DESCRIPTION "Time of day"
|
||||
|
||||
DESCRIPTION "Create a recurring reminder"
|
||||
|
||||
SET SCHEDULE cron_expression, "send-recurring.bas"
|
||||
|
||||
WITH reminder
|
||||
id = "REC-" + FORMAT(GUID())
|
||||
message = subject
|
||||
frequency = schedule
|
||||
remindTime = time
|
||||
status = "active"
|
||||
END WITH
|
||||
|
||||
SAVE "recurring_reminders.csv", reminder
|
||||
```
|
||||
|
||||
### Priority Levels
|
||||
|
||||
Add priority support:
|
||||
|
||||
```basic
|
||||
PARAM priority AS STRING LIKE "high" DESCRIPTION "Priority: low, medium, high" OPTIONAL
|
||||
|
||||
IF priority = "high" THEN
|
||||
' Send via multiple channels
|
||||
SEND EMAIL email, "🔴 URGENT: " + subject, message
|
||||
SEND SMS phone, "URGENT: " + subject
|
||||
END IF
|
||||
```
|
||||
|
||||
### Smart Suggestions
|
||||
|
||||
Add context-aware suggestions based on time:
|
||||
|
||||
```basic
|
||||
hour = HOUR(NOW())
|
||||
|
||||
IF hour < 12 THEN
|
||||
ADD SUGGESTION "today" AS "Remind me today"
|
||||
ADD SUGGESTION "afternoon" AS "This afternoon"
|
||||
ELSE
|
||||
ADD SUGGESTION "tomorrow" AS "Tomorrow morning"
|
||||
ADD SUGGESTION "evening" AS "This evening"
|
||||
END IF
|
||||
|
||||
ADD SUGGESTION "week" AS "Next week"
|
||||
ADD SUGGESTION "list" AS "My reminders"
|
||||
```
|
||||
|
||||
## Integration Examples
|
||||
|
||||
### With Calendar
|
||||
|
||||
```basic
|
||||
' Sync reminder to calendar
|
||||
IF reminder.notifyBy = "calendar" THEN
|
||||
CREATE CALENDAR EVENT reminder.message, reminder.remindAt, 15
|
||||
END IF
|
||||
```
|
||||
|
||||
### With Tasks
|
||||
|
||||
```basic
|
||||
' Convert reminder to task when due
|
||||
IF reminder.status = "sent" THEN
|
||||
CREATE TASK reminder.message, "medium", user_email
|
||||
END IF
|
||||
```
|
||||
|
||||
### With CRM
|
||||
|
||||
```basic
|
||||
' Add follow-up reminder from CRM
|
||||
PARAM contact_id AS STRING DESCRIPTION "Contact to follow up with"
|
||||
PARAM days AS INTEGER LIKE 7 DESCRIPTION "Days until follow-up"
|
||||
|
||||
contact = FIND "contacts.csv", "id = " + contact_id
|
||||
|
||||
WITH reminder
|
||||
id = FORMAT(GUID())
|
||||
message = "Follow up with " + contact.name
|
||||
remindAt = DATEADD(NOW(), days, "day")
|
||||
notifyBy = "chat"
|
||||
relatedTo = contact_id
|
||||
END WITH
|
||||
|
||||
SAVE "reminders.csv", reminder
|
||||
```
|
||||
|
||||
## Example Conversations
|
||||
|
||||
### Quick Reminder
|
||||
|
||||
```
|
||||
User: remind me in 30 minutes to take a break
|
||||
Bot: ✅ Reminder set: Take a break
|
||||
When: in 30 minutes (2:45 PM)
|
||||
Notification: chat
|
||||
```
|
||||
|
||||
### Work Reminder
|
||||
|
||||
```
|
||||
User: I need to remember to review the PR before EOD
|
||||
Bot: I'll set a reminder. What time should I remind you?
|
||||
User: 4:30pm
|
||||
Bot: ✅ Reminder set: Review the PR before EOD
|
||||
When: Today at 4:30 PM
|
||||
Notification: chat
|
||||
```
|
||||
|
||||
### Today's Reminders
|
||||
|
||||
```
|
||||
User: What's on my plate today?
|
||||
Bot: 📋 Today's Reminders:
|
||||
|
||||
⏰ 10:00 AM - Team standup
|
||||
⏰ 2:00 PM - Client call
|
||||
⏰ 4:30 PM - Review the PR
|
||||
|
||||
You have 3 reminders for today.
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Be specific** - Include enough detail in reminder messages
|
||||
2. **Set appropriate times** - Don't set reminders for odd hours
|
||||
3. **Use the right channel** - Critical reminders via multiple channels
|
||||
4. **Clean up** - Delete completed reminders regularly
|
||||
5. **Review regularly** - Check reminder list to stay organized
|
||||
6. **Test notifications** - Verify each channel works before relying on it
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Issue | Cause | Solution |
|
||||
|-------|-------|----------|
|
||||
| Reminder not sent | Scheduler not running | Verify cron job is active |
|
||||
| Wrong time | Timezone mismatch | Configure correct timezone |
|
||||
| No notification | Missing contact info | Ensure email/phone is set |
|
||||
| Duplicate reminders | Created multiple times | Check for existing before adding |
|
||||
| Past date accepted | No validation | Add date validation logic |
|
||||
|
||||
## Date Parsing Examples
|
||||
|
||||
The LLM understands various date formats:
|
||||
|
||||
| Input | Parsed As |
|
||||
|-------|-----------|
|
||||
| "tomorrow" | Next day, 9:00 AM |
|
||||
| "tomorrow at 3pm" | Next day, 3:00 PM |
|
||||
| "in 2 hours" | Current time + 2 hours |
|
||||
| "next Monday" | Coming Monday, 9:00 AM |
|
||||
| "end of day" | Today, 5:00 PM |
|
||||
| "next week" | 7 days from now |
|
||||
| "January 15" | Jan 15, current year |
|
||||
| "1/15 at noon" | Jan 15, 12:00 PM |
|
||||
|
||||
## Related Templates
|
||||
|
||||
- `office.gbai` - Office productivity with task management
|
||||
- `crm.gbai` - CRM with follow-up reminders
|
||||
- `contacts.gbai` - Contact management with activity tracking
|
||||
- `marketing.gbai` - Marketing with scheduled broadcasts
|
||||
|
||||
## Use Cases
|
||||
|
||||
- **Personal Productivity** - Don't forget important tasks
|
||||
- **Team Coordination** - Remind team members of deadlines
|
||||
- **Customer Follow-ups** - Schedule sales and support follow-ups
|
||||
- **Meeting Prep** - Get reminded before meetings
|
||||
- **Health & Wellness** - Regular break and wellness reminders
|
||||
|
||||
## License
|
||||
|
||||
AGPL-3.0 - Part of General Bots Open Source Platform.
|
||||
|
||||
---
|
||||
|
||||
**Pragmatismo** - General Bots
|
||||
485
templates/sales/crm.gbai/README.md
Normal file
485
templates/sales/crm.gbai/README.md
Normal file
|
|
@ -0,0 +1,485 @@
|
|||
# Sales CRM Template (crm.gbai)
|
||||
|
||||
A comprehensive General Bots template for sales customer relationship management with lead tracking, opportunity management, and sales pipeline automation.
|
||||
|
||||
## Overview
|
||||
|
||||
The CRM template provides a full-featured sales CRM system with conversational AI capabilities. It enables sales teams to manage leads, track opportunities through the pipeline, generate quotes, send proposals, and forecast revenue—all through natural conversation or automated workflows.
|
||||
|
||||
## Features
|
||||
|
||||
- **Lead Management** - Capture, qualify, convert, and nurture leads
|
||||
- **Opportunity Pipeline** - Track deals through customizable stages
|
||||
- **Account Management** - Manage customer accounts and contacts
|
||||
- **Activity Tracking** - Log calls, emails, meetings, and tasks
|
||||
- **Quote Generation** - Create and send professional quotes
|
||||
- **Proposal Automation** - Generate and deliver sales proposals
|
||||
- **Sales Forecasting** - Pipeline analysis and revenue projections
|
||||
- **Email Integration** - Receive and process emails automatically
|
||||
- **Sentiment Analysis** - AI-powered customer sentiment tracking
|
||||
- **Data Enrichment** - Automatic lead data enhancement
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
crm.gbai/
|
||||
├── README.md
|
||||
├── crm.gbdialog/
|
||||
│ ├── lead-management.bas # Lead lifecycle management
|
||||
│ ├── opportunity-management.bas # Opportunity pipeline
|
||||
│ ├── account-management.bas # Account/company management
|
||||
│ ├── activity-tracking.bas # Activity logging
|
||||
│ ├── case-management.bas # Support case handling
|
||||
│ ├── analyze-customer-sentiment.bas # AI sentiment analysis
|
||||
│ ├── data-enrichment.bas # Lead data enhancement
|
||||
│ ├── send-proposal.bas # Proposal generation
|
||||
│ ├── create-lead-from-draft.bas # Email to lead conversion
|
||||
│ ├── crm-jobs.bas # Scheduled background jobs
|
||||
│ ├── tables.bas # Database schema definitions
|
||||
│ └── ... (additional scripts)
|
||||
└── crm.gbot/
|
||||
└── config.csv # Bot configuration
|
||||
```
|
||||
|
||||
## Scripts
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `lead-management.bas` | Complete lead lifecycle: capture, qualify, convert, follow-up, nurture |
|
||||
| `opportunity-management.bas` | Pipeline stages, quotes, products, forecasting |
|
||||
| `account-management.bas` | Account and contact management |
|
||||
| `activity-tracking.bas` | Log and track all sales activities |
|
||||
| `case-management.bas` | Customer support case handling |
|
||||
| `analyze-customer-sentiment.bas` | AI-powered sentiment analysis |
|
||||
| `data-enrichment.bas` | Enrich leads with external data |
|
||||
| `send-proposal.bas` | Generate and send proposals |
|
||||
| `on-receive-email.bas` | Process incoming emails |
|
||||
| `crm-jobs.bas` | Scheduled automation tasks |
|
||||
| `tables.bas` | CRM database schema |
|
||||
|
||||
## Data Schema
|
||||
|
||||
### Leads Table
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `id` | GUID | Unique identifier |
|
||||
| `name` | String | Lead name |
|
||||
| `email` | Email | Email address |
|
||||
| `phone` | Phone | Phone number |
|
||||
| `company` | String | Company name |
|
||||
| `source` | String | Lead source |
|
||||
| `status` | String | new, qualified, hot, warm, cold, converted |
|
||||
| `score` | Integer | Lead qualification score (0-100) |
|
||||
| `assigned_to` | String | Sales rep ID |
|
||||
| `created_at` | DateTime | Creation timestamp |
|
||||
|
||||
### Opportunities Table
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `id` | GUID | Unique identifier |
|
||||
| `name` | String | Opportunity name |
|
||||
| `account_id` | GUID | Related account |
|
||||
| `contact_id` | GUID | Primary contact |
|
||||
| `amount` | Decimal | Deal value |
|
||||
| `stage` | String | Pipeline stage |
|
||||
| `probability` | Integer | Win probability (0-100) |
|
||||
| `close_date` | Date | Expected close date |
|
||||
| `owner_id` | String | Sales rep ID |
|
||||
| `lead_source` | String | Original lead source |
|
||||
|
||||
### Accounts Table
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `id` | GUID | Unique identifier |
|
||||
| `name` | String | Company name |
|
||||
| `type` | String | prospect, customer, partner |
|
||||
| `industry` | String | Industry vertical |
|
||||
| `owner_id` | String | Account owner |
|
||||
| `created_from_lead` | GUID | Original lead ID |
|
||||
|
||||
### Contacts Table
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `id` | GUID | Unique identifier |
|
||||
| `account_id` | GUID | Parent account |
|
||||
| `name` | String | Full name |
|
||||
| `email` | Email | Email address |
|
||||
| `phone` | Phone | Phone number |
|
||||
| `title` | String | Job title |
|
||||
| `primary_contact` | Boolean | Primary contact flag |
|
||||
|
||||
### Activities Table
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `id` | GUID | Unique identifier |
|
||||
| `type` | String | call, email, meeting, task |
|
||||
| `subject` | String | Activity subject |
|
||||
| `lead_id` | GUID | Related lead |
|
||||
| `opportunity_id` | GUID | Related opportunity |
|
||||
| `created_at` | DateTime | Activity timestamp |
|
||||
|
||||
## Pipeline Stages
|
||||
|
||||
| Stage | Probability | Description |
|
||||
|-------|-------------|-------------|
|
||||
| `qualification` | 10% | Initial qualification |
|
||||
| `needs_analysis` | 20% | Understanding requirements |
|
||||
| `value_proposition` | 50% | Presenting solution |
|
||||
| `decision_makers` | 60% | Engaging decision makers |
|
||||
| `proposal` | 75% | Proposal sent |
|
||||
| `negotiation` | 90% | Terms negotiation |
|
||||
| `closed_won` | 100% | Deal closed - won |
|
||||
| `closed_lost` | 0% | Deal closed - lost |
|
||||
|
||||
## Lead Management
|
||||
|
||||
### Lead Capture
|
||||
|
||||
```basic
|
||||
' Capture a new lead
|
||||
WITH new_lead
|
||||
id = FORMAT(GUID())
|
||||
name = lead_data.name
|
||||
email = lead_data.email
|
||||
phone = lead_data.phone
|
||||
company = lead_data.company
|
||||
source = lead_data.source
|
||||
status = "new"
|
||||
score = 0
|
||||
created_at = NOW()
|
||||
assigned_to = user_id
|
||||
END WITH
|
||||
|
||||
SAVE "leads.csv", new_lead
|
||||
```
|
||||
|
||||
### Lead Qualification (BANT)
|
||||
|
||||
The qualification process scores leads based on:
|
||||
|
||||
- **Budget** - Revenue range (up to 30 points)
|
||||
- **Authority** - Employee count/company size (up to 25 points)
|
||||
- **Need** - Timeline urgency (up to 30 points)
|
||||
- **Timeline** - Budget allocation (up to 25 points)
|
||||
|
||||
Scoring thresholds:
|
||||
- **Hot Lead** (≥70): Immediate follow-up
|
||||
- **Warm Lead** (50-69): 24-hour response
|
||||
- **Cold Lead** (30-49): Nurture campaign
|
||||
- **Unqualified** (<30): Archive
|
||||
|
||||
### Lead Conversion
|
||||
|
||||
When converting a lead, the system automatically creates:
|
||||
1. Account record
|
||||
2. Contact record
|
||||
3. Opportunity record
|
||||
|
||||
```basic
|
||||
' Convert qualified lead
|
||||
IF lead.status = "hot" OR lead.status = "warm" THEN
|
||||
' Create account
|
||||
SAVE "accounts.csv", account
|
||||
|
||||
' Create contact
|
||||
SAVE "contacts.csv", contact
|
||||
|
||||
' Create opportunity
|
||||
SAVE "opportunities.csv", opportunity
|
||||
|
||||
' Update lead status
|
||||
UPDATE "leads.csv" SET status = "converted"
|
||||
END IF
|
||||
```
|
||||
|
||||
### Lead Nurturing
|
||||
|
||||
Automated nurture campaigns based on lead age:
|
||||
|
||||
| Days | Content |
|
||||
|------|---------|
|
||||
| 3 | 5 Tips to Improve Your Business |
|
||||
| 7 | Case Study: How We Helped Similar Companies |
|
||||
| 14 | Free Consultation Offer |
|
||||
| 30 | Special Limited Time Offer |
|
||||
|
||||
## Opportunity Management
|
||||
|
||||
### Creating Opportunities
|
||||
|
||||
```
|
||||
User: Create a new opportunity for Acme Corp
|
||||
Bot: What should we call this opportunity?
|
||||
User: Enterprise License Deal
|
||||
Bot: What is the estimated value of this deal?
|
||||
User: $50,000
|
||||
Bot: When do you expect to close this deal?
|
||||
User: End of Q2
|
||||
Bot: ✅ Opportunity created: Enterprise License Deal
|
||||
Account: Acme Corp
|
||||
Value: $50,000
|
||||
Close Date: June 30, 2024
|
||||
```
|
||||
|
||||
### Updating Pipeline Stage
|
||||
|
||||
```
|
||||
User: Update the Acme deal to proposal stage
|
||||
Bot: Current stage: value_proposition
|
||||
|
||||
Select new stage:
|
||||
1. Qualification (10%)
|
||||
2. Needs Analysis (20%)
|
||||
3. Value Proposition (50%)
|
||||
4. Decision Makers (60%)
|
||||
5. Proposal (75%)
|
||||
6. Negotiation (90%)
|
||||
7. Closed Won (100%)
|
||||
8. Closed Lost (0%)
|
||||
|
||||
User: 5
|
||||
Bot: ✅ Stage updated to proposal (75%)
|
||||
```
|
||||
|
||||
### Quote Generation
|
||||
|
||||
```basic
|
||||
' Generate quote from opportunity
|
||||
quote_content = "QUOTATION\n"
|
||||
quote_content = quote_content + "Quote #: " + quote.quote_number + "\n"
|
||||
quote_content = quote_content + "To: " + account.name + "\n\n"
|
||||
quote_content = quote_content + "ITEMS:\n"
|
||||
|
||||
FOR EACH item IN products DO
|
||||
quote_content = quote_content + item.product_name + " x " + item.quantity +
|
||||
" @ $" + item.unit_price + " = $" + item.total + "\n"
|
||||
END FOR
|
||||
|
||||
quote_content = quote_content + "\nSubtotal: $" + quote.subtotal + "\n"
|
||||
quote_content = quote_content + "Tax (10%): $" + quote.tax_amount + "\n"
|
||||
quote_content = quote_content + "TOTAL: $" + quote.total + "\n"
|
||||
```
|
||||
|
||||
### Sales Forecasting
|
||||
|
||||
```
|
||||
User: Show me the sales forecast
|
||||
Bot: 📊 SALES FORECAST
|
||||
==============
|
||||
Total Pipeline: $425,000
|
||||
Weighted Pipeline: $187,500
|
||||
|
||||
Quarterly Forecast:
|
||||
Q1: $45,000
|
||||
Q2: $82,500
|
||||
Q3: $35,000
|
||||
Q4: $25,000
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
Configure in `crm.gbot/config.csv`:
|
||||
|
||||
| Parameter | Description | Example |
|
||||
|-----------|-------------|---------|
|
||||
| `Company Name` | Your company name | `Acme Sales` |
|
||||
| `Currency` | Default currency | `USD` |
|
||||
| `Tax Rate` | Default tax percentage | `10` |
|
||||
| `Quote Validity Days` | Quote expiration | `30` |
|
||||
| `Pipeline Stages` | Custom stage definitions | (JSON) |
|
||||
| `Lead Sources` | Available lead sources | `web,referral,event` |
|
||||
| `Admin Email` | Notifications email | `sales@company.com` |
|
||||
|
||||
## Email Integration
|
||||
|
||||
### Receiving Emails
|
||||
|
||||
```basic
|
||||
' on-receive-email.bas
|
||||
email_from = GET "email.from"
|
||||
email_subject = GET "email.subject"
|
||||
email_body = GET "email.body"
|
||||
|
||||
' Check if from existing contact
|
||||
contact = FIND "contacts.csv", "email = '" + email_from + "'"
|
||||
|
||||
IF contact THEN
|
||||
' Log activity against contact
|
||||
WITH activity
|
||||
type = "email"
|
||||
subject = email_subject
|
||||
contact_id = contact.id
|
||||
END WITH
|
||||
SAVE "activities.csv", activity
|
||||
ELSE
|
||||
' Create new lead from email
|
||||
CALL "create-lead-from-draft.bas"
|
||||
END IF
|
||||
```
|
||||
|
||||
### Sending Proposals
|
||||
|
||||
```basic
|
||||
' send-proposal.bas
|
||||
proposal = GENERATE FROM TEMPLATE "proposal_template.docx" WITH {
|
||||
"company": account.name,
|
||||
"contact": contact.name,
|
||||
"products": opportunity_products,
|
||||
"total": quote.total,
|
||||
"valid_until": quote.valid_until
|
||||
}
|
||||
|
||||
SEND EMAIL contact.email, "Proposal: " + opportunity.name,
|
||||
"Please find attached our proposal.", ATTACHMENT proposal
|
||||
```
|
||||
|
||||
## AI Features
|
||||
|
||||
### Customer Sentiment Analysis
|
||||
|
||||
```basic
|
||||
' analyze-customer-sentiment.bas
|
||||
SET CONTEXT "Analyze customer communication for sentiment and buying signals."
|
||||
|
||||
communications = FIND "activities.csv", "contact_id = '" + contact_id + "'"
|
||||
|
||||
analysis = LLM "Analyze these customer communications and provide:
|
||||
1. Overall sentiment (positive, neutral, negative)
|
||||
2. Buying signals detected
|
||||
3. Concerns or objections
|
||||
4. Recommended next action
|
||||
|
||||
Communications: " + JSON(communications)
|
||||
|
||||
TALK analysis
|
||||
```
|
||||
|
||||
### Data Enrichment
|
||||
|
||||
```basic
|
||||
' data-enrichment.bas
|
||||
' Enrich lead with external data
|
||||
company_info = GET "https://api.enrichment.com/company/" + lead.company
|
||||
|
||||
IF company_info THEN
|
||||
lead.industry = company_info.industry
|
||||
lead.employee_count = company_info.employees
|
||||
lead.revenue_range = company_info.revenue
|
||||
lead.linkedin_url = company_info.linkedin
|
||||
|
||||
UPDATE "leads.csv", lead
|
||||
END IF
|
||||
```
|
||||
|
||||
## Scheduled Jobs
|
||||
|
||||
| Job | Schedule | Description |
|
||||
|-----|----------|-------------|
|
||||
| Lead nurturing | Daily | Send nurture emails to cold/warm leads |
|
||||
| Follow-up reminders | Hourly | Alert reps of overdue follow-ups |
|
||||
| Pipeline cleanup | Weekly | Archive stale opportunities |
|
||||
| Forecast update | Daily | Recalculate sales forecast |
|
||||
| Activity sync | Real-time | Sync emails and calendar events |
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### Full Lead Lifecycle
|
||||
|
||||
```
|
||||
User: I just got a lead from the website
|
||||
Bot: Great! I'll help you capture it. What's their name?
|
||||
User: John Smith from TechCorp
|
||||
Bot: What's their email?
|
||||
User: john@techcorp.com
|
||||
Bot: ✅ Lead captured: John Smith (TechCorp)
|
||||
ID: LEAD-20240115-4821
|
||||
|
||||
Would you like to qualify this lead now?
|
||||
|
||||
User: Yes
|
||||
Bot: I'll ask a few questions to qualify them.
|
||||
What is TechCorp's annual revenue range?
|
||||
1. Under $1M
|
||||
2. $1M - $10M
|
||||
3. $10M - $50M
|
||||
4. Over $50M
|
||||
|
||||
User: 3
|
||||
Bot: How many employees?
|
||||
User: About 200
|
||||
Bot: What's their timeline?
|
||||
User: This quarter
|
||||
Bot: Do they have budget allocated?
|
||||
User: Yes
|
||||
|
||||
Bot: 🔥 Hot Lead! Score: 85/100
|
||||
This lead is a great fit. I've:
|
||||
- Notified sales@company.com
|
||||
- Created a follow-up task
|
||||
|
||||
Would you like to convert to an opportunity?
|
||||
|
||||
User: Yes
|
||||
Bot: ✅ Lead converted!
|
||||
- Account created: TechCorp
|
||||
- Contact created: John Smith
|
||||
- Opportunity created: Opportunity for TechCorp
|
||||
|
||||
What stage should we start at?
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Qualify early** - Use BANT scoring to prioritize leads
|
||||
2. **Track everything** - Log all customer interactions
|
||||
3. **Follow up promptly** - Hot leads within hours, warm within 24h
|
||||
4. **Use automation** - Let nurture campaigns work cold leads
|
||||
5. **Clean pipeline** - Archive stale opportunities regularly
|
||||
6. **Forecast accurately** - Keep close dates and probabilities updated
|
||||
7. **Segment leads** - Use tags and sources for better targeting
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Issue | Cause | Solution |
|
||||
|-------|-------|----------|
|
||||
| Lead not found | Search criteria too strict | Use partial match |
|
||||
| Stage not updating | Missing opportunity ID | Set opportunity in session |
|
||||
| Quote not generating | Missing products | Add products to opportunity first |
|
||||
| Email not sending | Missing contact email | Verify contact record |
|
||||
| Forecast incorrect | Stale data | Update opportunity amounts |
|
||||
|
||||
## Related Templates
|
||||
|
||||
- `contacts.gbai` - Contact directory management
|
||||
- `marketing.gbai` - Marketing automation and campaigns
|
||||
- `analytics.gbai` - Sales analytics and reporting
|
||||
- `reminder.gbai` - Follow-up reminders
|
||||
|
||||
## Use Cases
|
||||
|
||||
- **Inside Sales** - Lead qualification and opportunity management
|
||||
- **Field Sales** - Account management and activity tracking
|
||||
- **Sales Management** - Pipeline visibility and forecasting
|
||||
- **Business Development** - Lead generation and nurturing
|
||||
- **Customer Success** - Account health and expansion opportunities
|
||||
|
||||
## Integration Points
|
||||
|
||||
- **Email** - Inbound/outbound email tracking
|
||||
- **Calendar** - Meeting scheduling
|
||||
- **ERP** - Order and billing sync
|
||||
- **Marketing Automation** - Lead handoff
|
||||
- **Support Ticketing** - Case management
|
||||
|
||||
## License
|
||||
|
||||
AGPL-3.0 - Part of General Bots Open Source Platform.
|
||||
|
||||
---
|
||||
|
||||
**Pragmatismo** - General Bots
|
||||
458
templates/sales/marketing.gbai/README.md
Normal file
458
templates/sales/marketing.gbai/README.md
Normal file
|
|
@ -0,0 +1,458 @@
|
|||
# Marketing Automation Template (marketing.gbai)
|
||||
|
||||
A General Bots template for marketing campaign management, content creation, and multi-channel broadcast messaging.
|
||||
|
||||
## Overview
|
||||
|
||||
The Marketing template provides marketing automation capabilities including campaign management, content ideation, image generation, social media posting, and WhatsApp broadcast messaging. It enables marketing teams to create, schedule, and deliver campaigns through conversational AI.
|
||||
|
||||
## Features
|
||||
|
||||
- **Campaign Management** - Create and organize marketing campaigns
|
||||
- **Content Ideation** - AI-assisted content idea generation
|
||||
- **Image Generation** - AI-powered marketing visuals
|
||||
- **Social Media Posting** - Direct posting to Instagram and other platforms
|
||||
- **WhatsApp Broadcasts** - Mass messaging with template support
|
||||
- **Contact Segmentation** - Target specific audience segments
|
||||
- **Template Compliance** - META-approved template validation
|
||||
- **Broadcast Logging** - Track delivery and engagement
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
marketing.gbai/
|
||||
├── README.md
|
||||
├── marketing.gbdialog/
|
||||
│ ├── add-new-idea.bas # Content ideation tool
|
||||
│ ├── broadcast.bas # WhatsApp broadcast messaging
|
||||
│ ├── get-image.bas # AI image generation
|
||||
│ ├── post-to-instagram.bas # Instagram posting
|
||||
│ ├── poster.bas # Marketing poster creation
|
||||
│ └── campaigns/ # Campaign templates
|
||||
└── marketing.gbot/
|
||||
└── config.csv # Bot configuration
|
||||
```
|
||||
|
||||
## Scripts
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `add-new-idea.bas` | Generate and save marketing content ideas |
|
||||
| `broadcast.bas` | Send WhatsApp broadcasts to contact lists |
|
||||
| `get-image.bas` | Generate marketing images with AI |
|
||||
| `post-to-instagram.bas` | Post content to Instagram |
|
||||
| `poster.bas` | Create marketing posters and visuals |
|
||||
|
||||
## WhatsApp Broadcast
|
||||
|
||||
The `broadcast.bas` script enables mass WhatsApp messaging with template support:
|
||||
|
||||
### Parameters
|
||||
|
||||
| Parameter | Type | Description | Example |
|
||||
|-----------|------|-------------|---------|
|
||||
| `message` | STRING | Message with variables | `"Olá {name}, confira nossas novidades!"` |
|
||||
| `template_file` | FILE | Header image for template | `header.jpg` |
|
||||
| `list_file` | FILE | Contact list with phone numbers | `contacts.xlsx` |
|
||||
| `filter` | STRING | Optional filter condition | `"Perfil=VIP"` |
|
||||
|
||||
### Usage
|
||||
|
||||
```basic
|
||||
PARAM message AS STRING LIKE "Olá {name}, confira nossas novidades!"
|
||||
DESCRIPTION "Message to broadcast, supports {name} and {telefone} variables"
|
||||
PARAM template_file AS FILE LIKE "header.jpg"
|
||||
DESCRIPTION "Header image file for the template"
|
||||
PARAM list_file AS FILE LIKE "contacts.xlsx"
|
||||
DESCRIPTION "File with contacts (must have telefone column)"
|
||||
PARAM filter AS STRING LIKE "Perfil=VIP"
|
||||
DESCRIPTION "Filter condition for contact list" OPTIONAL
|
||||
|
||||
DESCRIPTION "Send marketing broadcast message to a filtered contact list via WhatsApp template"
|
||||
```
|
||||
|
||||
### Template Compliance
|
||||
|
||||
The system validates messages for META WhatsApp template approval:
|
||||
|
||||
```basic
|
||||
report = LLM "Esta mensagem será aprovada pelo WhatsApp META como Template?
|
||||
Responda OK se sim, ou explique o problema: " + message
|
||||
|
||||
IF report <> "OK" THEN
|
||||
TALK "Atenção: " + report
|
||||
END IF
|
||||
```
|
||||
|
||||
### Broadcast Execution
|
||||
|
||||
```basic
|
||||
IF filter THEN
|
||||
list = FIND list_file, filter
|
||||
ELSE
|
||||
list = FIND list_file
|
||||
END IF
|
||||
|
||||
index = 1
|
||||
sent = 0
|
||||
|
||||
DO WHILE index < UBOUND(list)
|
||||
row = list[index]
|
||||
|
||||
SEND TEMPLATE TO row.telefone, template_file
|
||||
|
||||
WAIT 0.1 ' Rate limiting
|
||||
|
||||
' Log delivery
|
||||
WITH logEntry
|
||||
timestamp = NOW()
|
||||
phone = row.telefone
|
||||
name = row.name
|
||||
status = "sent"
|
||||
END WITH
|
||||
|
||||
SAVE "broadcast_log.csv", logEntry
|
||||
|
||||
sent = sent + 1
|
||||
index = index + 1
|
||||
LOOP
|
||||
|
||||
TALK "Broadcast enviado para " + sent + " contatos."
|
||||
```
|
||||
|
||||
## Contact List Format
|
||||
|
||||
The contact file should include:
|
||||
|
||||
| Column | Required | Description |
|
||||
|--------|----------|-------------|
|
||||
| `telefone` | Yes | Phone number with country code |
|
||||
| `name` | No | Contact name for personalization |
|
||||
| `email` | No | Email address |
|
||||
| `Perfil` | No | Segment tag for filtering |
|
||||
|
||||
### Example contacts.xlsx
|
||||
|
||||
```csv
|
||||
telefone,name,email,Perfil
|
||||
+5511999999999,João Silva,joao@email.com,VIP
|
||||
+5511888888888,Maria Santos,maria@email.com,Regular
|
||||
+5511777777777,Pedro Costa,pedro@email.com,VIP
|
||||
```
|
||||
|
||||
## Campaign Management
|
||||
|
||||
### Creating Campaigns
|
||||
|
||||
```
|
||||
User: Create a new marketing campaign
|
||||
Bot: What's the campaign name?
|
||||
User: Black Friday 2024
|
||||
Bot: What's the campaign objective?
|
||||
User: Drive sales for electronics category
|
||||
Bot: What's the target audience?
|
||||
User: VIP customers who purchased in the last 6 months
|
||||
Bot: ✅ Campaign created: Black Friday 2024
|
||||
Objective: Drive sales for electronics
|
||||
Audience: VIP customers (last 6 months)
|
||||
```
|
||||
|
||||
### Campaign Structure
|
||||
|
||||
```basic
|
||||
WITH campaign
|
||||
id = "CAMP-" + FORMAT(NOW(), "YYYYMMDD") + "-" + FORMAT(RANDOM(1000, 9999))
|
||||
name = campaign_name
|
||||
objective = objective
|
||||
audience = audience_filter
|
||||
status = "draft"
|
||||
created_at = NOW()
|
||||
created_by = GET SESSION "user_email"
|
||||
END WITH
|
||||
|
||||
SAVE "campaigns.csv", campaign
|
||||
```
|
||||
|
||||
## Content Ideation
|
||||
|
||||
### AI-Powered Ideas
|
||||
|
||||
```basic
|
||||
' add-new-idea.bas
|
||||
PARAM topic AS STRING DESCRIPTION "Topic or product for content ideas"
|
||||
PARAM platform AS STRING LIKE "instagram" DESCRIPTION "Target platform"
|
||||
PARAM tone AS STRING LIKE "professional" DESCRIPTION "Content tone" OPTIONAL
|
||||
|
||||
DESCRIPTION "Generate marketing content ideas using AI"
|
||||
|
||||
SET CONTEXT "You are a creative marketing specialist."
|
||||
|
||||
ideas = LLM "Generate 5 creative marketing content ideas for:
|
||||
Topic: " + topic + "
|
||||
Platform: " + platform + "
|
||||
Tone: " + (tone OR "engaging") + "
|
||||
|
||||
Include:
|
||||
- Headline
|
||||
- Key message
|
||||
- Call to action
|
||||
- Hashtag suggestions"
|
||||
|
||||
TALK ideas
|
||||
|
||||
' Save ideas for future reference
|
||||
WITH idea_record
|
||||
id = FORMAT(GUID())
|
||||
topic = topic
|
||||
platform = platform
|
||||
ideas = ideas
|
||||
created_at = NOW()
|
||||
END WITH
|
||||
|
||||
SAVE "content_ideas.csv", idea_record
|
||||
```
|
||||
|
||||
## Image Generation
|
||||
|
||||
### AI Marketing Visuals
|
||||
|
||||
```basic
|
||||
' get-image.bas
|
||||
PARAM prompt AS STRING DESCRIPTION "Description of the image to generate"
|
||||
PARAM style AS STRING LIKE "photorealistic" DESCRIPTION "Image style" OPTIONAL
|
||||
PARAM size AS STRING LIKE "1080x1080" DESCRIPTION "Image dimensions" OPTIONAL
|
||||
|
||||
DESCRIPTION "Generate marketing images using AI"
|
||||
|
||||
full_prompt = prompt
|
||||
IF style THEN
|
||||
full_prompt = full_prompt + ", " + style + " style"
|
||||
END IF
|
||||
|
||||
image = GENERATE IMAGE full_prompt, size OR "1080x1080"
|
||||
|
||||
IF image THEN
|
||||
SEND FILE image, "Generated image for: " + prompt
|
||||
RETURN image
|
||||
ELSE
|
||||
TALK "Failed to generate image. Please try a different prompt."
|
||||
RETURN NULL
|
||||
END IF
|
||||
```
|
||||
|
||||
## Social Media Posting
|
||||
|
||||
### Instagram Integration
|
||||
|
||||
```basic
|
||||
' post-to-instagram.bas
|
||||
PARAM image AS FILE DESCRIPTION "Image to post"
|
||||
PARAM caption AS STRING DESCRIPTION "Post caption with hashtags"
|
||||
PARAM schedule AS STRING DESCRIPTION "Schedule time (optional)" OPTIONAL
|
||||
|
||||
DESCRIPTION "Post content to Instagram"
|
||||
|
||||
' Validate caption length
|
||||
IF LEN(caption) > 2200 THEN
|
||||
TALK "Caption too long. Maximum 2,200 characters."
|
||||
RETURN
|
||||
END IF
|
||||
|
||||
IF schedule THEN
|
||||
' Schedule for later
|
||||
SET SCHEDULE schedule, "execute-instagram-post.bas"
|
||||
SET BOT MEMORY "scheduled_post_" + FORMAT(GUID()), {
|
||||
"image": image,
|
||||
"caption": caption,
|
||||
"scheduled_for": schedule
|
||||
}
|
||||
TALK "Post scheduled for: " + schedule
|
||||
ELSE
|
||||
' Post immediately
|
||||
result = POST TO INSTAGRAM image, caption
|
||||
|
||||
IF result.success THEN
|
||||
TALK "✅ Posted to Instagram successfully!"
|
||||
TALK "Post ID: " + result.post_id
|
||||
ELSE
|
||||
TALK "❌ Failed to post: " + result.error
|
||||
END IF
|
||||
END IF
|
||||
```
|
||||
|
||||
## Poster Creation
|
||||
|
||||
### Marketing Poster Generator
|
||||
|
||||
```basic
|
||||
' poster.bas
|
||||
PARAM headline AS STRING DESCRIPTION "Main headline text"
|
||||
PARAM subheadline AS STRING DESCRIPTION "Supporting text" OPTIONAL
|
||||
PARAM product_image AS FILE DESCRIPTION "Product image" OPTIONAL
|
||||
PARAM template AS STRING LIKE "sale" DESCRIPTION "Poster template: sale, announcement, event"
|
||||
|
||||
DESCRIPTION "Create marketing posters with customizable templates"
|
||||
|
||||
' Generate poster using template
|
||||
poster = GENERATE POSTER template WITH {
|
||||
"headline": headline,
|
||||
"subheadline": subheadline,
|
||||
"image": product_image,
|
||||
"brand_color": GET CONFIG "brand_color",
|
||||
"logo": GET CONFIG "logo_file"
|
||||
}
|
||||
|
||||
SEND FILE poster, "Marketing poster: " + headline
|
||||
RETURN poster
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
Configure in `marketing.gbot/config.csv`:
|
||||
|
||||
| Parameter | Description | Example |
|
||||
|-----------|-------------|---------|
|
||||
| `Brand Color` | Primary brand color | `#FF5722` |
|
||||
| `Logo File` | Company logo path | `logo.png` |
|
||||
| `Instagram Account` | Connected IG account | `@mycompany` |
|
||||
| `WhatsApp Business ID` | WA Business account | `123456789` |
|
||||
| `Default Template` | Default broadcast template | `marketing_update` |
|
||||
| `Rate Limit` | Messages per second | `10` |
|
||||
| `Max Broadcast Size` | Maximum recipients | `1000` |
|
||||
|
||||
## Audience Segmentation
|
||||
|
||||
### Filter Examples
|
||||
|
||||
| Filter | Description |
|
||||
|--------|-------------|
|
||||
| `Perfil=VIP` | VIP customers only |
|
||||
| `Perfil=Regular AND compras>5` | Regular customers with 5+ purchases |
|
||||
| `ultima_compra>2024-01-01` | Recent purchasers |
|
||||
| `cidade=São Paulo` | Location-based |
|
||||
| `interesse=electronics` | Interest-based |
|
||||
|
||||
### Building Segments
|
||||
|
||||
```basic
|
||||
' Create reusable segments
|
||||
WITH segment
|
||||
id = "SEG-" + FORMAT(GUID())
|
||||
name = "VIP São Paulo"
|
||||
filter = "Perfil=VIP AND cidade=São Paulo"
|
||||
count = COUNT(FIND "contacts.xlsx", filter)
|
||||
created_at = NOW()
|
||||
END WITH
|
||||
|
||||
SAVE "segments.csv", segment
|
||||
```
|
||||
|
||||
## Analytics & Reporting
|
||||
|
||||
### Broadcast Analytics
|
||||
|
||||
```basic
|
||||
' Get broadcast statistics
|
||||
broadcast_id = "BROADCAST-20240115-1234"
|
||||
logs = FIND "broadcast_log.csv", "broadcast_id = '" + broadcast_id + "'"
|
||||
|
||||
total_sent = COUNT(logs)
|
||||
delivered = COUNT(FIND logs, "status = 'delivered'")
|
||||
read = COUNT(FIND logs, "status = 'read'")
|
||||
clicked = COUNT(FIND logs, "status = 'clicked'")
|
||||
|
||||
TALK "📊 Broadcast Report"
|
||||
TALK "Total Sent: " + total_sent
|
||||
TALK "Delivered: " + delivered + " (" + (delivered/total_sent*100) + "%)"
|
||||
TALK "Read: " + read + " (" + (read/total_sent*100) + "%)"
|
||||
TALK "Clicked: " + clicked + " (" + (clicked/total_sent*100) + "%)"
|
||||
```
|
||||
|
||||
## Example Workflows
|
||||
|
||||
### Product Launch Campaign
|
||||
|
||||
```
|
||||
User: Create a product launch broadcast
|
||||
Bot: What product are you launching?
|
||||
User: New wireless headphones
|
||||
Bot: I'll help you create the campaign. Let me generate some content ideas...
|
||||
|
||||
📝 Content Ideas:
|
||||
1. "Experience Sound Like Never Before 🎧"
|
||||
2. "Your Music. Your Freedom. Wireless."
|
||||
3. "Say Goodbye to Tangled Cables"
|
||||
|
||||
Which headline do you prefer?
|
||||
|
||||
User: 1
|
||||
Bot: Now let me generate a promotional image...
|
||||
[Generates AI image]
|
||||
|
||||
Here's your promotional image. Should I create the broadcast?
|
||||
|
||||
User: Yes, send to VIP customers
|
||||
Bot: ✅ Broadcast prepared:
|
||||
📱 Recipients: 234 VIP customers
|
||||
📝 Message: "Experience Sound Like Never Before 🎧"
|
||||
🖼️ Template with header image
|
||||
|
||||
Send now or schedule?
|
||||
|
||||
User: Send now
|
||||
Bot: 📤 Broadcasting...
|
||||
✅ Broadcast complete! Sent to 234 contacts.
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Template compliance** - Always validate templates before broadcast
|
||||
2. **Segment wisely** - Target relevant audiences to improve engagement
|
||||
3. **Rate limiting** - Respect platform rate limits to avoid blocks
|
||||
4. **Personalization** - Use variables for personalized messages
|
||||
5. **A/B testing** - Test different messages with small segments first
|
||||
6. **Timing** - Schedule broadcasts for optimal engagement times
|
||||
7. **Tracking** - Monitor delivery and engagement metrics
|
||||
8. **Opt-out handling** - Honor unsubscribe requests immediately
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Issue | Cause | Solution |
|
||||
|-------|-------|----------|
|
||||
| Template rejected | Non-compliant content | Review META guidelines |
|
||||
| Low delivery rate | Invalid phone numbers | Clean contact list |
|
||||
| Broadcast blocked | Rate limit exceeded | Reduce sending speed |
|
||||
| Images not generating | Invalid prompt | Simplify prompt text |
|
||||
| Instagram post failed | Auth expired | Reconnect account |
|
||||
|
||||
## Related Templates
|
||||
|
||||
- `crm.gbai` - Customer relationship management
|
||||
- `contacts.gbai` - Contact list management
|
||||
- `broadcast.gbai` - General message broadcasting
|
||||
- `analytics.gbai` - Marketing analytics
|
||||
|
||||
## Use Cases
|
||||
|
||||
- **Product Launches** - Announce new products to customers
|
||||
- **Promotions** - Send special offers and discounts
|
||||
- **Events** - Promote webinars, sales, and events
|
||||
- **Newsletters** - Regular customer communications
|
||||
- **Re-engagement** - Win back inactive customers
|
||||
- **Social Media** - Automated content posting
|
||||
|
||||
## Compliance Notes
|
||||
|
||||
- Ensure recipients have opted in to receive marketing messages
|
||||
- Honor unsubscribe requests within 24 hours
|
||||
- Follow META WhatsApp Business policies
|
||||
- Comply with GDPR/LGPD data protection requirements
|
||||
- Keep records of consent for audit purposes
|
||||
|
||||
## License
|
||||
|
||||
AGPL-3.0 - Part of General Bots Open Source Platform.
|
||||
|
||||
---
|
||||
|
||||
**Pragmatismo** - General Bots
|
||||
316
templates/template.gbai/README.md
Normal file
316
templates/template.gbai/README.md
Normal file
|
|
@ -0,0 +1,316 @@
|
|||
# Template for Creating Templates (template.gbai)
|
||||
|
||||
A General Bots meta-template that serves as a starting point for creating new bot templates.
|
||||
|
||||
## Overview
|
||||
|
||||
The Template template (yes, it's a template for templates!) provides the essential structure and best practices for creating new General Bots templates. Use this as your foundation when building custom templates for specific use cases.
|
||||
|
||||
## Features
|
||||
|
||||
- **Standard Structure** - Pre-configured folder hierarchy
|
||||
- **Best Practices** - Follows General Bots conventions
|
||||
- **Documentation Ready** - Includes README template
|
||||
- **Quick Start** - Minimal setup required
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
template.gbai/
|
||||
├── README.md # This documentation
|
||||
├── template.gbdialog/ # Dialog scripts
|
||||
│ └── send.bas # Example script (placeholder)
|
||||
├── template.gbdrive/ # File storage
|
||||
│ └── (your files here)
|
||||
├── template.gbkb/ # Knowledge base (optional)
|
||||
│ └── docs/
|
||||
└── template.gbot/ # Bot configuration
|
||||
└── config.csv
|
||||
```
|
||||
|
||||
## Creating a New Template
|
||||
|
||||
### Step 1: Copy the Template
|
||||
|
||||
```bash
|
||||
cp -r templates/template.gbai templates/your-template.gbai
|
||||
```
|
||||
|
||||
### Step 2: Rename Internal Folders
|
||||
|
||||
Rename all internal folders to match your template name:
|
||||
|
||||
```bash
|
||||
cd templates/your-template.gbai
|
||||
mv template.gbdialog your-template.gbdialog
|
||||
mv template.gbdrive your-template.gbdrive
|
||||
mv template.gbot your-template.gbot
|
||||
```
|
||||
|
||||
### Step 3: Configure Your Bot
|
||||
|
||||
Edit `your-template.gbot/config.csv`:
|
||||
|
||||
```csv
|
||||
name,value
|
||||
Bot Name,Your Bot Name
|
||||
Theme Color,blue
|
||||
Answer Mode,default
|
||||
LLM Provider,openai
|
||||
```
|
||||
|
||||
### Step 4: Create Dialog Scripts
|
||||
|
||||
Add your BASIC scripts to `your-template.gbdialog/`:
|
||||
|
||||
```basic
|
||||
' start.bas - Main entry point
|
||||
ADD TOOL "your-tool"
|
||||
|
||||
USE KB "your-template.gbkb"
|
||||
|
||||
CLEAR SUGGESTIONS
|
||||
|
||||
ADD SUGGESTION "option1" AS "First Option"
|
||||
ADD SUGGESTION "option2" AS "Second Option"
|
||||
ADD SUGGESTION "help" AS "Get Help"
|
||||
|
||||
BEGIN TALK
|
||||
**Your Bot Name**
|
||||
|
||||
Welcome! I can help you with:
|
||||
• Feature 1
|
||||
• Feature 2
|
||||
• Feature 3
|
||||
|
||||
What would you like to do?
|
||||
END TALK
|
||||
|
||||
BEGIN SYSTEM PROMPT
|
||||
You are a helpful assistant for [your use case].
|
||||
|
||||
Guidelines:
|
||||
- Be helpful and concise
|
||||
- Use the available tools when appropriate
|
||||
- Ask clarifying questions when needed
|
||||
END SYSTEM PROMPT
|
||||
```
|
||||
|
||||
### Step 5: Add Tools
|
||||
|
||||
Create tool scripts with proper parameters:
|
||||
|
||||
```basic
|
||||
' your-tool.bas
|
||||
PARAM input AS STRING LIKE "example" DESCRIPTION "Description of this parameter"
|
||||
PARAM optional_param AS STRING DESCRIPTION "Optional parameter" OPTIONAL
|
||||
|
||||
DESCRIPTION "What this tool does - this helps the LLM decide when to use it"
|
||||
|
||||
' Your implementation here
|
||||
result = DO_SOMETHING(input)
|
||||
|
||||
IF result THEN
|
||||
RETURN result
|
||||
ELSE
|
||||
RETURN {"error": "Something went wrong"}
|
||||
END IF
|
||||
```
|
||||
|
||||
### Step 6: Add Knowledge Base (Optional)
|
||||
|
||||
If your template needs reference documentation:
|
||||
|
||||
```
|
||||
your-template.gbkb/
|
||||
└── docs/
|
||||
├── feature1.md
|
||||
├── feature2.md
|
||||
└── faq.md
|
||||
```
|
||||
|
||||
### Step 7: Update README
|
||||
|
||||
Replace this README with documentation for your template:
|
||||
|
||||
```markdown
|
||||
# Your Template Name (your-template.gbai)
|
||||
|
||||
Description of what your template does.
|
||||
|
||||
## Overview
|
||||
|
||||
Detailed overview...
|
||||
|
||||
## Features
|
||||
|
||||
- Feature 1
|
||||
- Feature 2
|
||||
- Feature 3
|
||||
|
||||
## Package Structure
|
||||
|
||||
(Document your structure)
|
||||
|
||||
## Configuration
|
||||
|
||||
(Document configuration options)
|
||||
|
||||
## Usage
|
||||
|
||||
(Document how to use)
|
||||
|
||||
## Customization
|
||||
|
||||
(Document how to customize)
|
||||
|
||||
## License
|
||||
|
||||
AGPL-3.0 - Part of General Bots Open Source Platform.
|
||||
```
|
||||
|
||||
## Template Checklist
|
||||
|
||||
Before publishing your template, ensure:
|
||||
|
||||
- [ ] All folders renamed to match template name
|
||||
- [ ] `config.csv` configured with appropriate defaults
|
||||
- [ ] `start.bas` provides clear entry point
|
||||
- [ ] All tools have `PARAM` and `DESCRIPTION`
|
||||
- [ ] System prompt guides LLM behavior
|
||||
- [ ] README documents all features
|
||||
- [ ] No hardcoded credentials or secrets
|
||||
- [ ] Error handling implemented
|
||||
- [ ] Example conversations documented
|
||||
|
||||
## Naming Conventions
|
||||
|
||||
| Item | Convention | Example |
|
||||
|------|------------|---------|
|
||||
| Template folder | `kebab-case.gbai` | `my-crm.gbai` |
|
||||
| Dialog scripts | `kebab-case.bas` | `add-contact.bas` |
|
||||
| Tools | `kebab-case` | `search-products` |
|
||||
| Config keys | `Title Case` | `Theme Color` |
|
||||
| Table names | `PascalCase` | `CustomerOrders` |
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Dialog Scripts
|
||||
|
||||
1. **Clear entry point** - `start.bas` should be the main entry
|
||||
2. **Register tools** - Use `ADD TOOL` for LLM-callable functions
|
||||
3. **Set context** - Use `SET CONTEXT` and `BEGIN SYSTEM PROMPT`
|
||||
4. **Add suggestions** - Guide users with quick actions
|
||||
5. **Welcome message** - Use `BEGIN TALK` for introduction
|
||||
|
||||
### Tools
|
||||
|
||||
1. **Descriptive names** - Tool names should indicate function
|
||||
2. **Parameter examples** - Use `LIKE` to show expected format
|
||||
3. **Clear descriptions** - Help LLM understand when to use
|
||||
4. **Return values** - Always return meaningful results
|
||||
5. **Error handling** - Handle edge cases gracefully
|
||||
|
||||
### Configuration
|
||||
|
||||
1. **Sensible defaults** - Work out of the box
|
||||
2. **Document options** - Explain each setting
|
||||
3. **No secrets** - Use environment variables for credentials
|
||||
4. **Flexible** - Allow customization without code changes
|
||||
|
||||
### Documentation
|
||||
|
||||
1. **Clear overview** - Explain what the template does
|
||||
2. **Feature list** - Highlight capabilities
|
||||
3. **Usage examples** - Show common scenarios
|
||||
4. **Configuration guide** - Document all settings
|
||||
5. **Troubleshooting** - Address common issues
|
||||
|
||||
## File Templates
|
||||
|
||||
### config.csv Template
|
||||
|
||||
```csv
|
||||
name,value
|
||||
Bot Name,Your Bot Name
|
||||
Theme Color,blue
|
||||
Answer Mode,default
|
||||
LLM Provider,openai
|
||||
Admin Email,admin@company.com
|
||||
```
|
||||
|
||||
### start.bas Template
|
||||
|
||||
```basic
|
||||
' Register tools
|
||||
ADD TOOL "tool-name"
|
||||
|
||||
' Load knowledge base
|
||||
USE KB "your-template.gbkb"
|
||||
|
||||
' Configure suggestions
|
||||
CLEAR SUGGESTIONS
|
||||
ADD SUGGESTION "action" AS "Do Something"
|
||||
|
||||
' Welcome message
|
||||
BEGIN TALK
|
||||
**Bot Name**
|
||||
|
||||
Welcome message here.
|
||||
END TALK
|
||||
|
||||
' System prompt
|
||||
BEGIN SYSTEM PROMPT
|
||||
You are a helpful assistant.
|
||||
Define behavior and guidelines here.
|
||||
END SYSTEM PROMPT
|
||||
```
|
||||
|
||||
### Tool Template
|
||||
|
||||
```basic
|
||||
PARAM required_param AS STRING LIKE "example" DESCRIPTION "What this is"
|
||||
PARAM optional_param AS STRING DESCRIPTION "Optional input" OPTIONAL
|
||||
|
||||
DESCRIPTION "What this tool does"
|
||||
|
||||
' Implementation
|
||||
result = YOUR_LOGIC_HERE
|
||||
|
||||
IF result THEN
|
||||
RETURN result
|
||||
ELSE
|
||||
RETURN {"error": "Error message"}
|
||||
END IF
|
||||
```
|
||||
|
||||
## Publishing Your Template
|
||||
|
||||
1. **Test thoroughly** - Verify all features work
|
||||
2. **Document completely** - Users should be self-sufficient
|
||||
3. **Follow conventions** - Consistent with other templates
|
||||
4. **Update main README** - Add to templates list
|
||||
5. **Submit PR** - Include template and documentation
|
||||
|
||||
## Related Resources
|
||||
|
||||
- [General Bots Documentation](../../docs/src/README.md)
|
||||
- [BASIC Dialog Reference](../../docs/src/chapter-06-gbdialog/README.md)
|
||||
- [Template Samples](../../docs/src/chapter-02/template-samples.md)
|
||||
- [Existing Templates](../README.md)
|
||||
|
||||
## Support
|
||||
|
||||
For questions about creating templates:
|
||||
|
||||
- **Documentation**: See General Bots docs
|
||||
- **Issues**: GitHub Issues
|
||||
- **Community**: Discord/Slack channels
|
||||
|
||||
## License
|
||||
|
||||
AGPL-3.0 - Part of General Bots Open Source Platform.
|
||||
|
||||
---
|
||||
|
||||
**Pragmatismo** - General Bots
|
||||
Loading…
Add table
Reference in a new issue