From 2110995b7fd2d6bada5ea4c15b870e3af778f2d0 Mon Sep 17 00:00:00 2001 From: "Rodrigo Rodriguez (Pragmatismo)" Date: Wed, 3 Dec 2025 21:59:49 -0300 Subject: [PATCH] Refactor: CRM automations, monitoring homepage, webhook examples, docs standards MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Environment Variables: Simplified to ONLY VAULT_* vars, everything else in config.csv - Attendant Module: Added CRM automations (follow-ups, collections/cobranças, scheduling/agendamentos, sales/vendas) - NEW: Hosting, DNS, MDA integration docs (Namecheap, Stalwart, LLM providers) - Monitoring: Updated as live operations homepage with real data endpoints - Examples: Renamed to 'Webhook Integrations and Jobs', removed loop-based examples 1 & 5, added lead nurturing, payment collection, appointment scheduling - Documentation Standards: WhatsApp HTML style as canonical conversation format, SVG for interfaces - Reading Flow: Improved Executive Vision → Quick Start → Chapter 01 transitions with navigation tables --- src/SUMMARY.md | 4 +- src/appendix-docs-style/svg.md | 191 ++++ src/appendix-env-vars/README.md | 135 ++- .../attendance-queue.md | 392 ++++++++- src/appendix-external-services/hosting-dns.md | 325 +++++++ src/chapter-01/README.md | 133 ++- src/chapter-04-gbui/apps/chat.md | 32 +- src/chapter-04-gbui/monitoring.md | 345 +++++--- .../examples-consolidated.md | 824 +++++++----------- src/executive-vision.md | 36 +- src/introduction.md | 71 +- 11 files changed, 1692 insertions(+), 796 deletions(-) create mode 100644 src/appendix-docs-style/svg.md create mode 100644 src/appendix-external-services/hosting-dns.md diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 6b22d197..9d27084e 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -112,7 +112,7 @@ - [store.bas](./chapter-06-gbdialog/templates/store.md) - [talk-to-data.bas](./chapter-06-gbdialog/templates/talk-to-data.md) - [whatsapp.bas](./chapter-06-gbdialog/templates/whatsapp.md) - - [Consolidated Examples](./chapter-06-gbdialog/examples-consolidated.md) + - [Webhook Integrations and Jobs](./chapter-06-gbdialog/examples-consolidated.md) - [Data Sync Tools](./chapter-06-gbdialog/tools-data-sync.md) - [Keywords Reference](./chapter-06-gbdialog/keywords.md) - [TALK](./chapter-06-gbdialog/keyword-talk.md) @@ -357,6 +357,7 @@ - [Storage Services](./appendix-external-services/storage.md) - [Directory Services](./appendix-external-services/directory.md) - [Attendance Queue](./appendix-external-services/attendance-queue.md) + - [Hosting, DNS, and MDA](./appendix-external-services/hosting-dns.md) - [Time-Series Database](./appendix-external-services/timeseries.md) - [NVIDIA GPU](./appendix-external-services/nvidia.md) - [Multimodal](./appendix-external-services/multimodal.md) @@ -365,6 +366,7 @@ - [Appendix C: Environment Variables](./appendix-env-vars/README.md) - [Appendix D: Documentation Style](./appendix-docs-style/conversation-examples.md) + - [SVG and Conversation Standards](./appendix-docs-style/svg.md) [Glossary](./glossary.md) [Contact](./contact/README.md) \ No newline at end of file diff --git a/src/appendix-docs-style/svg.md b/src/appendix-docs-style/svg.md new file mode 100644 index 00000000..dd4f9795 --- /dev/null +++ b/src/appendix-docs-style/svg.md @@ -0,0 +1,191 @@ +# Documentation Style Standards + +All interface layouts in this documentation use SVG-based wireframe representations for screenshots and diagrams. Conversation examples use the WhatsApp-style HTML format for consistent, visually appealing rendering. + +--- + +## Interface Wireframes (SVG) + +All interface screenshots and layouts should use SVG wireframes located in `/assets/`. + +### Directory Structure + +``` +assets/ +├── suite/ +│ ├── chat-screen.svg +│ ├── drive-screen.svg +│ ├── calendar-screen.svg +│ ├── mail-screen.svg +│ ├── tasks-screen.svg +│ ├── meet-screen.svg +│ ├── live-monitoring-organism.svg +│ └── ... +├── chapter-01/ +│ ├── bootstrap-process.svg +│ └── session-states.svg +└── chapter-04/ + └── analytics-interface.svg +``` + +### Referencing SVG Wireframes + +Use standard HTML image syntax with responsive styling: + +```html +Chat Interface +``` + +--- + +## Conversation Examples (WhatsApp Style) + +All conversation examples throughout the book use the WhatsApp-style HTML format. This provides a familiar, visually consistent representation of bot interactions. + +### Standard Format + +```html +
+ + +
+``` + +### Complete Example + +```html +
+ + + + + +
+``` + +### Message Classes + +| Class | Usage | +|-------|-------| +| `wa-chat` | Container for the conversation | +| `wa-message` | Individual message wrapper | +| `wa-message user` | User message (right-aligned, colored) | +| `wa-message bot` | Bot message (left-aligned) | +| `wa-bubble` | Message bubble with styling | +| `wa-time` | Timestamp display | + +### Formatting Guidelines + +1. **User messages** — Use `wa-message user` class +2. **Bot messages** — Use `wa-message bot` class +3. **Timestamps** — Include `wa-time` div with realistic times +4. **Multi-line responses** — Use separate `

` tags for each line +5. **Emojis** — Use sparingly for status indicators (✅, ❌, 📧, 📅, 📁) +6. **Bold text** — Use `` for emphasis +7. **Attachments** — Indicate with 📎 emoji and filename + +### File Attachments Example + +```html +

