Chat Agent Flow

This flow shows how chat requests are processed, including system instructions, vector stores, n8n webhook tools, streaming, and history persistence.

Key Steps

  • Client sends chat request to /api/chat with tenantId and messages.
  • Server resolves system prompt (tenant override or default).
  • Server loads tenant vector store IDs and attaches fileSearch tools.
  • Server loads enabled webhooks from webhook_tools and attaches them as agent tools.
  • Agent is created with model gpt-4o-mini, instructions, and tools.
  • Conversation ID is created or reused for continuity.
  • Streaming response is sent via SSE (text + agent events).
  • When agent uses a webhook tool: executeWebhook runs, logs to webhook_logs, returns result.
  • User and assistant messages are saved to chat_history asynchronously.
  • Client renders streamed text and optional agent step events.

Chat Agent Flow

flowchart TD A["User submits chat message"] --> B["POST /api/chat (tenantId, messages, conversationId)"] B --> C["streamChatCompletion(tenantId, messages, conversationId)"] C --> D["getTenantConfig(tenantId)"] D --> E["Resolve system prompt (custom or default)"] E --> F["Load tenant vector store IDs + image store ID"] F --> G["Load enabled webhooks from webhook_tools"] G --> H["Attach fileSearch tools if stores exist"] H --> I["Attach webhook tools (n8n etc)"] I --> J["Create Agent with model gpt-4o + instructions + tools"] J --> K["Create or reuse conversationId (OpenAI Conversations)"] K --> L["Agent run with streaming"] L --> M["SSE stream to client (text + agent events)"] B --> N["Save user message to chat_history (async)"] M --> O["Collect assistant text from stream"] O --> P["Save assistant message to chat_history (async)"] Q["Client receives SSE"] --> R["Update UI incrementally"] R --> S["Render agent steps + tool events (optional)"] S --> T["Persist conversationId in localStorage"]

n8n Webhook Flow

Webhooks configured in Admin (n8n Webhooks) become agent tools. Calls are logged to webhook_logs.

flowchart TD W1["Admin: Add webhook (URL, method, params)"] --> W2["webhook_tools"] W2 --> A1["prepareChatCompletion: load enabled webhooks"] A1 --> A2["buildZodSchema per webhook"] A2 --> A3["tool(execute: executeWebhook)"] A3 --> A4["Attach to Agent"] A4 --> R1["When agent calls: executeWebhook"] R1 --> R2["Log to webhook_logs"] R2 --> R3["HTTP request to n8n URL"] R3 --> R4["Return result to agent"]