+ + +
+``` + +--- + +## CSS Styling + +The WhatsApp chat styling is defined in `whatsapp-chat.css` and automatically included in the book build. The styles provide: + +- Familiar messaging app appearance +- Proper alignment (user right, bot left) +- Bubble styling with shadows +- Responsive layout +- Timestamp formatting + +--- + +## When to Use Each Format + +| Content Type | Format | +|--------------|--------| +| Interface screenshots | SVG wireframe | +| System architecture | SVG diagram | +| Data flow diagrams | SVG diagram | +| Bot conversations | WhatsApp HTML | +| API examples | Code blocks | +| Configuration | Code blocks | + +--- + +## Global Conversation Style Reference + +For all conversation examples throughout the book, follow the format established in: + +**[BASIC vs Automation Tools](../chapter-06-gbdialog/basic-vs-automation-tools.md)** + +This document serves as the canonical reference for: + +- Conversation formatting +- Multi-channel message representation +- Bot response styling +- User input examples + +--- + +## See Also + +- [Conversation Examples](./conversation-examples.md) — Example patterns +- [BASIC vs Automation Tools](../chapter-06-gbdialog/basic-vs-automation-tools.md) — Canonical conversation style +- [Chapter 04 Apps](../chapter-04-gbui/apps/README.md) — Interface documentation \ No newline at end of file diff --git a/src/appendix-env-vars/README.md b/src/appendix-env-vars/README.md index a5bd61f2..4d0cce7a 100644 --- a/src/appendix-env-vars/README.md +++ b/src/appendix-env-vars/README.md @@ -1,14 +1,10 @@ # Appendix C: Environment Variables -General Bots uses a minimal set of environment variables. All configuration is managed through `config.csv` files within each bot's `.gbot` folder, with secrets stored securely in Vault. +General Bots uses a **minimal set of environment variables**. All configuration is managed through `config.csv` files within each bot's `.gbot` folder, with secrets stored securely in Vault. ## Required Environment Variables -Only Vault-related environment variables are used by General Bots: - -### VAULT_* Variables - -**Purpose**: HashiCorp Vault integration for secure secrets management. +Only Vault-related environment variables are required by General Bots: | Variable | Description | Example | |----------|-------------|---------| @@ -16,63 +12,18 @@ Only Vault-related environment variables are used by General Bots: | `VAULT_TOKEN` | Authentication token | Auto-generated during bootstrap | | `VAULT_NAMESPACE` | Vault namespace (optional) | `admin` | -**Example**: -```bash -VAULT_ADDR=http://localhost:8200 -VAULT_TOKEN=hvs.your-vault-token -``` - -## Auto-Managed Services - -The following services are automatically configured through Vault: - -| Service | Management | -|---------|------------| -| PostgreSQL | Connection credentials in Vault | -| S3-Compatible Storage | Access keys in Vault | -| Cache | Connection managed via Vault | -| Email (Stalwart) | Credentials in Vault | -| LLM API Keys | Stored in Vault | - -You do **not** need to set environment variables for these services. Vault handles credential distribution and rotation automatically. - -## What NOT to Use Environment Variables For - -**All application configuration belongs in `config.csv`**: - -| Configuration | Where to Configure | -|--------------|-------------------| -| Database connection | Managed by Vault | -| Storage credentials | Managed by Vault | -| LLM API keys | Managed by Vault | -| LLM provider | `config.csv`: `llm-url` | -| Email settings | `config.csv`: `email-*` | -| Channel tokens | `config.csv`: `whatsapp-*`, etc. | -| Bot settings | `config.csv`: all bot-specific settings | -| Feature flags | `config.csv`: various keys | - -## Configuration Philosophy - -General Bots follows these principles: - -1. **Vault-First**: All secrets are managed by Vault -2. **Minimal Environment**: Only Vault address and token use environment variables -3. **config.csv for Settings**: All application configuration is in `config.csv` -4. **Per-Bot Configuration**: Each bot has its own `config.csv` in its `.gbot` folder -5. **No Hardcoded Secrets**: Never store secrets in code or config files - ## Setting Environment Variables ### Linux/macOS -```bash +```botbook/src/appendix-env-vars/example.sh#L1-2 export VAULT_ADDR=http://localhost:8200 export VAULT_TOKEN=hvs.your-vault-token ``` ### Systemd Service -```ini +```botbook/src/appendix-env-vars/example.service#L1-3 [Service] Environment="VAULT_ADDR=http://localhost:8200" Environment="VAULT_TOKEN=hvs.your-vault-token" @@ -80,31 +31,79 @@ Environment="VAULT_TOKEN=hvs.your-vault-token" ### LXC Container -When using LXC deployment, environment variables are set in the container configuration: - -```bash +```botbook/src/appendix-env-vars/example-lxc.sh#L1-2 lxc config set container-name environment.VAULT_ADDR="http://localhost:8200" lxc config set container-name environment.VAULT_TOKEN="hvs.your-vault-token" ``` -## Security Notes +## Auto-Managed Services -1. **Never commit tokens**: Use `.env` files (gitignored) or secrets management -2. **Rotate regularly**: Vault tokens should be rotated periodically -3. **Limit access**: Only the botserver process needs these variables -4. **Use TLS**: Always use HTTPS for Vault in production +The following services are **automatically configured through Vault** during bootstrap: + +| Service | Management | +|---------|------------| +| PostgreSQL | Connection credentials stored in Vault | +| S3-Compatible Storage | Access keys stored in Vault | +| Cache | Connection managed via Vault | +| Email (Stalwart) | Credentials stored in Vault | +| LLM API Keys | Stored in Vault | + +You do **not** need environment variables for these services. Vault handles credential distribution and rotation automatically. + +## Everything Else Goes in config.csv + +**All application configuration belongs in `config.csv`**, not environment variables: + +| Configuration | Where to Configure | +|--------------|-------------------| +| LLM provider/model | `config.csv`: `llm-url`, `llm-model` | +| Email settings | `config.csv`: `email-*` | +| Channel tokens | `config.csv`: `whatsapp-*`, `telegram-*`, etc. | +| Bot settings | `config.csv`: all bot-specific settings | +| Feature flags | `config.csv`: various keys | +| Theme settings | `config.csv`: `theme-*` | +| Server port | `config.csv`: `server_port` | + +### Example config.csv + +```botbook/src/appendix-env-vars/example-config.csv#L1-8 +name,value +llm-url,http://localhost:8081 +llm-model,model.gguf +server_port,8080 +theme-color1,#0d2b55 +whatsapp-business-id,your-business-id +admin-email,admin@example.com +``` + +## Configuration Philosophy + +General Bots follows these principles: + +1. **Vault-First** — All secrets are managed by Vault +2. **Minimal Environment** — Only Vault address and token use environment variables +3. **config.csv for Settings** — All application configuration is in `config.csv` +4. **Per-Bot Configuration** — Each bot has its own `config.csv` in its `.gbot` folder +5. **No Hardcoded Secrets** — Never store secrets in code or config files ## Bootstrap Process During bootstrap, General Bots: 1. Connects to Vault using `VAULT_*` variables -2. Retrieves credentials for all managed services +2. Retrieves or generates credentials for all managed services 3. Configures database, storage, cache, and other services -4. Stores service endpoints securely +4. Stores service credentials securely in Vault This eliminates the need for manual credential management. +## Security Notes + +1. **Never commit tokens** — Use `.env` files (gitignored) or secrets management +2. **Rotate regularly** — Vault tokens should be rotated periodically +3. **Limit access** — Only the botserver process needs these variables +4. **Use TLS** — Always use HTTPS for Vault in production + ## Troubleshooting ### Vault Connection Failed @@ -124,13 +123,13 @@ Verify: If a managed service (database, storage, cache) is unavailable: 1. Check Vault is running and unsealed -2. Verify secrets exist in Vault +2. Verify secrets exist in Vault at expected paths 3. Check service container/process status 4. Review logs for connection errors ## See Also -- [config.csv Format](../chapter-08-config/config-csv.md) - Bot configuration -- [Secrets Management](../chapter-08-config/secrets-management.md) - Vault integration details -- [Drive Integration](../chapter-08-config/drive.md) - Storage setup -- [Authentication](../chapter-12-auth/README.md) - Security features \ No newline at end of file +- [config.csv Format](../chapter-08-config/config-csv.md) — Bot configuration reference +- [Secrets Management](../chapter-08-config/secrets-management.md) — Vault integration details +- [Drive Integration](../chapter-08-config/drive.md) — Storage setup +- [Authentication](../chapter-12-auth/README.md) — Security features \ No newline at end of file diff --git a/src/appendix-external-services/attendance-queue.md b/src/appendix-external-services/attendance-queue.md index d893354b..4c998051 100644 --- a/src/appendix-external-services/attendance-queue.md +++ b/src/appendix-external-services/attendance-queue.md @@ -1,22 +1,27 @@ # Attendance Queue Module -Human-attendant queue management for hybrid bot/human support workflows. +Human-attendant queue management for hybrid bot/human support workflows, plus CRM automations for follow-ups, collections, scheduling, and sales. ## Overview -The attendance queue module manages handoffs from bot to human agents, tracking conversation queues, attendant availability, and real-time assignment. +The attendance queue module manages handoffs from bot to human agents, tracking conversation queues, attendant availability, and real-time assignment. It also provides automated CRM workflows that run without human intervention. + +--- ## Configuration Create `attendant.csv` in your bot's `.gbai` folder: ```csv -id,name,channel,preferences -att-001,John Smith,whatsapp,sales -att-002,Jane Doe,web,support -att-003,Bob Wilson,all,technical +id,name,channel,preferences,department +att-001,John Smith,whatsapp,sales,commercial +att-002,Jane Doe,web,support,customer-service +att-003,Bob Wilson,all,technical,engineering +att-004,Maria Santos,whatsapp,collections,finance ``` +--- + ## Queue Status | Status | Description | @@ -36,12 +41,298 @@ att-003,Bob Wilson,all,technical | `away` | Temporarily unavailable | | `offline` | Not working | +--- + +## CRM Automations + +The attendant module includes built-in CRM automations that handle common business workflows automatically. + +### Follow-Up Automation + +Automated follow-up sequences for leads and customers. + +```basic +' follow-up.bas +' Automated follow-up workflow + +SET SCHEDULE "follow-ups", "0 9 * * 1-5" + +' Find leads needing follow-up +leads_1_day = FIND "leads", "status='new' AND DATEDIFF(NOW(), last_contact) = 1" +leads_3_day = FIND "leads", "status='contacted' AND DATEDIFF(NOW(), last_contact) = 3" +leads_7_day = FIND "leads", "status='contacted' AND DATEDIFF(NOW(), last_contact) = 7" + +' 1-day follow-up: Thank you message +FOR EACH lead IN leads_1_day + SEND TEMPLATE lead.phone, "follow_up_thanks", lead.name, lead.interest + UPDATE "leads", "id=" + lead.id, "contacted", NOW() + INSERT "activities", lead.id, "follow_up", "1-day thank you sent", NOW() +NEXT lead + +' 3-day follow-up: Value proposition +FOR EACH lead IN leads_3_day + SEND TEMPLATE lead.phone, "follow_up_value", lead.name, lead.interest + UPDATE "leads", "id=" + lead.id, "nurturing", NOW() + INSERT "activities", lead.id, "follow_up", "3-day value prop sent", NOW() +NEXT lead + +' 7-day follow-up: Special offer +FOR EACH lead IN leads_7_day + SEND TEMPLATE lead.phone, "follow_up_offer", lead.name, "10%" + UPDATE "leads", "id=" + lead.id, "offer_sent", NOW() + INSERT "activities", lead.id, "follow_up", "7-day offer sent", NOW() + + ' Alert sales team for hot leads + IF lead.score >= 70 THEN + attendant = FIND "attendants", "department='commercial' AND status='online'" + IF attendant THEN + SEND MAIL attendant.email, "Hot Lead Follow-up: " + lead.name, "Lead " + lead.name + " received 7-day offer. Score: " + lead.score + END IF + END IF +NEXT lead + +PRINT "Follow-ups completed: " + UBOUND(leads_1_day) + " 1-day, " + UBOUND(leads_3_day) + " 3-day, " + UBOUND(leads_7_day) + " 7-day" +``` + +### Collections Automation (Cobranças) + +Automated payment reminders and collection workflow. + +```basic +' collections.bas +' Automated payment collection workflow + +SET SCHEDULE "collections", "0 8 * * 1-5" + +' Find overdue invoices by age +due_today = FIND "invoices", "status='pending' AND due_date = CURDATE()" +overdue_3 = FIND "invoices", "status='pending' AND DATEDIFF(NOW(), due_date) = 3" +overdue_7 = FIND "invoices", "status='pending' AND DATEDIFF(NOW(), due_date) = 7" +overdue_15 = FIND "invoices", "status='pending' AND DATEDIFF(NOW(), due_date) = 15" +overdue_30 = FIND "invoices", "status='pending' AND DATEDIFF(NOW(), due_date) >= 30" + +' Due today: Friendly reminder via WhatsApp +FOR EACH invoice IN due_today + customer = FIND "customers", "id=" + invoice.customer_id + SEND TEMPLATE customer.phone, "payment_due_today", customer.name, invoice.id, invoice.amount + INSERT "collection_log", invoice.id, "reminder_due_today", NOW() +NEXT invoice + +' 3 days overdue: First collection notice +FOR EACH invoice IN overdue_3 + customer = FIND "customers", "id=" + invoice.customer_id + SEND TEMPLATE customer.phone, "payment_overdue_3", customer.name, invoice.id, invoice.amount + SEND MAIL customer.email, "Pagamento Pendente - Fatura #" + invoice.id, "Sua fatura está vencida há 3 dias. Valor: R$ " + invoice.amount + UPDATE "invoices", "id=" + invoice.id, "first_notice_sent", NOW() + INSERT "collection_log", invoice.id, "first_notice", NOW() +NEXT invoice + +' 7 days overdue: Second notice with urgency +FOR EACH invoice IN overdue_7 + customer = FIND "customers", "id=" + invoice.customer_id + SEND TEMPLATE customer.phone, "payment_overdue_7", customer.name, invoice.id, invoice.amount + UPDATE "invoices", "id=" + invoice.id, "second_notice_sent", NOW() + INSERT "collection_log", invoice.id, "second_notice", NOW() + + ' Notify collections team + SEND MAIL "cobranca@empresa.com", "Cobrança 7 dias: " + customer.name, "Cliente: " + customer.name + "\nFatura: " + invoice.id + "\nValor: R$ " + invoice.amount +NEXT invoice + +' 15 days overdue: Final notice before action +FOR EACH invoice IN overdue_15 + customer = FIND "customers", "id=" + invoice.customer_id + late_fee = invoice.amount * 0.02 + interest = invoice.amount * 0.01 * 15 + total_due = invoice.amount + late_fee + interest + + SEND TEMPLATE customer.phone, "payment_final_notice", customer.name, invoice.id, total_due + UPDATE "invoices", "id=" + invoice.id, late_fee, interest, total_due, "final_notice_sent", NOW() + INSERT "collection_log", invoice.id, "final_notice", NOW() + + ' Assign to human attendant for follow-up call + attendant = FIND "attendants", "department='finance' AND status='online'" + IF attendant THEN + INSERT "queue", invoice.customer_id, attendant.id, "collection_call", "high", NOW() + END IF +NEXT invoice + +' 30+ days overdue: Escalate to collections +FOR EACH invoice IN overdue_30 + IF invoice.status <> "collections" THEN + customer = FIND "customers", "id=" + invoice.customer_id + UPDATE "invoices", "id=" + invoice.id, "collections", NOW() + UPDATE "customers", "id=" + customer.id, "suspended" + + SEND MAIL "juridico@empresa.com", "Inadimplência 30+ dias: " + customer.name, "Cliente enviado para cobrança jurídica.\n\nCliente: " + customer.name + "\nFatura: " + invoice.id + "\nValor total: R$ " + invoice.total_due + INSERT "collection_log", invoice.id, "sent_to_collections", NOW() + END IF +NEXT invoice + +PRINT "Collections processed: " + UBOUND(due_today) + " due today, " + UBOUND(overdue_30) + " sent to collections" +``` + +### Scheduling Automation (Agendamentos) + +Automated appointment scheduling and reminders. + +```basic +' scheduling.bas +' Automated appointment scheduling and reminders + +SET SCHEDULE "appointment-reminders", "0 7 * * *" + +' Find appointments for today and tomorrow +today_appointments = FIND "appointments", "DATE(scheduled_at) = CURDATE() AND status='confirmed'" +tomorrow_appointments = FIND "appointments", "DATE(scheduled_at) = DATE_ADD(CURDATE(), INTERVAL 1 DAY) AND status='confirmed'" + +' Send day-before reminders +FOR EACH appt IN tomorrow_appointments + customer = FIND "customers", "id=" + appt.customer_id + staff = FIND "staff", "id=" + appt.staff_id + + appt_time = FORMAT(appt.scheduled_at, "HH:mm") + appt_date = FORMAT(appt.scheduled_at, "DD/MM/YYYY") + + SEND TEMPLATE customer.phone, "appointment_reminder_24h", customer.name, appt.service, appt_date, appt_time, staff.name + UPDATE "appointments", "id=" + appt.id, "reminder_24h_sent", NOW() +NEXT appt + +' Send same-day reminders (2 hours before) +FOR EACH appt IN today_appointments + IF DATEDIFF_HOURS(appt.scheduled_at, NOW()) <= 2 AND appt.reminder_2h_sent IS NULL THEN + customer = FIND "customers", "id=" + appt.customer_id + staff = FIND "staff", "id=" + appt.staff_id + + appt_time = FORMAT(appt.scheduled_at, "HH:mm") + + SEND TEMPLATE customer.phone, "appointment_reminder_2h", customer.name, appt.service, appt_time + UPDATE "appointments", "id=" + appt.id, "reminder_2h_sent", NOW() + + ' Notify staff + SEND TEMPLATE staff.phone, "staff_appointment_alert", staff.name, customer.name, appt.service, appt_time + END IF +NEXT appt + +' Check for no-shows (30 min past appointment time) +past_appointments = FIND "appointments", "scheduled_at < DATE_SUB(NOW(), INTERVAL 30 MINUTE) AND status='confirmed'" +FOR EACH appt IN past_appointments + customer = FIND "customers", "id=" + appt.customer_id + UPDATE "appointments", "id=" + appt.id, "no_show" + INSERT "activities", appt.customer_id, "no_show", "Missed appointment: " + appt.service, NOW() + + ' Send reschedule offer + SEND TEMPLATE customer.phone, "missed_appointment", customer.name, appt.service +NEXT appt + +PRINT "Reminders sent: " + UBOUND(tomorrow_appointments) + " for tomorrow, " + UBOUND(today_appointments) + " for today" +``` + +### Sales Automation (Vendas) + +Automated sales pipeline and lead scoring. + +```basic +' sales-automation.bas +' Automated sales pipeline management + +SET SCHEDULE "sales-automation", "0 8,14,18 * * 1-5" + +' Score and prioritize leads +new_leads = FIND "leads", "score IS NULL OR score = 0" +FOR EACH lead IN new_leads + score = 0 + + ' Score based on source + IF lead.source = "website" THEN score = score + 20 + IF lead.source = "referral" THEN score = score + 30 + IF lead.source = "campaign" THEN score = score + 15 + + ' Score based on company size + IF lead.company_size = "enterprise" THEN score = score + 25 + IF lead.company_size = "mid-market" THEN score = score + 20 + IF lead.company_size = "small" THEN score = score + 10 + + ' Score based on engagement + page_views = FIND "analytics", "lead_id=" + lead.id + " AND type='page_view'" + score = score + MIN(UBOUND(page_views) * 2, 20) + + ' Score based on email opens + email_opens = FIND "email_tracking", "lead_id=" + lead.id + " AND opened=true" + score = score + MIN(UBOUND(email_opens) * 5, 25) + + UPDATE "leads", "id=" + lead.id, score, NOW() +NEXT lead + +' Auto-assign hot leads to sales reps +hot_leads = FIND "leads", "score >= 70 AND assigned_to IS NULL" +FOR EACH lead IN hot_leads + ' Round-robin assignment + available_reps = FIND "attendants", "department='commercial' AND status='online'" + IF UBOUND(available_reps) > 0 THEN + ' Get rep with fewest active leads + rep = available_reps[0] + min_leads = 999 + FOR EACH r IN available_reps + rep_leads = FIND "leads", "assigned_to='" + r.id + "' AND status NOT IN ('converted', 'lost')" + IF UBOUND(rep_leads) < min_leads THEN + min_leads = UBOUND(rep_leads) + rep = r + END IF + NEXT r + + UPDATE "leads", "id=" + lead.id, rep.id, NOW() + + ' Notify sales rep via WhatsApp + SEND TEMPLATE rep.phone, "new_hot_lead", rep.name, lead.name, lead.company, lead.score + + ' Create follow-up task + CREATE TASK "Contact hot lead: " + lead.name, rep.email, NOW() + END IF +NEXT lead + +' Move stale opportunities +stale_opportunities = FIND "opportunities", "DATEDIFF(NOW(), last_activity) > 14 AND stage NOT IN ('closed_won', 'closed_lost')" +FOR EACH opp IN stale_opportunities + owner = FIND "attendants", "id=" + opp.owner_id + + ' Send reminder to owner + SEND TEMPLATE owner.phone, "stale_opportunity", owner.name, opp.name, opp.amount, DATEDIFF(NOW(), opp.last_activity) + + ' Create urgent task + CREATE TASK "URGENT: Update stale opportunity - " + opp.name, owner.email, NOW() + + INSERT "activities", opp.id, "stale_alert", "Opportunity marked as stale", NOW() +NEXT opp + +' Generate daily pipeline report +pipeline = FIND "opportunities", "stage NOT IN ('closed_won', 'closed_lost')" +total_value = AGGREGATE "SUM", pipeline, "amount" +weighted_value = 0 +FOR EACH opp IN pipeline + weighted_value = weighted_value + (opp.amount * opp.probability / 100) +NEXT opp + +report = "📊 Pipeline Diário\n\n" +report = report + "Total Pipeline: R$ " + FORMAT(total_value, "#,##0.00") + "\n" +report = report + "Valor Ponderado: R$ " + FORMAT(weighted_value, "#,##0.00") + "\n" +report = report + "Oportunidades Ativas: " + UBOUND(pipeline) + "\n" +report = report + "Leads Quentes: " + UBOUND(hot_leads) + +SEND MAIL "vendas@empresa.com", "Pipeline Diário - " + FORMAT(NOW(), "DD/MM/YYYY"), report + +PRINT "Sales automation completed. Hot leads assigned: " + UBOUND(hot_leads) +``` + +--- + ## REST API Endpoints -### GET /api/queue +### Queue Management + +#### GET /api/queue List conversations in queue. -### POST /api/queue/assign +#### POST /api/queue/assign Assign conversation to attendant. ```json @@ -51,7 +342,7 @@ Assign conversation to attendant. } ``` -### POST /api/queue/transfer +#### POST /api/queue/transfer Transfer conversation between attendants. ```json @@ -63,16 +354,95 @@ Transfer conversation between attendants. } ``` -### GET /api/attendants +### Attendant Management + +#### GET /api/attendants List all attendants with stats. +#### PUT /api/attendants/{id}/status +Update attendant status. + +```json +{ + "status": "online" +} +``` + +### CRM Automation + +#### GET /api/automation/status +Check automation job status. + +#### POST /api/automation/trigger/{job_name} +Manually trigger an automation job. + +--- + ## BASIC Keywords +### Transfer to Human + ```basic +' Transfer to any available human +TRANSFER TO HUMAN + +' Transfer to specific department TRANSFER TO HUMAN "sales" + +' Transfer with priority TRANSFER TO HUMAN "support", "high" + +' Transfer with context +TRANSFER TO HUMAN "technical", "normal", "Customer needs help with API integration" ``` +### Create Lead + +```basic +' Create lead from conversation +CREATE LEAD name, email, phone, source + +' Create lead with company info +CREATE LEAD name, email, phone, "website", company, "enterprise" +``` + +### Schedule Appointment + +```basic +' Schedule appointment +BOOK customer_email, service, date, time, staff_id + +' Schedule with duration +BOOK customer_email, "Consultation", "2025-01-20", "14:00", staff_id, 60 +``` + +--- + +## WhatsApp Templates + +Configure these templates in your WhatsApp Business account: + +| Template Name | Purpose | Variables | +|---------------|---------|-----------| +| `follow_up_thanks` | 1-day follow-up | name, interest | +| `follow_up_value` | 3-day value proposition | name, interest | +| `follow_up_offer` | 7-day special offer | name, discount | +| `payment_due_today` | Payment due reminder | name, invoice_id, amount | +| `payment_overdue_3` | 3-day overdue notice | name, invoice_id, amount | +| `payment_overdue_7` | 7-day overdue notice | name, invoice_id, amount | +| `payment_final_notice` | 15-day final notice | name, invoice_id, total | +| `appointment_reminder_24h` | Day-before reminder | name, service, date, time, staff | +| `appointment_reminder_2h` | 2-hour reminder | name, service, time | +| `missed_appointment` | No-show reschedule | name, service | +| `new_hot_lead` | Hot lead alert for sales | rep_name, lead_name, company, score | +| `stale_opportunity` | Stale deal reminder | rep_name, deal_name, amount, days | + +--- + ## See Also -- [Human Approval](../chapter-06-gbdialog/keyword-human-approval.md) \ No newline at end of file +- [Human Approval](../chapter-06-gbdialog/keyword-human-approval.md) +- [SEND TEMPLATE](../chapter-06-gbdialog/keyword-send-template.md) +- [SET SCHEDULE](../chapter-06-gbdialog/keyword-set-schedule.md) +- [CREATE LEAD](../chapter-06-gbdialog/keywords-lead-scoring.md) +- [Sales CRM Template](../chapter-02/template-crm.md) \ No newline at end of file diff --git a/src/appendix-external-services/hosting-dns.md b/src/appendix-external-services/hosting-dns.md new file mode 100644 index 00000000..1b7bf716 --- /dev/null +++ b/src/appendix-external-services/hosting-dns.md @@ -0,0 +1,325 @@ +# Hosting, DNS, and MDA Integration + +General Bots integrates with hosting providers, DNS services, and Mail Delivery Agents (MDA) for complete platform deployment. + +--- + +## Overview + +A complete General Bots deployment typically includes: + +| Component | Purpose | Providers Supported | +|-----------|---------|---------------------| +| **Hosting** | Run BotServer | Any VPS, LXC, bare metal | +| **DNS** | Domain management | Namecheap, Cloudflare, Route53 | +| **MDA** | Email delivery | Stalwart, Postfix, external SMTP | +| **AI/LLM** | Language models | OpenAI, Anthropic, local models | + +--- + +## Namecheap Integration + +General Bots can automatically manage DNS records via the Namecheap API. + +### Configuration + +Add to your bot's `config.csv`: + +```csv +name,value +namecheap-api-user,your-username +namecheap-api-key,stored-in-vault +namecheap-username,your-username +namecheap-client-ip,your-server-ip +``` + +> **Note**: API key is stored in Vault, not in config.csv. Only reference it by name. + +### Automatic DNS Setup + +When deploying a new bot instance, General Bots can: + +1. Create A record pointing to your server +2. Create MX records for email +3. Create TXT records for SPF/DKIM/DMARC +4. Create CNAME for www subdomain + +### BASIC Keywords for DNS + +```basic +' Create DNS record +DNS SET "bot.example.com", "A", server_ip + +' Create MX record for email +DNS SET "example.com", "MX", "mail.example.com", 10 + +' Create SPF record +DNS SET "example.com", "TXT", "v=spf1 mx a ip4:" + server_ip + " -all" + +' List current records +records = DNS LIST "example.com" +``` + +### Supported DNS Providers + +| Provider | API Support | Auto-SSL | +|----------|-------------|----------| +| Namecheap | ✅ Full | ✅ Let's Encrypt | +| Cloudflare | ✅ Full | ✅ Native | +| Route53 | ✅ Full | ✅ ACM | +| DigitalOcean | ✅ Full | ✅ Let's Encrypt | +| Manual | Via config | Manual | + +--- + +## Hosting Options + +### VPS Providers + +General Bots runs on any Linux VPS: + +| Provider | Minimum Spec | Recommended | +|----------|--------------|-------------| +| DigitalOcean | 2GB RAM, 1 vCPU | 4GB RAM, 2 vCPU | +| Linode | 2GB RAM, 1 vCPU | 4GB RAM, 2 vCPU | +| Vultr | 2GB RAM, 1 vCPU | 4GB RAM, 2 vCPU | +| Hetzner | 2GB RAM, 2 vCPU | 4GB RAM, 2 vCPU | +| AWS EC2 | t3.small | t3.medium | +| GCP | e2-small | e2-medium | + +### LXC Container Deployment + +Recommended for production isolation: + +```bash +# Create container +lxc launch ubuntu:22.04 botserver + +# Configure resources +lxc config set botserver limits.memory 4GB +lxc config set botserver limits.cpu 2 + +# Forward ports +lxc config device add botserver http proxy listen=tcp:0.0.0.0:80 connect=tcp:127.0.0.1:8080 +lxc config device add botserver https proxy listen=tcp:0.0.0.0:443 connect=tcp:127.0.0.1:8443 + +# Set environment for Vault +lxc config set botserver environment.VAULT_ADDR="http://vault:8200" + +# Deploy +lxc exec botserver -- ./botserver +``` + +### Docker Deployment + +```yaml +version: '3.8' +services: + botserver: + image: generalbots/botserver:latest + ports: + - "8080:8080" + environment: + - VAULT_ADDR=http://vault:8200 + volumes: + - ./bots:/app/bots + - ./botserver-stack:/app/botserver-stack +``` + +--- + +## MDA (Mail Delivery Agent) Integration + +General Bots includes Stalwart mail server for complete email functionality. + +### Built-in Stalwart + +Stalwart is automatically configured during bootstrap: + +| Feature | Status | +|---------|--------| +| IMAP | ✅ Enabled | +| SMTP | ✅ Enabled | +| JMAP | ✅ Enabled | +| Spam filtering | ✅ SpamAssassin | +| Virus scanning | ✅ ClamAV | +| DKIM signing | ✅ Auto-configured | + +### Email Configuration + +In `config.csv`: + +```csv +name,value +email-domain,example.com +email-dkim-selector,mail +email-spam-threshold,5.0 +email-max-size-mb,25 +``` + +### DNS Records for Email + +Required DNS records (auto-created with Namecheap integration): + +| Record | Type | Value | +|--------|------|-------| +| `mail.example.com` | A | Your server IP | +| `example.com` | MX | `mail.example.com` (priority 10) | +| `example.com` | TXT | `v=spf1 mx a -all` | +| `mail._domainkey.example.com` | TXT | DKIM public key | +| `_dmarc.example.com` | TXT | `v=DMARC1; p=quarantine` | + +### External SMTP + +To use external email providers instead: + +```csv +name,value +smtp-host,smtp.sendgrid.net +smtp-port,587 +smtp-user,apikey +smtp-secure,tls +``` + +Credentials stored in Vault: + +```bash +vault kv put secret/botserver/smtp password="your-api-key" +``` + +--- + +## AI/LLM Integration + +### Supported Providers + +| Provider | Models | Config Key | +|----------|--------|------------| +| OpenAI | GPT-4, GPT-3.5 | `llm-url=https://api.openai.com/v1` | +| Anthropic | Claude 3 | `llm-url=https://api.anthropic.com` | +| Groq | Llama, Mixtral | `llm-url=https://api.groq.com/openai/v1` | +| DeepSeek | DeepSeek-V2 | `llm-url=https://api.deepseek.com` | +| Local | Any GGUF | `llm-url=http://localhost:8081` | + +### Local LLM Setup + +Run local models with BotModels: + +```bash +# Install BotModels +./botserver install llm + +# Download a model +./botserver model download llama-3-8b + +# Configure in config.csv +``` + +```csv +name,value +llm-url,http://localhost:8081 +llm-model,llama-3-8b.gguf +llm-context-size,8192 +llm-gpu-layers,35 +``` + +### AI Features + +| Feature | Description | +|---------|-------------| +| **Conversation** | Natural language chat | +| **RAG** | Knowledge base search | +| **Tool Calling** | Automatic BASIC tool invocation | +| **Embeddings** | Document vectorization | +| **Vision** | Image analysis (multimodal models) | +| **Voice** | Speech-to-text, text-to-speech | + +--- + +## Complete Deployment Example + +### 1. Provision Server + +```bash +# On your VPS +wget https://github.com/GeneralBots/botserver/releases/latest/botserver +chmod +x botserver +``` + +### 2. Configure DNS (Namecheap) + +```basic +' setup-dns.bas +domain = "mybot.example.com" +server_ip = "203.0.113.50" + +DNS SET domain, "A", server_ip +DNS SET "mail." + domain, "A", server_ip +DNS SET domain, "MX", "mail." + domain, 10 +DNS SET domain, "TXT", "v=spf1 mx a ip4:" + server_ip + " -all" + +PRINT "DNS configured for " + domain +``` + +### 3. Start BotServer + +```bash +./botserver +``` + +### 4. Configure SSL + +```bash +# Auto-configured with Let's Encrypt +./botserver ssl enable mybot.example.com +``` + +### 5. Verify Email + +```basic +' test-email.bas +SEND MAIL "test@gmail.com", "Test from General Bots", "Email is working!" +PRINT "Email sent successfully" +``` + +--- + +## Troubleshooting + +### DNS Not Propagating + +1. Check Namecheap API credentials +2. Verify client IP is whitelisted +3. Wait up to 48 hours for propagation +4. Use `dig` or `nslookup` to verify + +### Email Marked as Spam + +1. Verify SPF record is correct +2. Check DKIM signature is valid +3. Ensure DMARC policy is set +4. Check IP reputation at mxtoolbox.com + +### SSL Certificate Errors + +1. Verify DNS A record points to server +2. Check port 80 is accessible for ACME challenge +3. Review Let's Encrypt rate limits +4. Check certificate expiry + +### LLM Connection Failed + +1. Verify `llm-url` in config.csv +2. Check API key in Vault +3. Test endpoint with curl +4. Review BotServer logs + +--- + +## See Also + +- [LLM Providers](./llm-providers.md) — Detailed LLM configuration +- [Storage](./storage.md) — S3-compatible storage setup +- [Directory](./directory.md) — User authentication +- [Channels](./channels.md) — WhatsApp, Telegram, etc. +- [Installation](../chapter-01/installation.md) — Full installation guide \ No newline at end of file diff --git a/src/chapter-01/README.md b/src/chapter-01/README.md index 8067b635..1b2df2ad 100644 --- a/src/chapter-01/README.md +++ b/src/chapter-01/README.md @@ -1,41 +1,130 @@ # Chapter 01: Run and Talk -Get General Bots running in 5 minutes. +> **⚡ In a hurry?** Jump straight to [Quick Start](./quick-start.md) — you'll be chatting with your bot in 5 minutes. -## What You'll Learn +Get General Bots running and have your first conversation. -- How to start General Bots -- Your first conversation -- How sessions work -- Basic bot interaction +--- -## Quick Start +## What You'll Achieve + +By the end of this chapter, you will: + +- ✅ Have General Bots running on your machine +- ✅ Understand what happens during bootstrap +- ✅ Complete your first conversation with a bot +- ✅ Know how sessions and channels work + +--- + +## Choose Your Path + +| If You Want To... | Go To | +|-------------------|-------| +| Get running immediately | [Quick Start](./quick-start.md) | +| Understand the architecture first | [Overview](./overview.md) | +| See all installation options | [Installation](./installation.md) | +| Learn about conversations | [First Conversation](./first-conversation.md) | +| Understand session management | [Sessions and Channels](./sessions.md) | + +--- + +## The 30-Second Version -Download and run: ```bash ./botserver ``` -That's it. Everything installs automatically on first run. +Open `http://localhost:8080`. Start chatting. That's it. -## What Happens +Everything installs automatically on first run—PostgreSQL, storage, cache, and your first bot. -1. **Auto-Bootstrap**: Installs PostgreSQL, cache, storage, and LLM -2. **Load Bots**: Finds `.gbai` folders and loads them -3. **Start Server**: Opens on `http://localhost:8080` -4. **Ready**: Talk to your bot +--- -## First Conversation +## How It Works -Open browser, type a message, get a response. Simple. + -## Topics Covered +--- -- [Overview](./overview.md) - What General Bots does -- [Quick Start](./quick-start.md) - Get running fast -- [Installation](./installation.md) - Detailed setup options -- [First Conversation](./first-conversation.md) - Using your bot -- [Sessions](./sessions.md) - How conversations are managed +## Topics in This Chapter + +### [Overview](./overview.md) +What General Bots does and how it fits together. + +### [Quick Start](./quick-start.md) +The fastest path from zero to running bot. + +### [Installation](./installation.md) +Detailed setup options including LXC containers and production deployment. + +### [First Conversation](./first-conversation.md) +Understanding how the bot responds and learns. + +### [Sessions and Channels](./sessions.md) +How conversations are managed across WhatsApp, Web, Telegram, and more. + +--- + +## Coming From Executive Vision? + +If you just read the [Executive Vision](../executive-vision.md), here's what to know: + +1. **Everything in that feature table?** It's all included in the single `botserver` binary +2. **No configuration needed** — Bootstrap detects your system and sets everything up +3. **Start simple** — Run it, chat with it, then customize + +The philosophy is: **get running first, understand later**. + +--- + +## Prerequisites + +- **Operating System**: Linux, macOS, or Windows (WSL2 recommended) +- **Disk Space**: ~2GB for botserver-stack +- **RAM**: 4GB minimum, 8GB recommended +- **Ports**: 8080 (web), 5432 (database), 9000 (storage) + +No Docker required. No cloud accounts. No API keys to start. + +--- + +## Next Step + +**[Quick Start →](./quick-start.md)** --- diff --git a/src/chapter-04-gbui/apps/chat.md b/src/chapter-04-gbui/apps/chat.md index a0a88e32..e85c5c56 100644 --- a/src/chapter-04-gbui/apps/chat.md +++ b/src/chapter-04-gbui/apps/chat.md @@ -77,6 +77,8 @@ Bot responses support full Markdown rendering: - Links and images - Tables +--- + ## Keyboard Shortcuts | Shortcut | Action | @@ -87,6 +89,8 @@ Bot responses support full Markdown rendering: | `/` | Open command menu | | `Escape` | Cancel current action | +--- + ## API Endpoints ### WebSocket Connection @@ -112,7 +116,7 @@ ws://your-server:8080/ws | `/api/voice/stop` | POST | Stop voice recording | | `/api/suggestions` | GET | Get suggestion chips | - +--- ## Example Conversations @@ -179,7 +183,7 @@ ws://your-server:8080/ws - +--- ## Accessibility @@ -189,19 +193,7 @@ ws://your-server:8080/ws - Adjustable font sizes - ARIA labels on all interactive elements -```html -
-
- - -``` +--- ## Troubleshooting @@ -226,9 +218,11 @@ ws://your-server:8080/ws 3. Clear browser cache 4. Check for JavaScript errors +--- + ## See Also -- [HTMX Architecture](../htmx-architecture.md) - How Chat uses HTMX -- [Suite Manual](../suite-manual.md) - Complete user guide -- [Tasks App](./tasks.md) - Create tasks from chat -- [Mail App](./mail.md) - Email integration \ No newline at end of file +- [HTMX Architecture](../htmx-architecture.md) — How Chat uses HTMX +- [Suite Manual](../suite-manual.md) — Complete user guide +- [Tasks App](./tasks.md) — Create tasks from chat +- [Mail App](./mail.md) — Email integration \ No newline at end of file diff --git a/src/chapter-04-gbui/monitoring.md b/src/chapter-04-gbui/monitoring.md index 8d39c0ba..ab0ed5b5 100644 --- a/src/chapter-04-gbui/monitoring.md +++ b/src/chapter-04-gbui/monitoring.md @@ -1,8 +1,8 @@ # Monitoring Dashboard -The Monitoring Dashboard provides real-time visibility into your General Bots deployment through an animated, interactive SVG visualization showing system health, active sessions, and resource utilization. +The Monitoring Dashboard is the **live operations homepage** for your General Bots deployment. It provides real-time visibility into system health, active sessions, and resource utilization through an animated, interactive SVG visualization. -## Live System Visualization +## Live System Architecture Live Monitoring Dashboard @@ -14,113 +14,109 @@ The dashboard displays BotServer at the center orchestrating all interactions, w - **Top**: Real-time metrics panels for sessions, messages, and response time - **Bottom**: Resource utilization bars and activity ticker +--- + ## Accessing the Dashboard -Access monitoring from the Suite interface: +The monitoring dashboard is the **default homepage** when accessing Suite: + +```/dev/null/monitoring-url.txt#L1 +http://localhost:8080/monitoring +``` + +Or from within Suite: 1. Click the apps menu (⋮⋮⋮) 2. Select **Monitoring** -3. Or navigate directly to `/monitoring` -## Dashboard Features +--- -### Animated System Architecture +## Real-Time Metrics -The SVG visualization shows real-time data flow: +### Active Sessions Panel -| Component | Color | Description | -|-----------|-------|-------------| -| **BotServer** | Blue/Purple | Central orchestrator with rotating ring | -| **PostgreSQL** | Blue | Primary database with cylinder icon | -| **Qdrant** | Purple | Vector database with triangle nodes | -| **MinIO** | Amber | Object storage with disk icon | -| **BotModels** | Pink | AI/ML service with neural network icon | -| **Cache** | Cyan | In-memory cache with lightning icon | -| **Vault** | Green | Secrets management with lock icon | +Displays current conversation sessions: + +```/dev/null/sessions-example.txt#L1-4 +Active Sessions: 12 +Peak Today: 47 +Avg Duration: 8m 32s +Trend: ↑ +3 in last hour +``` + +### Messages Panel + +Shows message throughput: + +```/dev/null/messages-example.txt#L1-4 +Today: 1,234 messages +This Hour: 89 +Avg Response: 1.2s +Rate: 14.8 msg/min +``` + +### Resource Utilization + +Real-time system resources: + +| Resource | Current | Threshold | +|----------|---------|-----------| +| **CPU** | 65% | Warning > 80% | +| **Memory** | 72% | Warning > 85% | +| **GPU** | 45% | Warning > 90% | +| **Disk** | 28% | Warning > 90% | + +--- + +## Service Health Status + +Each service has a status indicator: + +| Service | Status | Health Check | +|---------|--------|--------------| +| **PostgreSQL** | 🟢 Running | Connection pool, query latency | +| **Qdrant** | 🟢 Running | Vector count, search time | +| **MinIO** | 🟢 Running | Storage usage, object count | +| **BotModels** | 🟢 Running | Token usage, response time | +| **Cache** | 🟢 Running | Hit rate, memory usage | +| **Vault** | 🟢 Running | Seal status, policy count | ### Status Indicators -Each service has a status dot: - | Status | Color | Animation | |--------|-------|-----------| | **Running** | 🟢 Green | Gentle pulse | | **Warning** | 🟡 Amber | Fast pulse | | **Stopped** | 🔴 Red | No animation | -### Real-Time Metrics +--- -Three metric panels at the top update automatically: +## Live Data Endpoints -| Panel | Update Interval | Description | -|-------|-----------------|-------------| -| **Active Sessions** | 5 seconds | Current open conversations with trend | -| **Messages Today** | 10 seconds | Total messages with hourly rate | -| **Avg Response** | 10 seconds | Average response time in milliseconds | - -### Resource Utilization - -Resource bars show system health: - -| Resource | Gradient | Warning Threshold | -|----------|----------|-------------------| -| **CPU** | Blue/Purple | > 80% | -| **Memory** | Green | > 85% | -| **GPU** | Purple | > 90% | -| **Disk** | Amber | > 90% | - -### Activity Ticker - -A live ticker at the bottom shows the latest system events with a pulsing green indicator. - -## View Modes - -Toggle between two views using the grid button or press `V`: - -### Live View (Default) -The animated SVG visualization showing the complete system topology with flowing data packets. - -### Grid View -Traditional panel-based layout with detailed tree views for each metric category: -- Sessions panel with active, peak, and duration -- Messages panel with counts and rates -- Resources panel with progress bars -- Services panel with health status -- Bots panel with active bot list - -## Keyboard Shortcuts - -| Shortcut | Action | -|----------|--------| -| `V` | Toggle between Live and Grid view | -| `R` | Refresh all metrics | - -## HTMX Integration - -The dashboard uses HTMX for real-time updates without full page reloads: +The dashboard pulls real data from these HTMX endpoints: | Endpoint | Interval | Data | |----------|----------|------| -| `/api/monitoring/metric/sessions` | 5s | Session count | -| `/api/monitoring/metric/messages` | 10s | Message count | -| `/api/monitoring/metric/response_time` | 10s | Avg response | -| `/api/monitoring/resources/bars` | 15s | Resource SVG bars | +| `/api/monitoring/metric/sessions` | 5s | Session count, trend | +| `/api/monitoring/metric/messages` | 10s | Message count, rate | +| `/api/monitoring/metric/response_time` | 10s | Avg response time | +| `/api/monitoring/resources/bars` | 15s | CPU, memory, GPU, disk | | `/api/monitoring/services/status` | 30s | Service health JSON | -| `/api/monitoring/activity/latest` | 5s | Activity text | -| `/api/monitoring/timestamp` | 5s | Last updated time | +| `/api/monitoring/activity/latest` | 5s | Activity ticker text | +| `/api/monitoring/bots/active` | 30s | Active bot list | + +--- ## API Access -Access monitoring data programmatically: +### Full Status Endpoint -### Get Full Status - -```/dev/null/monitoring-api.txt +```/dev/null/api-call.txt#L1 GET /api/monitoring/status ``` -**Response:** +Returns complete system status: -```/dev/null/monitoring-response.json +```/dev/null/monitoring-response.json#L1-25 { "sessions": { "active": 12, @@ -149,31 +145,89 @@ GET /api/monitoring/status } ``` -### Service-Specific Endpoints +### Active Bots Endpoint -| Endpoint | Returns | -|----------|---------| -| `/api/monitoring/services` | All service details | -| `/api/monitoring/bots` | Active bot list | -| `/api/monitoring/history?period=24h` | Historical metrics | -| `/api/monitoring/prometheus` | Prometheus format export | +```/dev/null/bots-api.txt#L1 +GET /api/monitoring/bots +``` -## Component Health Details +Returns list of deployed bots with metrics: -| Component | Health Check | Warning Signs | -|-----------|--------------|---------------| -| **PostgreSQL** | Connection count, query rate | > 80 connections, slow queries | -| **Qdrant** | Vector count, search latency | > 50ms search time | -| **MinIO** | Storage usage, object count | > 80% storage used | -| **BotModels** | Token usage, response latency | > 2s response time | -| **Vault** | Seal status, policy count | Unsealed without auth | -| **Cache** | Hit rate, memory usage | < 80% hit rate | +```/dev/null/bots-response.json#L1-18 +{ + "bots": [ + { + "name": "default", + "status": "active", + "sessions_today": 34, + "messages_today": 567, + "avg_response_ms": 980 + }, + { + "name": "support", + "status": "active", + "sessions_today": 12, + "messages_today": 234, + "avg_response_ms": 1100 + } + ] +} +``` -## Alerts Configuration +### Historical Data + +```/dev/null/history-api.txt#L1 +GET /api/monitoring/history?period=24h +``` + +Returns time-series data for charting. + +### Prometheus Export + +```/dev/null/prometheus-api.txt#L1 +GET /api/monitoring/prometheus +``` + +Returns metrics in Prometheus format for external monitoring systems. + +--- + +## View Modes + +Toggle between two views using the grid button or press `V`: + +### Live View (Default) + +The animated SVG visualization showing the complete system topology with flowing data packets. This is the recommended view for operations dashboards. + +### Grid View + +Traditional panel-based layout with detailed metrics: + +- **Sessions Panel**: Active, peak, average duration +- **Messages Panel**: Counts, rates, response times +- **Resources Panel**: Progress bars with thresholds +- **Services Panel**: Health status for each component +- **Bots Panel**: List of active bots with metrics + +--- + +## Keyboard Shortcuts + +| Shortcut | Action | +|----------|--------| +| `V` | Toggle between Live and Grid view | +| `R` | Refresh all metrics immediately | +| `F` | Toggle fullscreen mode | +| `?` | Show keyboard shortcuts | + +--- + +## Alert Configuration Configure alert thresholds in `config.csv`: -```/dev/null/config-alerts.csv +```/dev/null/config-alerts.csv#L1-6 name,value alert-cpu-threshold,80 alert-memory-threshold,85 @@ -182,78 +236,93 @@ alert-response-time-ms,5000 alert-email,admin@example.com ``` -## Console Mode +When thresholds are exceeded: +1. Service status turns amber/red +2. Alert notification sent to configured email +3. Activity ticker shows alert message -For terminal-based monitoring: +--- -```/dev/null/console-command.bash +## Console Mode Monitoring + +For terminal-based monitoring or headless servers: + +```/dev/null/console-command.sh#L1 ./botserver --console --monitor ``` Output: -```/dev/null/console-output.txt + +```/dev/null/console-output.txt#L1-6 [MONITOR] 2025-01-15 14:32:00 Sessions: 12 active (peak: 47) Messages: 1,234 today (89/hour) CPU: 65% | MEM: 72% | GPU: 45% Services: 6/6 running +Latest: User enrolled in Computer Science course ``` -## Tips & Best Practices +--- -💡 **Watch the data packets** - Flowing animations indicate active communication between components +## Component Health Details -💡 **Monitor trends** - The session trend indicator (↑/↓) shows direction of change +| Component | Metrics Monitored | Warning Signs | +|-----------|-------------------|---------------| +| **PostgreSQL** | Connection count, query rate, replication lag | > 80 connections, queries > 100ms | +| **Qdrant** | Vector count, search latency, memory | > 50ms search, > 80% memory | +| **MinIO** | Storage usage, object count, bandwidth | > 80% storage, high error rate | +| **BotModels** | Token usage, response latency, queue depth | > 2s response, queue > 10 | +| **Vault** | Seal status, policy count, auth failures | Sealed, repeated auth failures | +| **Cache** | Hit rate, memory usage, evictions | < 80% hit rate, frequent evictions | -💡 **Click services** - Click any service node in Live view to see detailed status +--- -💡 **Set up alerts** - Configure thresholds before issues become critical +## Best Practices -💡 **Use keyboard shortcuts** - Press `R` for quick refresh, `V` to toggle views +1. **Keep monitoring visible** — Use a dedicated screen or dashboard monitor for operations +2. **Set appropriate thresholds** — Configure alerts before issues become critical +3. **Watch data flow** — Animated packets indicate active communication between components +4. **Monitor trends** — The session trend indicator (↑/↓) shows direction of change +5. **Use historical data** — Query `/api/monitoring/history` for trend analysis +6. **Enable Prometheus export** — Integrate with existing monitoring infrastructure -💡 **Check historical data** - Query `/api/monitoring/history` for trend analysis +--- ## Troubleshooting -### Dashboard not loading +### Dashboard Not Loading -**Possible causes:** -1. WebSocket connection failed -2. API endpoint unreachable -3. Browser blocking HTMX - -**Solution:** 1. Check browser console for errors 2. Verify `/api/monitoring/status` returns data -3. Refresh the page +3. Ensure WebSocket connection is established +4. Refresh the page -### Metrics showing "--" +### Metrics Showing "--" -**Possible causes:** -1. Initial load in progress -2. API timeout -3. Service unavailable +1. Wait 5-10 seconds for initial data load +2. Check network tab for failed API requests +3. Verify all services are running +4. Check BotServer logs for errors -**Solution:** -1. Wait 5-10 seconds for first update -2. Check network tab for failed requests -3. Verify services are running +### Animations Stuttering -### Animations stuttering - -**Possible causes:** -1. High CPU usage -2. Many browser tabs open -3. Hardware acceleration disabled - -**Solution:** -1. Close unused tabs -2. Enable hardware acceleration in browser +1. Close unused browser tabs +2. Enable hardware acceleration in browser settings 3. Use Grid view for lower resource usage +4. Check if system CPU is overloaded + +### Service Showing Red + +1. Check service-specific logs in `botserver-stack/logs/` +2. Verify Vault is unsealed +3. Check database connection limits +4. Restart the affected service + +--- ## See Also -- [Monitoring API Reference](../chapter-10-api/monitoring-api.md) -- [Console Mode](./console-mode.md) -- [Configuration Options](../chapter-08-config/README.md) -- [Analytics App](./apps/analytics.md) \ No newline at end of file +- [Console Mode](./console-mode.md) — Terminal-based interface +- [HTMX Architecture](./htmx-architecture.md) — How real-time updates work +- [Suite Manual](./suite-manual.md) — Complete user guide +- [Analytics App](./apps/analytics.md) — Business metrics and reporting \ No newline at end of file diff --git a/src/chapter-06-gbdialog/examples-consolidated.md b/src/chapter-06-gbdialog/examples-consolidated.md index 1d52f6e2..58976103 100644 --- a/src/chapter-06-gbdialog/examples-consolidated.md +++ b/src/chapter-06-gbdialog/examples-consolidated.md @@ -1,97 +1,16 @@ -# Consolidated Examples: Complete Tools & Workflows +# Webhook Integrations and Jobs Examples -This document provides complete, production-ready examples that demonstrate how multiple keywords work together to build real-world tools and automation workflows. +This document provides complete, production-ready examples demonstrating webhook endpoints and scheduled jobs. All examples use event-driven patterns—no conversation loops. -## 1. Customer Support Bot with AI +--- -A complete customer support solution with knowledge base, ticket creation, and escalation. +## 1. E-Commerce Order Management System -```basic -' customer-support.bas -' Complete customer support tool with AI-powered responses +Complete order processing with inventory, payments, and notifications via webhook. -' Initialize knowledge bases -USE KB "product-docs" -USE KB "faq" -USE KB "policies" - -' Set AI personality -SET CONTEXT "You are a helpful customer support agent for TechCorp. Be friendly, professional, and concise. If you cannot answer a question, offer to create a support ticket." - -' Main conversation loop -TALK "Hello! I'm your TechCorp support assistant. How can I help you today?" - -conversation_active = TRUE - -WHILE conversation_active - HEAR user_message - - ' Check for exit commands - IF INSTR(LCASE(user_message), "bye") > 0 OR INSTR(LCASE(user_message), "exit") > 0 THEN - TALK "Thank you for contacting TechCorp support. Have a great day!" - conversation_active = FALSE - ELSE IF INSTR(LCASE(user_message), "ticket") > 0 OR INSTR(LCASE(user_message), "human") > 0 THEN - ' User wants to create a ticket or talk to human - TALK "I'll create a support ticket for you. Please describe your issue in detail." - HEAR issue_description - - TALK "What's your email address?" - HEAR customer_email - - ' Create ticket in database - ticket_id = "TKT-" + FORMAT(NOW(), "YYYYMMDDHHmmss") - description = issue_description - ticket_status = "open" - priority = "normal" - created_at = NOW() - conversation_history = user_message - - SAVE "support_tickets", ticket_id, customer_email, description, ticket_status, priority, created_at, conversation_history - - ticket_result = ticket_id - ticket_id = ticket_result.id - - ' Send confirmation email - email_body = "Your support ticket #" + ticket_id + " has been created. Our team will respond within 24 hours." - SEND MAIL customer_email, "Support Ticket Created - #" + ticket_id, email_body - - ' Notify support team - SEND MAIL "support@techcorp.com", "New Ticket #" + ticket_id, "Customer: " + customer_email + "\n\nIssue: " + issue_description - - TALK "I've created ticket #" + ticket_id + ". You'll receive a confirmation email shortly. Is there anything else I can help with?" - ELSE - ' Use AI to answer the question - response = LLM user_message - TALK response - - ' Log the conversation - question = user_message - answer = response - log_timestamp = NOW() - INSERT "conversation_logs", question, answer, log_timestamp - - TALK "Did that answer your question? (yes/no/create ticket)" - HEAR feedback - - IF INSTR(LCASE(feedback), "no") > 0 THEN - TALK "I'm sorry I couldn't help. Would you like me to create a support ticket? (yes/no)" - HEAR create_ticket - IF INSTR(LCASE(create_ticket), "yes") > 0 THEN - ' Trigger ticket creation on next loop - user_message = "create ticket" - END IF - END IF - END IF -WEND -``` - -## 2. E-Commerce Order Management System - -Complete order processing with inventory, payments, and notifications. - -```basic +```botbook/src/chapter-06-gbdialog/examples-consolidated.bas#L1-80 ' order-system.bas -' E-commerce order management tool +' E-commerce order management webhook WEBHOOK "new-order" @@ -106,10 +25,8 @@ payment_token = body.payment.token ' Validate order IF order_id = "" OR customer_email = "" THEN - WITH result = NEW OBJECT - .status = 400 - .error = "Missing required fields" - END WITH + result_status = 400 + result_error = "Missing required fields" EXIT END IF @@ -126,35 +43,20 @@ FOR EACH item IN items NEXT item IF NOT inventory_ok THEN - ' Notify customer of stock issue SEND MAIL customer_email, "Order Issue - Items Out of Stock", "Unfortunately, the following items are out of stock: " + out_of_stock_items - - WITH result = NEW OBJECT - .status = 400 - .error = "Items out of stock" - .items = out_of_stock_items - END WITH + result_status = 400 + result_error = "Items out of stock" EXIT END IF ' Process payment -WITH payment_request = NEW OBJECT - .amount = body.total - .currency = "USD" - .token = payment_token - .description = "Order " + order_id -END WITH - SET HEADER "Authorization", "Bearer " + GET BOT MEMORY "stripe_key" -payment_result = POST "https://api.stripe.com/v1/charges", payment_request +payment_result = POST "https://api.stripe.com/v1/charges", body.total, "USD", payment_token, "Order " + order_id IF payment_result.status <> "succeeded" THEN SEND MAIL customer_email, "Payment Failed", "Your payment could not be processed. Please try again." - - WITH result = NEW OBJECT - .status = 402 - .error = "Payment failed" - END WITH + result_status = 402 + result_error = "Payment failed" EXIT END IF @@ -162,74 +64,40 @@ END IF FOR EACH item IN items current_stock = FIND "products", "sku=" + item.sku new_stock = current_stock.stock - item.quantity + UPDATE "products", "sku=" + item.sku, new_stock, NOW() - WITH stock_update = NEW OBJECT - .stock = new_stock - .updated_at = NOW() - END WITH - UPDATE "products", "sku=" + item.sku, stock_update - - ' Alert if low stock IF new_stock < 10 THEN SEND MAIL "inventory@company.com", "Low Stock Alert: " + item.sku, "Stock level: " + new_stock END IF NEXT item -' Create order record -WITH order_record = NEW OBJECT - .order_id = order_id - .customer_email = customer_email - .customer_name = customer_name - .items = items - .total = body.total - .shipping_address = shipping_address - .payment_id = payment_result.id - .status = "confirmed" - .created_at = NOW() -END WITH +' Save order record +SAVE "orders", order_id, customer_email, customer_name, items, body.total, shipping_address, payment_result.id, "confirmed", NOW() -SAVE "orders", order_id, order_record - -' Generate invoice PDF - pass variables directly -invoice_customer = customer_name -invoice_email = customer_email -invoice_items = order_items -subtotal = body.subtotal -tax = body.tax -shipping_cost = body.shipping_cost -invoice_date = FORMAT(NOW(), "MMMM DD, YYYY") - -invoice_pdf = GENERATE PDF "templates/invoice.html", order_id, invoice_customer, invoice_email, invoice_items, subtotal, tax, shipping_cost, total, invoice_date, "invoices/" + order_id + ".pdf" - -' Send confirmation email with invoice -email_body = "Thank you for your order, " + customer_name + "!\n\n" -email_body = email_body + "Order #: " + order_id + "\n" -email_body = email_body + "Total: $" + body.total + "\n\n" -email_body = email_body + "Your invoice is attached. You'll receive shipping updates soon." +' Generate invoice PDF +invoice_pdf = GENERATE PDF "templates/invoice.html", order_id, customer_name, customer_email, items, body.subtotal, body.tax, body.shipping_cost, body.total, FORMAT(NOW(), "MMMM DD, YYYY"), "invoices/" + order_id + ".pdf" +' Send confirmation email +email_body = "Thank you for your order, " + customer_name + "!\n\nOrder #: " + order_id + "\nTotal: $" + body.total + "\n\nYour invoice is attached." SEND MAIL customer_email, "Order Confirmed - #" + order_id, email_body, invoice_pdf.url -' Notify warehouse - build simple notification -warehouse_order_id = order_id -warehouse_items = items -warehouse_address = shipping_address -warehouse_priority = "normal" -POST "https://warehouse.internal/api/orders", warehouse_order_id, warehouse_items, warehouse_address, warehouse_priority +' Notify warehouse +POST "https://warehouse.internal/api/orders", order_id, items, shipping_address, "normal" -' Return success result_status = "confirmed" result_order_id = order_id result_payment_id = payment_result.id -result_invoice_url = invoice_pdf.url ``` -## 3. HR Onboarding Automation +--- -Complete employee onboarding workflow. +## 2. HR Onboarding Automation -```basic +Complete employee onboarding workflow triggered by webhook. + +```botbook/src/chapter-06-gbdialog/examples-consolidated.bas#L82-150 ' onboarding.bas -' HR onboarding automation tool +' HR onboarding automation webhook WEBHOOK "new-employee" @@ -242,25 +110,14 @@ role = body.role ' Validate input IF employee_email = "" OR employee_name = "" THEN - WITH result = NEW OBJECT - .status = 400 - .error = "Missing employee name or email" - END WITH + result_status = 400 + result_error = "Missing employee name or email" EXIT END IF ' Create employee record employee_id = "EMP-" + FORMAT(NOW(), "YYYYMMDD") + "-" + LEFT(GUID(), 4) -emp_name = employee_name -emp_email = employee_email -emp_department = department -emp_role = role -emp_manager = manager_email -emp_start_date = start_date -emp_status = "onboarding" -created_at = NOW() - -SAVE "employees", employee_id, emp_name, emp_email, emp_department, emp_role, emp_manager, emp_start_date, emp_status, created_at +SAVE "employees", employee_id, employee_name, employee_email, department, role, manager_email, start_date, "onboarding", NOW() ' Create tasks for IT setup CREATE TASK "Create email account for " + employee_name, "it@company.com", start_date @@ -275,25 +132,16 @@ CREATE TASK "Add " + employee_name + " to benefits enrollment", "hr@company.com" ' Send welcome email to new employee USE KB "employee-handbook" SET CONTEXT "You are a friendly HR assistant. Create a warm, professional welcome message." - welcome_content = LLM "Write a welcome email for " + employee_name + " joining as " + role + " in " + department + " department, starting on " + start_date - SEND MAIL employee_email, "Welcome to the Team, " + employee_name + "!", welcome_content ' Notify manager -manager_message = "New team member alert!\n\n" -manager_message = manager_message + employee_name + " will be joining your team as " + role + " on " + start_date + ".\n\n" -manager_message = manager_message + "Please prepare:\n" -manager_message = manager_message + "- First week schedule\n" -manager_message = manager_message + "- Team introduction meeting\n" -manager_message = manager_message + "- Project assignments\n" - +manager_message = "New team member alert!\n\n" + employee_name + " will be joining your team as " + role + " on " + start_date + ".\n\nPlease prepare:\n- First week schedule\n- Team introduction meeting\n- Project assignments" SEND MAIL manager_email, "New Team Member: " + employee_name, manager_message -' Add to department Slack channel +' Post to Slack slack_channel = "#" + LCASE(department) -slack_text = "🎉 Please welcome " + employee_name + " who will be joining us as " + role + " on " + start_date + "!" -POST "https://hooks.slack.com/services/xxx", slack_channel, slack_text +POST "https://hooks.slack.com/services/xxx", slack_channel, "🎉 Please welcome " + employee_name + " who will be joining us as " + role + " on " + start_date + "!" ' Schedule 30-60-90 day check-ins check_in_dates = [30, 60, 90] @@ -302,18 +150,18 @@ FOR EACH days IN check_in_dates CREATE TASK days + "-day check-in with " + employee_name, manager_email, check_in_date NEXT days -' Return success result_status = "success" result_employee_id = employee_id result_tasks_created = 9 -result_message = "Onboarding initiated for " + employee_name ``` -## 4. Daily Business Intelligence Report +--- -Automated daily report with AI-generated insights. +## 3. Daily Business Intelligence Report -```basic +Automated daily report job with AI-generated insights. + +```botbook/src/chapter-06-gbdialog/examples-consolidated.bas#L152-230 ' daily-report.bas ' Automated daily business intelligence report @@ -341,198 +189,51 @@ avg_resolution_time = AGGREGATE "AVG", tickets_resolved, "resolution_time_hours" low_stock = FIND "products", "stock < 10" out_of_stock = FIND "products", "stock = 0" -' Gather website analytics -SET HEADER "Authorization", "Bearer " + GET BOT MEMORY "analytics_api_key" -analytics = GET "https://api.analytics.com/v1/summary?date=" + today - ' Compile data for AI analysis -report_date = today -sales_revenue = total_revenue_today -sales_orders = order_count_today -sales_change = revenue_change -tickets_opened = UBOUND(tickets_today) -tickets_resolved_count = UBOUND(tickets_resolved) -avg_resolution = avg_resolution_time -low_stock_count = UBOUND(low_stock) -out_of_stock_count = UBOUND(out_of_stock) -visitors = analytics.visitors -page_views = analytics.page_views -bounce_rate = analytics.bounce_rate - -report_data = "Date: " + report_date + ", Revenue: $" + sales_revenue + ", Orders: " + sales_orders + ", Change: " + sales_change + "%, Tickets: " + tickets_opened + " opened, " + tickets_resolved_count + " resolved, Low stock: " + low_stock_count +report_data = "Date: " + today + ", Revenue: $" + total_revenue_today + ", Orders: " + order_count_today + ", Change: " + revenue_change + "%, Tickets: " + UBOUND(tickets_today) + " opened, " + UBOUND(tickets_resolved) + " resolved, Low stock: " + UBOUND(low_stock) ' Generate AI insights SET CONTEXT "You are a business analyst. Analyze this data and provide actionable insights. Be concise and focus on key trends and recommendations." +ai_insights = LLM "Analyze this business data and provide 3-5 key insights:\n\n" + report_data -analysis_prompt = "Analyze this business data and provide 3-5 key insights:\n\n" + report_data -ai_insights = LLM analysis_prompt - -' Build HTML report -report_title = "Daily Business Report - " + today -generated_at = NOW() - -report_pdf = GENERATE PDF "templates/daily-report.html", report_title, report_data, ai_insights, generated_at, "reports/daily-" + today + ".pdf" +' Build report PDF +report_pdf = GENERATE PDF "templates/daily-report.html", "Daily Business Report - " + today, report_data, ai_insights, NOW(), "reports/daily-" + today + ".pdf" ' Send to executives executives = ["ceo@company.com", "cfo@company.com", "coo@company.com"] - FOR EACH exec IN executives SEND MAIL exec, "Daily Business Report - " + today, "Please find attached today's business intelligence report.\n\n" + ai_insights, report_pdf.url NEXT exec ' Post summary to Slack -slack_channel = "#executive-updates" -slack_text = "📊 *Daily Report - " + today + "*\n\n" -slack_text = slack_text + "💰 Revenue: $" + FORMAT(total_revenue_today, "#,##0.00") + " (" + FORMAT(revenue_change, "+0.0") + "%)\n" -slack_text = slack_text + "📦 Orders: " + order_count_today + "\n" -slack_text = slack_text + "🎫 Support Tickets: " + UBOUND(tickets_today) + " opened, " + UBOUND(tickets_resolved) + " resolved\n" -slack_text = slack_text + "⚠️ Low Stock Items: " + UBOUND(low_stock) + "\n\n" -slack_text = slack_text + "*AI Insights:*\n" + ai_insights -POST "https://hooks.slack.com/services/xxx", slack_channel, slack_text +slack_summary = "📊 *Daily Report - " + today + "*\n\n💰 Revenue: $" + FORMAT(total_revenue_today, "#,##0.00") + " (" + FORMAT(revenue_change, "+0.0") + "%)\n📦 Orders: " + order_count_today + "\n🎫 Support Tickets: " + UBOUND(tickets_today) + " opened, " + UBOUND(tickets_resolved) + " resolved\n⚠️ Low Stock Items: " + UBOUND(low_stock) +POST "https://hooks.slack.com/services/xxx", "#executive-updates", slack_summary ' Store report in database -report_date = today -pdf_url = report_pdf.url -SAVE "daily_reports", report_date, report_data, ai_insights, pdf_url +SAVE "daily_reports", today, report_data, ai_insights, report_pdf.url PRINT "Daily report generated and distributed for " + today ``` -## 5. Multi-Language Customer Survey Tool +--- -Interactive survey with real-time translation and sentiment analysis. +## 4. Document Processing Pipeline -```basic -' survey-tool.bas -' Multi-language customer survey with AI analysis +Automated document intake, processing, and classification via webhook. -TALK "Welcome! What language would you prefer? / ¡Bienvenido! ¿Qué idioma prefiere? / Bienvenue! Quelle langue préférez-vous?" - -HEAR language_choice - -' Detect language -SET CONTEXT "Identify the language of this text. Respond with only the language code: en, es, fr, de, pt, or other." -detected_lang = LLM language_choice -detected_lang = TRIM(LCASE(detected_lang)) - -' Set translations -IF detected_lang = "es" THEN - q1 = "¿Cómo calificaría su experiencia general? (1-10)" - q2 = "¿Qué es lo que más le gustó de nuestro servicio?" - q3 = "¿Qué podríamos mejorar?" - q4 = "¿Nos recomendaría a un amigo? (sí/no)" - thank_you = "¡Gracias por sus comentarios!" -ELSE IF detected_lang = "fr" THEN - q1 = "Comment évalueriez-vous votre expérience globale ? (1-10)" - q2 = "Qu'avez-vous le plus apprécié dans notre service ?" - q3 = "Que pourrions-nous améliorer ?" - q4 = "Nous recommanderiez-vous à un ami ? (oui/non)" - thank_you = "Merci pour vos commentaires !" -ELSE - q1 = "How would you rate your overall experience? (1-10)" - q2 = "What did you like most about our service?" - q3 = "What could we improve?" - q4 = "Would you recommend us to a friend? (yes/no)" - thank_you = "Thank you for your feedback!" - detected_lang = "en" -END IF - -' Collect responses -TALK q1 -HEAR rating -IF NOT IS NUMERIC(rating) THEN - rating = 5 -END IF - -TALK q2 -HEAR liked_most - -TALK q3 -HEAR improvements - -TALK q4 -HEAR recommend - -' Translate responses to English for analysis if needed -IF detected_lang <> "en" THEN - SET CONTEXT "Translate the following text to English. Only provide the translation, nothing else." - liked_most_en = LLM liked_most - improvements_en = LLM improvements -ELSE - liked_most_en = liked_most - improvements_en = improvements -END IF - -' Sentiment analysis -SET CONTEXT "Analyze the sentiment of this feedback. Respond with: positive, neutral, or negative." -sentiment = LLM "Liked: " + liked_most_en + ". Improvements: " + improvements_en -sentiment = TRIM(LCASE(sentiment)) - -' NPS calculation -IF INSTR(LCASE(recommend), "yes") > 0 OR INSTR(LCASE(recommend), "sí") > 0 OR INSTR(LCASE(recommend), "oui") > 0 THEN - would_recommend = TRUE - nps_category = "promoter" -ELSE - would_recommend = FALSE - nps_category = "detractor" -END IF - -IF rating >= 9 THEN - nps_category = "promoter" -ELSE IF rating >= 7 THEN - nps_category = "passive" -ELSE - nps_category = "detractor" -END IF - -' Save survey response -survey_language = detected_lang -survey_rating = rating -submitted_at = NOW() - -SAVE "survey_responses", survey_language, survey_rating, liked_most, liked_most_en, improvements, improvements_en, would_recommend, sentiment, nps_category, submitted_at - -' Generate AI summary for low scores -IF rating < 6 THEN - SET CONTEXT "You are a customer experience manager. Summarize this negative feedback and suggest immediate actions." - - alert_summary = LLM "Customer rated us " + rating + "/10. They liked: " + liked_most_en + ". They want us to improve: " + improvements_en - - SEND MAIL "cx-team@company.com", "⚠️ Low Survey Score Alert", "Rating: " + rating + "/10\n\nSummary: " + alert_summary + "\n\nOriginal feedback:\n- Liked: " + liked_most + "\n- Improve: " + improvements -END IF - -TALK thank_you - -' Show aggregated stats -total_responses = AGGREGATE "COUNT", "survey_responses", "id" -avg_rating = AGGREGATE "AVG", "survey_responses", "rating" -promoters = FILTER "survey_responses", "nps_category=promoter" -detractors = FILTER "survey_responses", "nps_category=detractor" -nps_score = ((UBOUND(promoters) - UBOUND(detractors)) / total_responses) * 100 - -PRINT "Survey completed. Total responses: " + total_responses + ", Avg rating: " + FORMAT(avg_rating, "0.0") + ", NPS: " + FORMAT(nps_score, "0") -``` - -## 6. Document Processing Pipeline - -Automated document intake, processing, and classification. - -```basic +```botbook/src/chapter-06-gbdialog/examples-consolidated.bas#L232-330 ' document-pipeline.bas ' Automated document processing and classification WEBHOOK "document-upload" -' Get uploaded document document_url = body.document_url document_name = body.filename uploader_email = body.uploader_email IF document_url = "" THEN - WITH result = NEW OBJECT - .status = 400 - .error = "No document URL provided" - END WITH + result_status = 400 + result_error = "No document URL provided" EXIT END IF @@ -541,111 +242,62 @@ local_path = DOWNLOAD document_url, "incoming/" + document_name ' Extract text based on file type file_extension = LCASE(RIGHT(document_name, 4)) - -IF file_extension = ".pdf" THEN - content = GET local_path -ELSE IF file_extension = "docx" OR file_extension = ".doc" THEN - content = GET local_path -ELSE IF file_extension = ".txt" THEN - content = READ local_path -ELSE - ' Try OCR for images - content = GET local_path -END IF +content = GET local_path ' Classify document using AI -SET CONTEXT "You are a document classifier. Classify this document into one of these categories: invoice, contract, report, correspondence, legal, hr, other. Also extract key metadata. Respond in JSON format with fields: category, confidence, key_dates, key_parties, summary." - +SET CONTEXT "You are a document classifier. Classify this document into one of these categories: invoice, contract, report, correspondence, legal, hr, other. Respond with just the category name." classification_prompt = "Classify this document:\n\n" + LEFT(content, 5000) -classification_result = LLM classification_prompt - -' Parse AI response (simplified - in production use proper JSON parsing) -category = "other" -IF INSTR(classification_result, "invoice") > 0 THEN - category = "invoice" -ELSE IF INSTR(classification_result, "contract") > 0 THEN - category = "contract" -ELSE IF INSTR(classification_result, "report") > 0 THEN - category = "report" -ELSE IF INSTR(classification_result, "legal") > 0 THEN - category = "legal" -ELSE IF INSTR(classification_result, "hr") > 0 THEN - category = "hr" -END IF +category = TRIM(LCASE(LLM classification_prompt)) ' Move to appropriate folder destination = category + "/" + document_name MOVE local_path, destination ' Create searchable index entry -filename = document_name -original_url = document_url -stored_path = destination -content_preview = LEFT(content, 1000) -full_text = content -classification_details = classification_result -uploaded_by = uploader_email -processed_at = NOW() - -doc_id = INSERT "documents", filename, original_url, stored_path, category, content_preview, full_text, classification_details, uploaded_by, processed_at +doc_id = INSERT "documents", document_name, document_url, destination, category, LEFT(content, 1000), content, uploader_email, NOW() ' Add to knowledge base for future queries USE KB category + "-docs" ' Category-specific processing -SELECT CASE category - CASE "invoice" - ' Extract invoice details - SET CONTEXT "Extract from this invoice: vendor name, invoice number, date, due date, total amount, line items. Respond in JSON." - invoice_data = LLM content - - ' Create payable record - payable_doc_id = doc_id - extracted_data = invoice_data - payable_status = "pending_review" - payable_created_at = NOW() - INSERT "accounts_payable", payable_doc_id, extracted_data, payable_status, payable_created_at - - SEND MAIL "accounting@company.com", "New Invoice for Review", "A new invoice has been uploaded and classified.\n\nDocument: " + document_name + "\nCategory: Invoice\n\nPlease review in the accounting portal." - - CASE "contract" - ' Extract contract details - SET CONTEXT "Extract from this contract: parties involved, effective date, expiration date, key terms, renewal clauses. Respond in JSON." - contract_data = LLM content - - contract_doc_id = doc_id - contract_extracted = contract_data - contract_status = "active" - contract_created_at = NOW() - INSERT "contracts", contract_doc_id, contract_extracted, contract_status, contract_created_at - - SEND MAIL "legal@company.com", "New Contract Uploaded", "A new contract has been processed.\n\nDocument: " + document_name + "\n\nDetails: " + contract_data - - CASE "hr" - SEND MAIL "hr@company.com", "New HR Document", "A new HR document has been uploaded: " + document_name -END SELECT +IF category = "invoice" THEN + SET CONTEXT "Extract from this invoice: vendor name, invoice number, date, due date, total amount. Respond in JSON." + invoice_data = LLM content + INSERT "accounts_payable", doc_id, invoice_data, "pending_review", NOW() + SEND MAIL "accounting@company.com", "New Invoice for Review", "A new invoice has been uploaded.\n\nDocument: " + document_name +END IF + +IF category = "contract" THEN + SET CONTEXT "Extract from this contract: parties involved, effective date, expiration date, key terms. Respond in JSON." + contract_data = LLM content + INSERT "contracts", doc_id, contract_data, "active", NOW() + SEND MAIL "legal@company.com", "New Contract Uploaded", "A new contract has been processed.\n\nDocument: " + document_name +END IF + +IF category = "hr" THEN + SEND MAIL "hr@company.com", "New HR Document", "A new HR document has been uploaded: " + document_name +END IF ' Notify uploader -SEND MAIL uploader_email, "Document Processed: " + document_name, "Your document has been successfully processed.\n\nCategory: " + category + "\nDocument ID: " + doc_id + "\n\nYou can now search for this document in the document portal." +SEND MAIL uploader_email, "Document Processed: " + document_name, "Your document has been successfully processed.\n\nCategory: " + category + "\nDocument ID: " + doc_id -' Return result result_status = "processed" result_doc_id = doc_id result_category = category -result_path = destination ``` -## 7. Real-time Data Sync Tool +--- -Bidirectional sync between systems. +## 5. Real-time Data Sync (CRM to ERP) -```basic +Bidirectional sync between systems via webhook. + +```botbook/src/chapter-06-gbdialog/examples-consolidated.bas#L332-420 ' data-sync.bas ' Real-time data synchronization between CRM and ERP WEBHOOK "crm-update" -' Handle CRM webhook event_type = body.event record_type = body.record_type record_id = body.record_id @@ -653,82 +305,42 @@ data = body.data timestamp = body.timestamp ' Log sync event -sync_source = "crm" -sync_event = event_type -sync_record_type = record_type -sync_record_id = record_id -sync_timestamp = source_timestamp -received_at = NOW() -INSERT "sync_logs", sync_source, sync_event, sync_record_type, sync_record_id, sync_timestamp, received_at +INSERT "sync_logs", "crm", event_type, record_type, record_id, timestamp, NOW() ' Check for sync conflicts last_erp_update = FIND "erp_sync_status", "record_id=" + record_id IF last_erp_update.updated_at > timestamp THEN - ' ERP has newer data - conflict - WITH conflict = NEW OBJECT - .record_id = record_id - .crm_timestamp = timestamp - .erp_timestamp = last_erp_update.updated_at - .crm_data = data - .erp_data = last_erp_update.data - .status = "pending_resolution" - END WITH - INSERT "sync_conflicts", conflict - + INSERT "sync_conflicts", record_id, timestamp, last_erp_update.updated_at, data, last_erp_update.data, "pending_resolution" SEND MAIL "data-admin@company.com", "Sync Conflict Detected", "Record " + record_id + " has conflicting updates. Please resolve in the admin portal." - - WITH result = NEW OBJECT - .status = "conflict" - .message = "Newer data exists in ERP" - END WITH + result_status = "conflict" + result_message = "Newer data exists in ERP" EXIT END IF -' Transform data for ERP format -SELECT CASE record_type - CASE "customer" - WITH erp_data = NEW OBJECT - .customer_code = record_id - .company_name = data.company - .contact_name = data.contact_first_name + " " + data.contact_last_name - .email = data.email - .phone = data.phone - .billing_address = data.address.street + ", " + data.address.city + ", " + data.address.state + " " + data.address.zip - .credit_limit = data.credit_limit - .payment_terms = data.payment_terms - .updated_at = NOW() - END WITH - - erp_endpoint = "/api/customers/" + record_id - - CASE "order" - WITH erp_data = NEW OBJECT - .order_number = record_id - .customer_code = data.customer_id - .order_date = data.created_at - .ship_date = data.expected_ship_date - .line_items = data.products - .subtotal = data.subtotal - .tax = data.tax - .total = data.total - .status = data.status - END WITH - - erp_endpoint = "/api/orders/" + record_id - - CASE "product" - WITH erp_data = NEW OBJECT - .sku = record_id - .description = data.name - .category = data.category - .unit_price = data.price - .cost = data.cost - .weight = data.weight - .dimensions = data.dimensions - END WITH - - erp_endpoint = "/api/products/" + record_id -END SELECT +' Transform data for ERP format based on record type +IF record_type = "customer" THEN + erp_endpoint = "/api/customers/" + record_id + erp_customer_code = record_id + erp_company_name = data.company + erp_contact_name = data.contact_first_name + " " + data.contact_last_name + erp_email = data.email + erp_phone = data.phone +END IF + +IF record_type = "order" THEN + erp_endpoint = "/api/orders/" + record_id + erp_order_number = record_id + erp_customer_code = data.customer_id + erp_order_date = data.created_at + erp_total = data.total +END IF + +IF record_type = "product" THEN + erp_endpoint = "/api/products/" + record_id + erp_sku = record_id + erp_description = data.name + erp_unit_price = data.price +END IF ' Send to ERP erp_api_key = GET BOT MEMORY "erp_api_key" @@ -736,42 +348,206 @@ SET HEADER "Authorization", "Bearer " + erp_api_key SET HEADER "Content-Type", "application/json" IF event_type = "create" THEN - erp_result = POST "https://erp.company.com" + erp_endpoint, erp_data + erp_result = POST "https://erp.company.com" + erp_endpoint, data ELSE IF event_type = "update" THEN - erp_result = PUT "https://erp.company.com" + erp_endpoint, erp_data + erp_result = PUT "https://erp.company.com" + erp_endpoint, data ELSE IF event_type = "delete" THEN erp_result = DELETE "https://erp.company.com" + erp_endpoint END IF ' Update sync status -WITH sync_status = NEW OBJECT - .record_id = record_id - .record_type = record_type - .last_crm_update = timestamp - .last_erp_sync = NOW() - .sync_result = erp_result.status - .data = erp_data -END WITH -SAVE "erp_sync_status", record_id, sync_status +SAVE "erp_sync_status", record_id, record_type, timestamp, NOW(), erp_result.status, data -' Update sync log with result -WITH log_update = NEW OBJECT - .sync_completed_at = NOW() - .erp_response = erp_result.status -END WITH -UPDATE "sync_logs", "record_id=" + record_id + " AND source='crm'", log_update - -WITH result = NEW OBJECT - .status = "synced" - .record_id = record_id - .erp_status = erp_result.status -END WITH +result_status = "synced" +result_record_id = record_id +result_erp_status = erp_result.status ``` +--- + +## 6. Scheduled Lead Nurturing Job + +Automated lead follow-up and nurturing campaign. + +```botbook/src/chapter-06-gbdialog/examples-consolidated.bas#L422-490 +' lead-nurturing.bas +' Scheduled lead nurturing campaign + +SET SCHEDULE "lead-nurture", "0 9 * * *" + +' Find leads needing follow-up +cold_leads_3_days = FIND "leads", "status='cold' AND DATEDIFF(NOW(), last_contact) >= 3" +cold_leads_7_days = FIND "leads", "status='cold' AND DATEDIFF(NOW(), last_contact) >= 7" +cold_leads_14_days = FIND "leads", "status='cold' AND DATEDIFF(NOW(), last_contact) >= 14" +cold_leads_30_days = FIND "leads", "status='cold' AND DATEDIFF(NOW(), last_contact) >= 30" + +' 3-day follow-up: Tips email +FOR EACH lead IN cold_leads_3_days + IF lead.nurture_stage = 0 THEN + SEND MAIL lead.email, "5 Tips to Improve Your Business", "templates/nurture-tips.html" + UPDATE "leads", "id=" + lead.id, 1, NOW() + END IF +NEXT lead + +' 7-day follow-up: Case study +FOR EACH lead IN cold_leads_7_days + IF lead.nurture_stage = 1 THEN + SEND MAIL lead.email, "Case Study: How We Helped Similar Companies", "templates/nurture-case-study.html" + UPDATE "leads", "id=" + lead.id, 2, NOW() + END IF +NEXT lead + +' 14-day follow-up: Free consultation +FOR EACH lead IN cold_leads_14_days + IF lead.nurture_stage = 2 THEN + SEND MAIL lead.email, "Free Consultation Offer", "templates/nurture-consultation.html" + UPDATE "leads", "id=" + lead.id, 3, NOW() + END IF +NEXT lead + +' 30-day follow-up: Special offer +FOR EACH lead IN cold_leads_30_days + IF lead.nurture_stage = 3 THEN + SEND MAIL lead.email, "Special Limited Time Offer", "templates/nurture-special-offer.html" + UPDATE "leads", "id=" + lead.id, 4, NOW() + END IF +NEXT lead + +' Log nurturing stats +PRINT "Lead nurturing completed: " + UBOUND(cold_leads_3_days) + " at stage 1, " + UBOUND(cold_leads_7_days) + " at stage 2" +``` + +--- + +## 7. Payment Collection Reminder Job + +Automated payment reminders and collection workflow. + +```botbook/src/chapter-06-gbdialog/examples-consolidated.bas#L492-560 +' payment-collection.bas +' Scheduled payment collection reminders + +SET SCHEDULE "payment-reminders", "0 8 * * 1-5" + +' Find overdue invoices +due_today = FIND "invoices", "status='pending' AND due_date = CURDATE()" +overdue_3_days = FIND "invoices", "status='pending' AND DATEDIFF(NOW(), due_date) = 3" +overdue_7_days = FIND "invoices", "status='pending' AND DATEDIFF(NOW(), due_date) = 7" +overdue_14_days = FIND "invoices", "status='pending' AND DATEDIFF(NOW(), due_date) = 14" +overdue_30_days = FIND "invoices", "status='pending' AND DATEDIFF(NOW(), due_date) >= 30" + +' Due today reminder +FOR EACH invoice IN due_today + customer = FIND "customers", "id=" + invoice.customer_id + SEND MAIL customer.email, "Payment Due Today - Invoice #" + invoice.id, "Your invoice #" + invoice.id + " for $" + invoice.amount + " is due today. Please make payment to avoid late fees." +NEXT invoice + +' 3-day overdue: First reminder +FOR EACH invoice IN overdue_3_days + customer = FIND "customers", "id=" + invoice.customer_id + SEND MAIL customer.email, "Payment Overdue - Invoice #" + invoice.id, "Your invoice #" + invoice.id + " for $" + invoice.amount + " is now 3 days overdue. Please remit payment as soon as possible." + UPDATE "invoices", "id=" + invoice.id, "first_reminder_sent", NOW() +NEXT invoice + +' 7-day overdue: Second reminder with late fee warning +FOR EACH invoice IN overdue_7_days + customer = FIND "customers", "id=" + invoice.customer_id + SEND MAIL customer.email, "URGENT: Payment Overdue - Invoice #" + invoice.id, "Your invoice #" + invoice.id + " is now 7 days overdue. A late fee may be applied if not paid within 7 days." + UPDATE "invoices", "id=" + invoice.id, "second_reminder_sent", NOW() +NEXT invoice + +' 14-day overdue: Final notice +FOR EACH invoice IN overdue_14_days + customer = FIND "customers", "id=" + invoice.customer_id + late_fee = invoice.amount * 0.05 + new_total = invoice.amount + late_fee + SEND MAIL customer.email, "FINAL NOTICE: Invoice #" + invoice.id, "Your invoice is now 14 days overdue. A 5% late fee ($" + late_fee + ") has been applied. New total: $" + new_total + UPDATE "invoices", "id=" + invoice.id, late_fee, new_total, "final_notice_sent", NOW() + + ' Notify accounts receivable + SEND MAIL "ar@company.com", "Invoice Escalation: #" + invoice.id, "Invoice #" + invoice.id + " for " + customer.name + " is 14 days overdue. Amount: $" + new_total +NEXT invoice + +' 30+ day overdue: Send to collections +FOR EACH invoice IN overdue_30_days + IF invoice.status <> "collections" THEN + customer = FIND "customers", "id=" + invoice.customer_id + UPDATE "invoices", "id=" + invoice.id, "collections", NOW() + + ' Notify collections team + SEND MAIL "collections@company.com", "New Collections Account: " + customer.name, "Invoice #" + invoice.id + " - $" + invoice.total_with_fees + "\nCustomer: " + customer.name + "\nDays overdue: " + DATEDIFF(NOW(), invoice.due_date) + END IF +NEXT invoice + +PRINT "Payment reminders sent: " + UBOUND(due_today) + " due today, " + UBOUND(overdue_3_days) + " 3-day, " + UBOUND(overdue_7_days) + " 7-day" +``` + +--- + +## 8. Appointment Scheduling Webhook + +Handle appointment bookings from external calendar systems. + +```botbook/src/chapter-06-gbdialog/examples-consolidated.bas#L562-620 +' appointment-webhook.bas +' Handle appointment scheduling from external systems + +WEBHOOK "appointment-booked" + +appointment_id = body.appointment_id +customer_email = body.customer.email +customer_name = body.customer.name +customer_phone = body.customer.phone +service_type = body.service +appointment_date = body.date +appointment_time = body.time +staff_id = body.staff_id + +' Validate +IF appointment_id = "" OR customer_email = "" THEN + result_status = 400 + result_error = "Missing required fields" + EXIT +END IF + +' Check staff availability +existing = FIND "appointments", "staff_id='" + staff_id + "' AND date='" + appointment_date + "' AND time='" + appointment_time + "'" +IF UBOUND(existing) > 0 THEN + result_status = 409 + result_error = "Time slot not available" + EXIT +END IF + +' Save appointment +SAVE "appointments", appointment_id, customer_email, customer_name, customer_phone, service_type, appointment_date, appointment_time, staff_id, "confirmed", NOW() + +' Get staff info +staff = FIND "staff", "id=" + staff_id + +' Send confirmation to customer +confirmation_msg = "Your appointment has been confirmed!\n\n📅 " + appointment_date + " at " + appointment_time + "\n🏢 Service: " + service_type + "\n👤 With: " + staff.name + "\n\nPlease arrive 10 minutes early." +SEND MAIL customer_email, "Appointment Confirmed - " + service_type, confirmation_msg + +' Send SMS reminder setup +SET SCHEDULE "reminder-" + appointment_id, DATEADD(appointment_date + " " + appointment_time, -24, "hour") + +' Notify staff +SEND MAIL staff.email, "New Appointment: " + customer_name, "You have a new appointment:\n\n📅 " + appointment_date + " at " + appointment_time + "\n👤 Customer: " + customer_name + "\n📞 Phone: " + customer_phone + "\n🏢 Service: " + service_type + +' Add to calendar +BOOK staff.email, "Appointment: " + customer_name + " - " + service_type, appointment_date, appointment_time, 60 + +result_status = "confirmed" +result_appointment_id = appointment_id +``` + +--- + ## See Also -- [Keywords Reference](./keywords.md) - Complete keyword documentation -- [WEBHOOK](./keyword-webhook.md) - Creating API endpoints -- [SET SCHEDULE](./keyword-set-schedule.md) - Scheduled automation -- [Data Operations](./keywords.md#database--data-operations) - Database keywords -- [File Operations](./keywords.md#file--document-operations) - File handling \ No newline at end of file +- [Keywords Reference](./keywords.md) — Complete keyword documentation +- [WEBHOOK](./keyword-webhook.md) — Creating API endpoints +- [SET SCHEDULE](./keyword-set-schedule.md) — Scheduled automation +- [Data Operations](./keywords-data.md) — Database keywords +- [File Operations](./keywords-file.md) — File handling +- [HTTP Operations](./keywords-http.md) — REST API calls \ No newline at end of file diff --git a/src/executive-vision.md b/src/executive-vision.md index 84ba6e46..12a9b252 100644 --- a/src/executive-vision.md +++ b/src/executive-vision.md @@ -189,8 +189,40 @@ Pragmatismo develops General Bots as an open-source platform for enterprise AI a --- +## QUICK START + +Ready to see it in action? Skip to the hands-on guide: + +**[⚡ Quick Start: Run Your First Bot in 5 Minutes →](./chapter-01/quick-start.md)** + +Or continue reading for the full journey: + +| Path | Time | Best For | +|------|------|----------| +| [Quick Start](./chapter-01/quick-start.md) | 5 min | Developers who want to dive in immediately | +| [Introduction](./introduction.md) | 10 min | Understanding the "No Forms" philosophy | +| [Chapter 01](./chapter-01/README.md) | 15 min | Complete installation and first conversation | + +--- + ## NEXT STEPS -[Chapter 01: Run and Talk →](./chapter-01/README.md) + -Get started with your General Bots deployment in minutes. \ No newline at end of file +[Chapter 01: Run and Talk →](./chapter-01/README.md) \ No newline at end of file diff --git a/src/introduction.md b/src/introduction.md index 201cc031..2e9688de 100644 --- a/src/introduction.md +++ b/src/introduction.md @@ -1,7 +1,16 @@ # Introduction to General Bots +> **⚡ Want to skip ahead?** [Quick Start →](./chapter-01/quick-start.md) gets you running in 5 minutes. + **Build conversational AI bots in minutes, not months.** General Bots lets you create intelligent chatbots by writing simple [BASIC scripts](./chapter-06-gbdialog/basics.md) and dropping in your [documents](./chapter-02/gbkb.md). No complex frameworks, no cloud dependencies, no AI expertise required. +| Your Goal | Go To | +|-----------|-------| +| Run a bot NOW | [Quick Start](./chapter-01/quick-start.md) | +| Understand the vision | Keep reading below | +| Write your first script | [Chapter 06: BASIC Dialogs](./chapter-06-gbdialog/README.md) | +| Add documents to bot | [Chapter 02: Packages](./chapter-02/README.md) | + ## The No Forms Movement General Bots in 2017 @@ -47,17 +56,57 @@ General Bots was born from this vision: **replace forms with conversations**. ### After: The Conversation Experience -``` -User: I need help with my order -Bot: I'd be happy to help! What's your order number? -User: It's 12345 -Bot: Found it - your laptop order from last week. What's the issue? -User: It arrived damaged -Bot: I'm sorry to hear that. I'll create a return label for you. - Should I send it to your email on file? -User: Yes please -Bot: Done! Check your inbox. Is there anything else? -``` + **Benefits:** - Natural and intuitive