feat(captain): align assistant resources
This commit is contained in:
@@ -16,9 +16,9 @@ Build GoChat as a Go backend that can directly reuse the frontend from `referenc
|
||||
|
||||
## Current Baseline
|
||||
|
||||
- Latest implementation checkpoint: `feat(inboxes): enforce chatwoot inbox limits`.
|
||||
- Latest documentation checkpoint: this checkpoint, recorded with the B10.4 account inbox-limit implementation.
|
||||
- Worktree status at this implementation checkpoint: B10.4 enforces Chatwoot account-level `usage_limits[:inboxes]` during generic inbox and dedicated channel creation; next active slice is B11 Captain/Copilot persistence and feature gates.
|
||||
- Latest implementation checkpoint: `feat(captain): align assistant resources`.
|
||||
- Latest documentation checkpoint: this checkpoint, recorded with the B11.1a Captain assistant resource implementation.
|
||||
- Worktree status at this implementation checkpoint: B11.1a aligns Captain assistant CRUD, tools, account-scoped show/update/delete, and assistant inbox binding/list/delete payloads with the reused Chatwoot frontend; next active slice is B11.1b Captain documents/scenarios/responses/custom tools payload depth.
|
||||
- `go test ./...` passes.
|
||||
- Route dump succeeds with `TOTAL: 830` after adding the Chatwoot-compatible applied-SLA index route.
|
||||
- Route parity artifacts now exist under `docs/parity/` and are generated by `cmd/route_parity`.
|
||||
@@ -55,7 +55,7 @@ Next ordered checkpoints:
|
||||
| Phase 1 | Meilisearch search engine | Review | B6 payload parity, optional live gate, and DB-fallback hardening are implemented; an actual live Meilisearch run is optional and environment-dependent |
|
||||
| Phase 2 | Route and controller parity audit | Doing | Ruby/Bundler unavailable, so Chatwoot route extraction currently uses static `routes.rb` fallback |
|
||||
| Phase 3 | Data and serializer parity | Doing | JSON fixture coverage is partial and still endpoint-family based |
|
||||
| Phase 4 | Enterprise feature completion | Doing | B7, B8, B9, and B10 are in Review; B11 Captain/Copilot is the next active enterprise slice |
|
||||
| Phase 4 | Enterprise feature completion | Doing | B7, B8, B9, and B10 are in Review; B11 Captain/Copilot assistant resources are partially landed and deeper Captain/Copilot resources remain active |
|
||||
| Phase 5 | Background jobs and integrations | Planned | durable worker choice and job parity are open |
|
||||
| Phase 6 | Core placeholder burn-down | Doing | account/contact/conversation/message/inbox placeholder groups remain broad |
|
||||
| Phase 7 | Verification harness | Planned | search live gate and reused-frontend smoke harness are not complete |
|
||||
@@ -146,12 +146,13 @@ This ledger records the committed parity checkpoints that future slices should b
|
||||
| `feat(custom-roles): align chatwoot permissions` | Completed B10.3 CustomRole parity: custom roles now accept and serialize Chatwoot permission arrays, raw list/show/create/update/delete payloads match the enterprise Jbuilder views, admin gates are enforced, `AccountUser.role` stays `agent` while `custom_role_id` drives custom permissions, profile account payloads include `custom_role_id/custom_role/permissions`, and delete clears related account users. | `go test ./internal/handler/api/v1 -run CustomRole -count=1`; `go test ./internal/service -run 'CustomRole\|RBAC' -count=1`; `go test ./internal/model -run 'CustomRole\|AccountUser' -count=1`; `go test ./internal/middleware -run AccountScope -count=1`; handler/service/model packages passed; full verification recorded below. No route changes; route dump remains `TOTAL: 830`. | Continue B10.4 remaining InboxLimit/account-limit create-path enforcement. |
|
||||
| `docs: land inbox limit handoff tracker` | Landed the B10.4 reference findings and implementation contract: Chatwoot account inbox limits come from `Current.account.usage_limits[:inboxes]`, over-limit create returns `402 { error: "Account limit exceeded. Upgrade to a higher plan" }`, and capacity-policy `InboxCapacityLimit` is explicitly separate assignment-capacity data. | Documentation-only checkpoint; `git diff --check` passed. | Start B10.4 implementation from the recorded guard, migration, handler, and test plan. |
|
||||
| `feat(inboxes): enforce chatwoot inbox limits` | Completed B10.4 account-level inbox limit parity: `accounts.inbox_limit` now represents Chatwoot `usage_limits[:inboxes]`, `InboxService.EnsureCanCreateInbox` blocks over-limit creates before persistence, generic inbox and dedicated channel create paths return `402 { error: "Account limit exceeded. Upgrade to a higher plan" }`, and LINE/email/Twilio plus other channel handlers avoid orphan channel rows. | `go test ./internal/handler/api/v1 -run 'Inbox\|Channel\|Capacity\|Limit' -count=1`; `go test ./internal/service -run 'Inbox\|Channel\|Capacity\|Limit' -count=1`; handler and service packages passed; full verification recorded below. No route changes; route dump remains `TOTAL: 830`. | Continue B11 Captain/Copilot persistence, safe disabled states, and frontend payload parity. |
|
||||
| `feat(captain): align assistant resources` | Completed B11.1a Captain assistant resource parity for the reused dashboard assistant client: assistant list/show/create/update/delete now use raw Chatwoot/Jbuilder payloads, nested `{ assistant: ... }` bodies are accepted, assistant access is account-scoped, `/captain/assistants/tools` returns the built-in tool array, and assistant inbox bind/list/delete routes use Chatwoot `{ payload, meta }`, raw inbox, and `204` contracts. | `go test ./internal/handler/api/v1 -run CaptainAssistant -count=1`; `go test ./internal/service -run CaptainAssistant -count=1`; route dump/parity regenerated with unchanged `TOTAL: 830`; focused handler fixtures cover account scoping, tools, inbox binding, and no local `{ success, data }` envelopes. | Continue B11.1b with Captain documents, scenarios, assistant responses, bulk actions, and custom tools payload depth; B11 stays Doing until Copilot, LLM/document gates, and smoke coverage land. |
|
||||
|
||||
## Next Slice Contract
|
||||
|
||||
Completed implementation slice: B10.4 now enforces account-level inbox create limits and frontend-readable over-limit errors.
|
||||
Completed implementation slice: B11.1a now aligns Captain assistant CRUD, tools, and assistant inbox bindings with Chatwoot frontend payloads.
|
||||
|
||||
Next implementation slice: start B11 Captain/Copilot persistence, safe LLM feature gates, and frontend payload parity. B9.3 delayed/durable worker scheduling and B9.4 macro attachment depth remain named Phase 5 follow-ups.
|
||||
Next implementation slice: continue B11.1b Captain documents, scenarios, assistant responses, bulk actions, and custom tools payload depth before moving to B11.2 Copilot persistence and safe LLM/document gates. B9.3 delayed/durable worker scheduling and B9.4 macro attachment depth remain named Phase 5 follow-ups.
|
||||
|
||||
| Step | Required result | Reference source | Verification |
|
||||
| --- | --- | --- | --- |
|
||||
@@ -170,7 +171,9 @@ Next implementation slice: start B11 Captain/Copilot persistence, safe LLM featu
|
||||
| N13 | Keep B9.1c execution outcome logging as current automation observability baseline. | Chatwoot automation listener/action service rescue behavior and Go execution log service. | Done by `feat(automation): record rule execution outcomes`; skipped/failed/success action results, event names, and no-stop-on-match behavior are covered. |
|
||||
| N14 | Keep B9.1d external action delivery boundary as current action-delivery baseline. | Chatwoot `AutomationRules::ActionService`, `WebhookJob`, transcript mailer path, current Go action service. | Done by `feat(automation): deliver retryable external actions`; webhook/email transcript actions are timeout-bound, retryable, observable in action results, and covered by fake HTTP/mailer tests. |
|
||||
| N15 | Keep B9.2 macro CRUD/execute parity as current macro baseline. | Chatwoot `MacrosController`, `Macro`, `MacrosExecutionJob`, `Macros::ExecutionService`, dashboard macro API/store. | Done by `feat(macros): align chatwoot macro payloads`; frontend payloads, visibility/authorization, display-ID execution, and real conversation/message/label/status side effects are covered. |
|
||||
| N16 | Update this tracker after every implementation checkpoint. | This document. | `git diff --check`; `go test ./...` for Go changes. |
|
||||
| N16 | Keep B10.4 account inbox limits as current limit baseline. | Chatwoot account `usage_limits[:inboxes]` and request exception handler. | Done by `feat(inboxes): enforce chatwoot inbox limits`; generic and dedicated channel create paths return the exact over-limit `402` response and avoid orphan rows. |
|
||||
| N17 | Keep B11.1a Captain assistant resources as current Captain baseline. | `reference/chatwoot/enterprise/app/controllers/api/v1/accounts/captain/assistants_controller.rb`, Captain inboxes controller, assistant Jbuilder views, dashboard Captain assistant/inbox API clients, `config/agents/tools.yml`. | Done by `feat(captain): align assistant resources`; assistant CRUD/tools/inbox binding payloads are account-scoped and frontend-shaped. |
|
||||
| N18 | Update this tracker after every implementation checkpoint. | This document. | `git diff --check`; `go test ./...` for Go changes. |
|
||||
|
||||
Current B2 profile checkpoint:
|
||||
|
||||
@@ -399,7 +402,7 @@ Upcoming enterprise task boards:
|
||||
| B10 | B10.2 | Add audit writer coverage for representative core and enterprise mutations: inbox, conversation assignment/status, SLA policy, capacity policy, custom role, automation, macro, CSAT review notes. | Chatwoot audit hooks and current Go service mutation points. | Mutation tests assert audit rows with actor, auditable type/id, account, IP/request metadata where available. | Done by `feat(audit): record enterprise mutations` and `feat(audit): cover operational mutations` |
|
||||
| B10 | B10.3 | Align CustomRole permission keys, account-user role resolution, deletion nullification, and authorization failure payloads. | Chatwoot custom role controllers/policies and permission constants. | Permission matrix tests for admin/non-admin/custom-role access. | Done by `feat(custom-roles): align chatwoot permissions` |
|
||||
| B10 | B10.4 | Review remaining InboxLimit/account-limit create-path enforcement outside capacity policies. | Chatwoot enterprise account/inbox limit policies. | Inbox/channel create tests for over-limit behavior and frontend-readable errors. | Done by `feat(inboxes): enforce chatwoot inbox limits` |
|
||||
| B11 | B11.1 | Align Captain assistant CRUD, inbox bindings, responses, documents, scenarios, and custom tools payloads. | Captain controllers/services/frontend clients under `reference/chatwoot`. | Handler/service fixtures for every Captain dashboard client path. | Todo |
|
||||
| B11 | B11.1 | Align Captain assistant CRUD, inbox bindings, responses, documents, scenarios, and custom tools payloads. | Captain controllers/services/frontend clients under `reference/chatwoot`. | Handler/service fixtures for every Captain dashboard client path. | Doing; assistant CRUD/tools/inbox binding landed by `feat(captain): align assistant resources` |
|
||||
| B11 | B11.2 | Align Copilot threads, messages, tasks, preferences, playground/tool-call behavior, and disabled-state feature gates. | Copilot controllers/services/frontend clients under `reference/chatwoot`. | Copilot handler/service tests for persistence, disabled LLM state, and frontend payloads. | Todo |
|
||||
| B11 | B11.3 | Add document sync/embedding/LLM job boundaries where external dependencies are required. | Captain/Copilot jobs and document services. | Worker tests or explicit feature-gated fallback tests. | Todo |
|
||||
| B12 | B12.1 | Add a repeatable command to run the reused Chatwoot frontend against GoChat. | `reference/chatwoot` frontend boot/auth/API clients. | Smoke command documented and runnable locally. | Todo |
|
||||
@@ -758,10 +761,21 @@ B11 Captain/Copilot breakdown:
|
||||
|
||||
| Step | Implementation target | Reference source | Required tests | Status |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| B11.1 | Align Captain assistant CRUD, inbox bindings, scenarios, responses, and document/custom-tool payloads. | `reference/chatwoot` Captain controllers/services/frontend clients. | Handler/service tests for assistant lifecycle, nested resources, account scoping, and feature-disabled state. | Todo |
|
||||
| B11.1a | Align Captain assistant CRUD, tools, and inbox binding/list/delete payloads used by `assistant.js` and `inboxes.js`. | Assistant controller, inboxes controller, assistant Jbuilder views, `config/agents/tools.yml`, dashboard Captain assistant/inbox clients. | Handler tests for assistant lifecycle, account scoping, tools array, raw inbox binding, list meta, and `204` delete. | Done by `feat(captain): align assistant resources` |
|
||||
| B11.1b | Align Captain documents, scenarios, assistant responses, bulk actions, and custom tools payloads. | `documents_controller.rb`, `scenarios_controller.rb`, `assistant_responses_controller.rb`, `bulk_actions_controller.rb`, `custom_tools_controller.rb`, dashboard Captain clients. | Handler/service fixtures for list/show/create/update/delete, account scoping, sync status, and no local response envelopes. | Todo |
|
||||
| B11.2 | Implement document sync/indexing gates for Meilisearch or the chosen embedding/search backend without blocking the frontend when LLM config is absent. | Captain document and embedding services. | Tests cover disabled state, failed sync observability, and successful fake backend indexing. | Todo |
|
||||
| B11.3 | Align Copilot thread/message/task APIs, tool calls, preferences, and streaming fallback. | Copilot controllers/services/frontend clients. | Handler tests cover thread/message/task lifecycle, tool-call persistence, disabled-state payloads, and non-streaming fallback. | Todo |
|
||||
|
||||
B11.1a current checkpoint:
|
||||
|
||||
- Reference files inspected for this landing slice: `reference/chatwoot/config/routes.rb:62-89`, enterprise Captain `assistants_controller.rb`, `inboxes_controller.rb`, assistant/inbox Jbuilder views, dashboard `assistant.js`/`inboxes.js`, and `reference/chatwoot/config/agents/tools.yml`.
|
||||
- Assistant list now returns `{ payload: [...], meta: { total_count, page: 1 } }`; show/create/update return the raw assistant serializer with Unix `created_at`/`updated_at`, JSON `config`, `guardrails`, and `response_guidelines`; delete returns `204 No Content`.
|
||||
- Create/update accept Chatwoot nested `{ assistant: { ... } }` bodies while retaining flat compatibility for local callers.
|
||||
- Assistant get/update/delete are scoped by account, so another account cannot access or remove the resource by primary key.
|
||||
- `/api/v1/accounts/:account_id/captain/assistants/tools` returns the raw built-in tool array from the current reference `tools.yml` contract and is registered before dynamic assistant routes.
|
||||
- Assistant inbox binding accepts `{ inbox: { inbox_id } }`, validates both assistant and inbox account ownership, returns the raw inbox serializer on create, returns `{ payload, meta }` on list, and returns `204` for account-scoped delete.
|
||||
- Route dump/parity were regenerated after the router handler remap; external route count remains `TOTAL: 830` and tracked route parity remains unchanged.
|
||||
|
||||
B11 landing rules:
|
||||
|
||||
| Area | Landing requirement | Done signal |
|
||||
@@ -1160,7 +1174,7 @@ Included checklist:
|
||||
- [x] Custom roles and permission checks.
|
||||
- [x] Agent capacity and assignment limits.
|
||||
- [ ] Assignment policies and auto-assignment compatibility.
|
||||
- [ ] Captain/Copilot assistant, custom tools, scenarios, documents, responses, and inbox bindings.
|
||||
- [ ] Captain/Copilot assistant, custom tools, scenarios, documents, responses, and inbox bindings. Assistant CRUD/tools/inbox binding are landed; the rest remains active.
|
||||
- [x] CSAT survey response flow, metrics, filters, and review notes.
|
||||
- [x] Inbox limits and account/inbox usage enforcement.
|
||||
- [x] Automation rules, macros, execution logs, and action side effects.
|
||||
@@ -1179,7 +1193,7 @@ Enterprise tracking table:
|
||||
| P4.3 | Custom roles/permissions | `internal/model/custom_role.go`, `internal/service/custom_role_service.go`, `internal/middleware/role_check.go`, `internal/handler/api/v1/custom_role_handler.go` | Permission arrays, raw admin payloads, administrator gates, account-user resolution, profile permissions, and delete nullification are implemented; keep in Review until frontend smoke covers enterprise settings. | Review |
|
||||
| P4.4 | Agent capacity | `internal/model/agent_capacity_policy.go`, `internal/service/agent_capacity_policy_service.go`, `internal/handler/api/v1/agent_capacity_handler.go`, `internal/autoassignment/*` | First align AgentCapacityPolicy API, serializers, nested users, and `InboxCapacityLimit` data contracts; then enforce capacity in manual/auto assignment. | Review |
|
||||
| P4.5 | Inbox limits | `internal/model/agent_capacity_policy.go` `InboxCapacityLimit`, plus legacy `internal/model/inbox_limit.go`, `internal/service/inbox_limit_service.go`, `internal/repository/inbox_limit_repo.go`, `internal/handler/api/v1/inbox_limit_handler.go` | Chatwoot enterprise nested `agent_capacity_policies/:policy_id/inbox_limits`, assignment-path enforcement, and account-level `usage_limits[:inboxes]` create-path enforcement are covered. | Review |
|
||||
| P4.6 | Captain/Copilot | `internal/model/captain_models.go`, `internal/model/copilot_models.go`, `internal/service/captain_*`, `internal/service/copilot_*`, `internal/handler/api/v1/captain_*`, `internal/handler/api/v1/copilot_handler.go` | Complete assistant, tools, scenarios, documents, responses, inbox bindings, suggestions, and streaming compatibility. | Todo |
|
||||
| P4.6 | Captain/Copilot | `internal/model/captain_models.go`, `internal/model/copilot_models.go`, `internal/service/captain_*`, `internal/service/copilot_*`, `internal/handler/api/v1/captain_*`, `internal/handler/api/v1/copilot_handler.go` | Assistant CRUD/tools/inbox binding payloads are aligned; complete Captain documents/scenarios/responses/custom tools, Copilot threads/messages/tasks, suggestions, document/LLM gates, and streaming compatibility. | Doing |
|
||||
| P4.7 | CSAT | `internal/csat/*`, `internal/automation/csat_survey_*`, `internal/handler/api/v1/csat_*`, `internal/service/csat_metrics_service.go` | Account-side list/metrics/review-note payloads, public update depth, resolve-triggered generic survey send, and download CSV are aligned; channel-specific template send hooks remain Phase 5 integration work. | Review |
|
||||
| P4.8 | Automation and macros | `internal/automation/*`, `internal/handler/api/v1/automation_rule_handler.go`, `internal/handler/api/v1/macro_handler.go` | Automation-rule CRUD/listener/log/external-action delivery and macro CRUD/display-ID execution parity are implemented; durable delayed actions and deeper macro attachment/file parity remain B9.3/B9.4 follow-ups. | Review |
|
||||
| P4.9 | Assignment policies | `internal/autoassignment/*`, `internal/automation/agent_bot_rule_listener.go` | Match Chatwoot assignment policy behavior and availability/capacity rules. | Doing |
|
||||
@@ -1196,7 +1210,7 @@ Enterprise work package breakdown:
|
||||
| Audit | Audit model parity, mutating action coverage, request metadata, filters/pagination, admin endpoint payloads. | List/admin payload parity is covered by `feat(audit): align chatwoot audit log payloads`; named representative writer coverage is covered by `feat(audit): record enterprise mutations` and `feat(audit): cover operational mutations`. | Review |
|
||||
| Custom roles | Permission-key parity, account-user role resolution, policy middleware, create/update/delete behavior. | Permission arrays, raw admin payloads, admin gates, RBAC/account-scope/profile resolution, and delete nullification are covered by `feat(custom-roles): align chatwoot permissions`. | Review |
|
||||
| Inbox limits | Account/inbox limit models, create/update enforcement, UI-readable limit responses, admin overrides. | Chatwoot nested capacity-limit API, assignment-path enforcement, and account-level create-limit `402` behavior are covered by B5/B7/B10.4. | Review |
|
||||
| Captain/Copilot | Assistants, inbox bindings, scenarios, responses, documents, tools, copilot threads/messages, tasks, streaming/tool-call behavior. | Route fixtures, persistence tests, feature gates for external LLM dependencies, frontend smoke screens. | Todo |
|
||||
| Captain/Copilot | Assistants, inbox bindings, scenarios, responses, documents, tools, copilot threads/messages, tasks, streaming/tool-call behavior. | Assistant CRUD/tools/inbox binding fixtures are covered by `feat(captain): align assistant resources`; route fixtures, feature gates for external LLM dependencies, and frontend smoke screens remain for deeper Captain/Copilot paths. | Doing |
|
||||
|
||||
Enterprise acceptance gates:
|
||||
|
||||
@@ -1431,3 +1445,4 @@ Verification milestone gates:
|
||||
- 2026-06-05: B10.3 CustomRole checkpoint prepared as `feat(custom-roles): align chatwoot permissions`; custom roles now accept/serialize Chatwoot permission arrays, return raw enterprise Jbuilder payloads, enforce administrator-only access, keep custom-role account users as `role=agent` with `custom_role_id`, load custom-role permissions through RBAC/AccountScope, expose profile account `custom_role_id/custom_role/permissions`, and nullify account users on role delete. Focused CustomRole/RBAC/model/AccountScope tests, handler/service/model package tests, and full verification were run before commit; sandboxed middleware package tests still require socket-capable execution for miniredis. Next slice is B10.4 InboxLimit create-path enforcement.
|
||||
- 2026-06-05: B10.4 handoff tracker prepared as `docs: land inbox limit handoff tracker`; the active plan now records the exact Chatwoot account inbox-limit source (`usage_limits[:inboxes]`), the `402 { error: "Account limit exceeded. Upgrade to a higher plan" }` response contract, the separation from capacity-policy `InboxCapacityLimit`, the required account schema guard, dedicated-channel precheck, no-orphan persistence tests, and updated enterprise status rows. Documentation-only checkpoint; `git diff --check` passed.
|
||||
- 2026-06-05: B10.4 InboxLimit checkpoint prepared as `feat(inboxes): enforce chatwoot inbox limits`; account-level `inbox_limit` now gates generic inbox and dedicated channel creation with Chatwoot's exact `402` error body, service and handler tests cover unlimited, below-limit, over-limit, and no-orphan LINE channel behavior, and B10 moves to Review. Focused inbox/channel/limit tests, handler/service package tests, escalated full `go test ./...`, and `git diff --check` passed. Next slice is B11 Captain/Copilot.
|
||||
- 2026-06-05: B11.1a Captain assistant checkpoint prepared as `feat(captain): align assistant resources`; assistant CRUD now returns Chatwoot raw assistant payloads and list meta, nested assistant request bodies are accepted, account-scoped get/update/delete prevents cross-account access, tools returns the raw built-in tool array, and assistant inbox create/list/delete use raw inbox/list/204 contracts. Focused CaptainAssistant handler/service tests passed, route dump/parity regenerated with unchanged `TOTAL: 830`, and `git diff --check` passed. Next slice is B11.1b Captain documents/scenarios/responses/custom tools.
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
"github.com/gochat/gochat/internal/service"
|
||||
applogger "github.com/gochat/gochat/pkg/logger"
|
||||
"github.com/gochat/gochat/pkg/pagination"
|
||||
"github.com/gochat/gochat/pkg/response"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// CaptainAssistantHandler handles CaptainAssistant REST API endpoints.
|
||||
@@ -26,83 +28,106 @@ func NewCaptainAssistantHandler(svc *service.CaptainAssistantService) *CaptainAs
|
||||
// Create creates a new captain assistant.
|
||||
// POST /api/v1/accounts/:account_id/captain_assistants
|
||||
func (h *CaptainAssistantHandler) Create(c *gin.Context) {
|
||||
accountID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
|
||||
var req service.CreateAssistantRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
if err := bindCaptainAssistantPayload(c, &req); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
assistant, err := h.svc.Create(c.Request.Context(), uint(accountID), &req)
|
||||
assistant, err := h.svc.Create(c.Request.Context(), accountID, &req)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Create captain assistant: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to create assistant")
|
||||
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
response.Created(c, assistant)
|
||||
c.JSON(http.StatusOK, captainAssistantPayload(assistant))
|
||||
}
|
||||
|
||||
// Get retrieves a captain assistant by ID.
|
||||
// GET /api/v1/accounts/:account_id/captain_assistants/:id
|
||||
func (h *CaptainAssistantHandler) Get(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
id, err := parseUintParam(c, "assistant_id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
assistant, err := h.svc.Get(c.Request.Context(), uint(id))
|
||||
assistant, err := h.svc.Get(c.Request.Context(), accountID, id)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Get captain assistant: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrNotFound, "assistant not found")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, assistant)
|
||||
c.JSON(http.StatusOK, captainAssistantPayload(assistant))
|
||||
}
|
||||
|
||||
// Update updates an existing captain assistant.
|
||||
// PUT /api/v1/accounts/:account_id/captain_assistants/:id
|
||||
func (h *CaptainAssistantHandler) Update(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
id, err := parseUintParam(c, "assistant_id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
var req service.UpdateAssistantRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
if err := bindCaptainAssistantPayload(c, &req); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
assistant, err := h.svc.Update(c.Request.Context(), uint(id), &req)
|
||||
assistant, err := h.svc.Update(c.Request.Context(), accountID, id, &req)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Update captain assistant: %v", err)
|
||||
if captainAssistantErrorStatus(err) == http.StatusNotFound {
|
||||
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrNotFound, "assistant not found")
|
||||
return
|
||||
}
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to update assistant")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, assistant)
|
||||
c.JSON(http.StatusOK, captainAssistantPayload(assistant))
|
||||
}
|
||||
|
||||
// Delete deletes a captain assistant.
|
||||
// DELETE /api/v1/accounts/:account_id/captain_assistants/:id
|
||||
func (h *CaptainAssistantHandler) Delete(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
id, err := parseUintParam(c, "assistant_id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.svc.Delete(c.Request.Context(), uint(id)); err != nil {
|
||||
if err := h.svc.Delete(c.Request.Context(), accountID, id); err != nil {
|
||||
applogger.L().Errorf("Delete captain assistant: %v", err)
|
||||
if captainAssistantErrorStatus(err) == http.StatusNotFound {
|
||||
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrNotFound, "assistant not found")
|
||||
return
|
||||
}
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to delete assistant")
|
||||
return
|
||||
}
|
||||
@@ -113,33 +138,36 @@ func (h *CaptainAssistantHandler) Delete(c *gin.Context) {
|
||||
// List retrieves captain assistants for an account.
|
||||
// GET /api/v1/accounts/:account_id/captain_assistants
|
||||
func (h *CaptainAssistantHandler) List(c *gin.Context) {
|
||||
accountID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
|
||||
p := pagination.Parse(c)
|
||||
assistants, count, err := h.svc.List(c.Request.Context(), uint(accountID), p.Offset, p.PerPage)
|
||||
assistants, count, err := h.svc.List(c.Request.Context(), accountID, 0, 1000)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("List captain assistants: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to list assistants")
|
||||
return
|
||||
}
|
||||
|
||||
response.OKWithMeta(c, assistants, p.Page, p.PerPage, count)
|
||||
payload := make([]gin.H, 0, len(assistants))
|
||||
for i := range assistants {
|
||||
payload = append(payload, captainAssistantPayload(&assistants[i]))
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"payload": payload, "meta": gin.H{"total_count": count, "page": 1}})
|
||||
}
|
||||
|
||||
// GetConfig retrieves the assistant's JSONB config.
|
||||
// GET /api/v1/accounts/:account_id/captain_assistants/:id/config
|
||||
func (h *CaptainAssistantHandler) GetConfig(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
id, err := parseUintAnyParam(c, "assistant_id", "id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
cfg, err := h.svc.GetConfig(c.Request.Context(), uint(id))
|
||||
cfg, err := h.svc.GetConfig(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("GetConfig captain assistant: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrNotFound, "assistant not found")
|
||||
@@ -152,7 +180,7 @@ func (h *CaptainAssistantHandler) GetConfig(c *gin.Context) {
|
||||
// SetConfig updates the assistant's JSONB config.
|
||||
// PUT /api/v1/accounts/:account_id/captain_assistants/:id/config
|
||||
func (h *CaptainAssistantHandler) SetConfig(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
id, err := parseUintAnyParam(c, "assistant_id", "id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
|
||||
return
|
||||
@@ -164,7 +192,7 @@ func (h *CaptainAssistantHandler) SetConfig(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.svc.SetConfig(c.Request.Context(), uint(id), &cfg); err != nil {
|
||||
if err := h.svc.SetConfig(c.Request.Context(), id, &cfg); err != nil {
|
||||
applogger.L().Errorf("SetConfig captain assistant: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to update config")
|
||||
return
|
||||
@@ -176,80 +204,191 @@ func (h *CaptainAssistantHandler) SetConfig(c *gin.Context) {
|
||||
// AssociateInbox binds an assistant to an inbox.
|
||||
// POST /api/v1/accounts/:account_id/captain_assistants/:id/inboxes
|
||||
func (h *CaptainAssistantHandler) AssociateInbox(c *gin.Context) {
|
||||
assistantID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
assistantID, err := parseUintParam(c, "assistant_id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid assistant id")
|
||||
return
|
||||
}
|
||||
accountID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
InboxID uint `json:"inbox_id" validate:"required"`
|
||||
Inbox struct {
|
||||
InboxID uint `json:"inbox_id"`
|
||||
} `json:"inbox"`
|
||||
InboxID uint `json:"inbox_id"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
|
||||
return
|
||||
}
|
||||
inboxID := req.InboxID
|
||||
if inboxID == 0 {
|
||||
inboxID = req.Inbox.InboxID
|
||||
}
|
||||
|
||||
if err := h.svc.AssociateInbox(c.Request.Context(), uint(assistantID), req.InboxID, uint(accountID)); err != nil {
|
||||
inbox, err := h.svc.AssociateInbox(c.Request.Context(), assistantID, inboxID, accountID)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("AssociateInbox: %v", err)
|
||||
if captainAssistantErrorStatus(err) == http.StatusNotFound {
|
||||
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrNotFound, "captain inbox not found")
|
||||
return
|
||||
}
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to associate inbox")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, gin.H{"associated": true})
|
||||
c.JSON(http.StatusOK, serializeInbox(inbox))
|
||||
}
|
||||
|
||||
// DissociateInbox unbinds an assistant from an inbox.
|
||||
// DELETE /api/v1/accounts/:account_id/captain_assistants/:id/inboxes/:inbox_id
|
||||
func (h *CaptainAssistantHandler) DissociateInbox(c *gin.Context) {
|
||||
assistantID, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
assistantID, err := parseUintParam(c, "assistant_id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid assistant id")
|
||||
return
|
||||
}
|
||||
inboxID, err := strconv.ParseUint(c.Param("inbox_id"), 10, 64)
|
||||
inboxID, err := parseUintParam(c, "inbox_id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid inbox_id")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.svc.DissociateInbox(c.Request.Context(), uint(assistantID), uint(inboxID)); err != nil {
|
||||
if err := h.svc.DissociateInbox(c.Request.Context(), accountID, assistantID, inboxID); err != nil {
|
||||
applogger.L().Errorf("DissociateInbox: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to dissociate inbox")
|
||||
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrNotFound, "captain inbox not found")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, gin.H{"dissociated": true})
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *CaptainAssistantHandler) ListInboxes(c *gin.Context) {
|
||||
accountID := parseAccountIDParam(c)
|
||||
if accountID == 0 {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid account_id")
|
||||
return
|
||||
}
|
||||
assistantID, err := parseUintParam(c, "assistant_id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid assistant id")
|
||||
return
|
||||
}
|
||||
inboxes, err := h.svc.ListInboxes(c.Request.Context(), accountID, assistantID)
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusNotFound, response.ErrNotFound, "assistant not found")
|
||||
return
|
||||
}
|
||||
payload := make([]gin.H, 0, len(inboxes))
|
||||
for i := range inboxes {
|
||||
payload = append(payload, serializeInbox(&inboxes[i]))
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"payload": payload, "meta": gin.H{"total_count": len(payload), "page": 1}})
|
||||
}
|
||||
|
||||
func (h *CaptainAssistantHandler) Tools(c *gin.Context) {
|
||||
accountID := parseAccountIDParam(c)
|
||||
c.JSON(http.StatusOK, h.svc.AvailableTools(c.Request.Context(), accountID))
|
||||
}
|
||||
|
||||
// GenerateResponse generates an AI response via RAG.
|
||||
// POST /api/v1/accounts/:account_id/captain_assistants/:id/generate_response
|
||||
func (h *CaptainAssistantHandler) GenerateResponse(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
id, err := parseUintAnyParam(c, "assistant_id", "id")
|
||||
if err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrBadRequest, "invalid id")
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Query string `json:"query" validate:"required"`
|
||||
Assistant struct {
|
||||
MessageContent string `json:"message_content"`
|
||||
Query string `json:"query"`
|
||||
} `json:"assistant"`
|
||||
MessageContent string `json:"message_content"`
|
||||
Query string `json:"query"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, err.Error())
|
||||
return
|
||||
}
|
||||
query := req.Query
|
||||
if query == "" {
|
||||
query = req.MessageContent
|
||||
}
|
||||
if query == "" {
|
||||
query = req.Assistant.Query
|
||||
}
|
||||
if query == "" {
|
||||
query = req.Assistant.MessageContent
|
||||
}
|
||||
if query == "" {
|
||||
response.AbortWithStatusError(c, http.StatusBadRequest, response.ErrValidation, "message_content is required")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.svc.GenerateResponse(c.Request.Context(), uint(id), req.Query)
|
||||
result, err := h.svc.GenerateResponse(c.Request.Context(), id, query)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("GenerateResponse: %v", err)
|
||||
response.AbortWithStatusError(c, http.StatusInternalServerError, response.ErrInternal, "failed to generate response")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, gin.H{"response": result})
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"response": result})
|
||||
}
|
||||
|
||||
func bindCaptainAssistantPayload(c *gin.Context, dst any) error {
|
||||
var raw map[string]json.RawMessage
|
||||
if err := c.ShouldBindJSON(&raw); err != nil {
|
||||
return err
|
||||
}
|
||||
if nested, ok := raw["assistant"]; ok {
|
||||
return json.Unmarshal(nested, dst)
|
||||
}
|
||||
body, err := json.Marshal(raw)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.Unmarshal(body, dst)
|
||||
}
|
||||
|
||||
func captainAssistantPayload(assistant *model.CaptainAssistant) gin.H {
|
||||
return gin.H{
|
||||
"account_id": assistant.AccountID,
|
||||
"config": rawJSONValue(assistant.Config),
|
||||
"created_at": assistant.CreatedAt.Unix(),
|
||||
"description": assistant.Description,
|
||||
"guardrails": rawJSONValue(assistant.Guardrails),
|
||||
"id": assistant.ID,
|
||||
"name": assistant.Name,
|
||||
"response_guidelines": rawJSONValue(assistant.ResponseGuidelines),
|
||||
"updated_at": assistant.UpdatedAt.Unix(),
|
||||
}
|
||||
}
|
||||
|
||||
func rawJSONValue(raw json.RawMessage) any {
|
||||
if len(raw) == 0 || string(raw) == "null" {
|
||||
return nil
|
||||
}
|
||||
var value any
|
||||
if err := json.Unmarshal(raw, &value); err != nil {
|
||||
return fmt.Sprintf("%s", raw)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func captainAssistantErrorStatus(err error) int {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return http.StatusNotFound
|
||||
}
|
||||
return http.StatusInternalServerError
|
||||
}
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gochat/gochat/internal/model"
|
||||
"github.com/gochat/gochat/internal/repository"
|
||||
"github.com/gochat/gochat/internal/service"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func setupCaptainAssistantHandlerTest(t *testing.T) (*gin.Engine, *gorm.DB) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
dbName := fmt.Sprintf("file:%s?mode=memory&cache=private", t.Name())
|
||||
db, err := gorm.Open(sqlite.Open(dbName), &gorm.Config{})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, db.AutoMigrate(
|
||||
&model.Account{},
|
||||
&model.Inbox{},
|
||||
&model.CaptainAssistant{},
|
||||
&model.CaptainInbox{},
|
||||
))
|
||||
t.Cleanup(func() {
|
||||
sqlDB, _ := db.DB()
|
||||
sqlDB.Close()
|
||||
})
|
||||
|
||||
assistantRepo := repository.NewCaptainAssistantRepo(db)
|
||||
inboxRepo := repository.NewCaptainInboxRepo(db)
|
||||
documentRepo := repository.NewCaptainDocumentRepo(db)
|
||||
responseRepo := repository.NewCaptainAssistantResponseRepo(db)
|
||||
svc := service.NewCaptainAssistantService(assistantRepo, inboxRepo, documentRepo, responseRepo, nil)
|
||||
handler := NewCaptainAssistantHandler(svc)
|
||||
|
||||
router := gin.New()
|
||||
assistants := router.Group("/api/v1/accounts/:account_id/captain/assistants")
|
||||
assistants.GET("/", handler.List)
|
||||
assistants.POST("/", handler.Create)
|
||||
assistants.GET("/tools", handler.Tools)
|
||||
assistants.GET("/:assistant_id", handler.Get)
|
||||
assistants.PUT("/:assistant_id", handler.Update)
|
||||
assistants.DELETE("/:assistant_id", handler.Delete)
|
||||
assistants.GET("/:assistant_id/inboxes", handler.ListInboxes)
|
||||
assistants.POST("/:assistant_id/inboxes", handler.AssociateInbox)
|
||||
assistants.DELETE("/:assistant_id/inboxes/:inbox_id", handler.DissociateInbox)
|
||||
return router, db
|
||||
}
|
||||
|
||||
func seedCaptainAssistantAccount(t *testing.T, db *gorm.DB, name string) *model.Account {
|
||||
t.Helper()
|
||||
account := &model.Account{Name: name, Locale: "en", Active: true}
|
||||
require.NoError(t, db.Create(account).Error)
|
||||
return account
|
||||
}
|
||||
|
||||
func captainAssistantJSONRequest(t *testing.T, router *gin.Engine, method, path string, body any) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
var reader *bytes.Reader
|
||||
if body == nil {
|
||||
reader = bytes.NewReader(nil)
|
||||
} else {
|
||||
payload, err := json.Marshal(body)
|
||||
require.NoError(t, err)
|
||||
reader = bytes.NewReader(payload)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(method, path, reader)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
router.ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
func TestCaptainAssistantHandler_CRUDUsesChatwootPayloadShape(t *testing.T) {
|
||||
router, db := setupCaptainAssistantHandlerTest(t)
|
||||
account := seedCaptainAssistantAccount(t, db, "Captain Org")
|
||||
basePath := "/api/v1/accounts/" + strconv.FormatUint(uint64(account.ID), 10) + "/captain/assistants"
|
||||
|
||||
createBody := map[string]any{
|
||||
"assistant": map[string]any{
|
||||
"name": "Fin",
|
||||
"description": "Support copilot",
|
||||
"config": map[string]any{
|
||||
"product_name": "GoChat",
|
||||
"temperature": 0.2,
|
||||
},
|
||||
"guardrails": []string{"never ask for passwords"},
|
||||
"response_guidelines": []string{"be concise"},
|
||||
},
|
||||
}
|
||||
w := captainAssistantJSONRequest(t, router, http.MethodPost, basePath+"/", createBody)
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
|
||||
var created map[string]any
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &created))
|
||||
assert.NotContains(t, created, "success")
|
||||
assert.NotContains(t, created, "data")
|
||||
assert.Equal(t, float64(account.ID), created["account_id"])
|
||||
assert.Equal(t, "Fin", created["name"])
|
||||
assert.Equal(t, "Support copilot", created["description"])
|
||||
assert.Equal(t, "GoChat", created["config"].(map[string]any)["product_name"])
|
||||
assistantID := uint(created["id"].(float64))
|
||||
|
||||
w = captainAssistantJSONRequest(t, router, http.MethodGet, basePath+"/", nil)
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
var listResp map[string]any
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &listResp))
|
||||
assert.Len(t, listResp["payload"], 1)
|
||||
assert.Equal(t, float64(1), listResp["meta"].(map[string]any)["total_count"])
|
||||
assert.Equal(t, float64(1), listResp["meta"].(map[string]any)["page"])
|
||||
|
||||
updateBody := map[string]any{"assistant": map[string]any{"name": "Fin Prime", "description": "Updated"}}
|
||||
w = captainAssistantJSONRequest(t, router, http.MethodPut, fmt.Sprintf("%s/%d", basePath, assistantID), updateBody)
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
var updated map[string]any
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &updated))
|
||||
assert.Equal(t, "Fin Prime", updated["name"])
|
||||
assert.Equal(t, "Updated", updated["description"])
|
||||
|
||||
w = captainAssistantJSONRequest(t, router, http.MethodGet, fmt.Sprintf("%s/%d", basePath, assistantID), nil)
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
|
||||
w = captainAssistantJSONRequest(t, router, http.MethodDelete, fmt.Sprintf("%s/%d", basePath, assistantID), nil)
|
||||
assert.Equal(t, http.StatusNoContent, w.Code)
|
||||
}
|
||||
|
||||
func TestCaptainAssistantHandler_AccountScopedShowAndInboxBinding(t *testing.T) {
|
||||
router, db := setupCaptainAssistantHandlerTest(t)
|
||||
account := seedCaptainAssistantAccount(t, db, "Account One")
|
||||
otherAccount := seedCaptainAssistantAccount(t, db, "Account Two")
|
||||
assistant := &model.CaptainAssistant{AccountID: account.ID, Name: "Fin", Description: "Support", Config: json.RawMessage(`{}`), Status: model.AssistantStatusActive}
|
||||
require.NoError(t, db.Create(assistant).Error)
|
||||
inbox := &model.Inbox{AccountID: account.ID, Name: "Primary", ChannelType: "web_widget"}
|
||||
require.NoError(t, db.Create(inbox).Error)
|
||||
otherInbox := &model.Inbox{AccountID: otherAccount.ID, Name: "Other", ChannelType: "web_widget"}
|
||||
require.NoError(t, db.Create(otherInbox).Error)
|
||||
|
||||
basePath := "/api/v1/accounts/" + strconv.FormatUint(uint64(account.ID), 10) + "/captain/assistants"
|
||||
otherBasePath := "/api/v1/accounts/" + strconv.FormatUint(uint64(otherAccount.ID), 10) + "/captain/assistants"
|
||||
|
||||
w := captainAssistantJSONRequest(t, router, http.MethodGet, fmt.Sprintf("%s/%d", otherBasePath, assistant.ID), nil)
|
||||
assert.Equal(t, http.StatusNotFound, w.Code)
|
||||
|
||||
w = captainAssistantJSONRequest(t, router, http.MethodGet, basePath+"/tools", nil)
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
var tools []map[string]any
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &tools))
|
||||
assert.Len(t, tools, 7)
|
||||
assert.Equal(t, "add_contact_note", tools[0]["id"])
|
||||
|
||||
bindBody := map[string]any{"inbox": map[string]any{"inbox_id": inbox.ID}}
|
||||
w = captainAssistantJSONRequest(t, router, http.MethodPost, fmt.Sprintf("%s/%d/inboxes", basePath, assistant.ID), bindBody)
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
var bound map[string]any
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &bound))
|
||||
assert.Equal(t, float64(inbox.ID), bound["id"])
|
||||
assert.NotContains(t, bound, "success")
|
||||
|
||||
w = captainAssistantJSONRequest(t, router, http.MethodGet, fmt.Sprintf("%s/%d/inboxes", basePath, assistant.ID), nil)
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
var inboxList map[string]any
|
||||
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &inboxList))
|
||||
assert.Len(t, inboxList["payload"], 1)
|
||||
|
||||
wrongBindBody := map[string]any{"inbox": map[string]any{"inbox_id": otherInbox.ID}}
|
||||
w = captainAssistantJSONRequest(t, router, http.MethodPost, fmt.Sprintf("%s/%d/inboxes", basePath, assistant.ID), wrongBindBody)
|
||||
assert.Equal(t, http.StatusNotFound, w.Code)
|
||||
|
||||
w = captainAssistantJSONRequest(t, router, http.MethodDelete, fmt.Sprintf("%s/%d/inboxes/%d", otherBasePath, assistant.ID, inbox.ID), nil)
|
||||
assert.Equal(t, http.StatusNotFound, w.Code)
|
||||
|
||||
w = captainAssistantJSONRequest(t, router, http.MethodDelete, fmt.Sprintf("%s/%d/inboxes/%d", basePath, assistant.ID, inbox.ID), nil)
|
||||
assert.Equal(t, http.StatusNoContent, w.Code)
|
||||
}
|
||||
@@ -73,7 +73,7 @@ type CaptainAssistant struct {
|
||||
AccountID uint `gorm:"index;not null" json:"account_id"`
|
||||
Name string `gorm:"size:255;not null" json:"name"`
|
||||
Description string `gorm:"size:1024" json:"description"`
|
||||
Config json.RawMessage `gorm:"type:jsonb;not null;default:'{}';serializer:json" json:"config"`
|
||||
Config json.RawMessage `gorm:"type:jsonb;not null;default:'{}';serializer:json" json:"config"`
|
||||
Guardrails json.RawMessage `gorm:"type:jsonb;serializer:json" json:"guardrails,omitempty"`
|
||||
ResponseGuidelines json.RawMessage `gorm:"type:jsonb;serializer:json" json:"response_guidelines,omitempty"`
|
||||
Status AssistantStatus `gorm:"size:50;default:active" json:"status"`
|
||||
@@ -92,9 +92,9 @@ func (CaptainAssistant) TableName() string { return "captain_assistants" }
|
||||
// Reference: Chatwoot Captain::Assistant default config values
|
||||
func DefaultAssistantConfig() map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"temperature": 0.7,
|
||||
"product_name": "",
|
||||
"feature_flags": map[string]bool{},
|
||||
"temperature": 0.7,
|
||||
"product_name": "",
|
||||
"feature_flags": map[string]bool{},
|
||||
"response_guidelines": "",
|
||||
}
|
||||
}
|
||||
@@ -287,15 +287,15 @@ func (CaptainInbox) TableName() string { return "captain_inboxes" }
|
||||
|
||||
type CaptainPreference struct {
|
||||
Base
|
||||
AccountID uint `gorm:"uniqueIndex;not null" json:"account_id"`
|
||||
Tone string `gorm:"size:50;default:professional" json:"tone"` // professional, friendly, casual, formal
|
||||
Language string `gorm:"size:10;default:en" json:"language"` // ISO 639-1 language code
|
||||
ResponseGuidelines string `gorm:"type:text" json:"response_guidelines,omitempty"` // free-form instructions for AI responses
|
||||
AutoLabelEnabled bool `gorm:"default:false" json:"auto_label_enabled"` // auto-apply label suggestions
|
||||
AutoFollowUpEnabled bool `gorm:"default:false" json:"auto_follow_up_enabled"` // auto-create follow-up tasks
|
||||
AutoReplyEnabled bool `gorm:"default:false" json:"auto_reply_enabled"` // auto-send assistant responses
|
||||
MaxResponseLength int `gorm:"default:500" json:"max_response_length"` // max characters in AI response
|
||||
CustomPromptSuffix string `gorm:"type:text" json:"custom_prompt_suffix,omitempty"` // appended to system prompts
|
||||
AccountID uint `gorm:"uniqueIndex;not null" json:"account_id"`
|
||||
Tone string `gorm:"size:50;default:professional" json:"tone"` // professional, friendly, casual, formal
|
||||
Language string `gorm:"size:10;default:en" json:"language"` // ISO 639-1 language code
|
||||
ResponseGuidelines string `gorm:"type:text" json:"response_guidelines,omitempty"` // free-form instructions for AI responses
|
||||
AutoLabelEnabled bool `gorm:"default:false" json:"auto_label_enabled"` // auto-apply label suggestions
|
||||
AutoFollowUpEnabled bool `gorm:"default:false" json:"auto_follow_up_enabled"` // auto-create follow-up tasks
|
||||
AutoReplyEnabled bool `gorm:"default:false" json:"auto_reply_enabled"` // auto-send assistant responses
|
||||
MaxResponseLength int `gorm:"default:500" json:"max_response_length"` // max characters in AI response
|
||||
CustomPromptSuffix string `gorm:"type:text" json:"custom_prompt_suffix,omitempty"` // appended to system prompts
|
||||
}
|
||||
|
||||
func (CaptainPreference) TableName() string { return "captain_preferences" }
|
||||
func (CaptainPreference) TableName() string { return "captain_preferences" }
|
||||
|
||||
@@ -28,6 +28,14 @@ func (r *CaptainAssistantRepo) GetByID(ctx context.Context, id uint) (*model.Cap
|
||||
return &assistant, nil
|
||||
}
|
||||
|
||||
func (r *CaptainAssistantRepo) GetByAccountAndID(ctx context.Context, accountID, id uint) (*model.CaptainAssistant, error) {
|
||||
var assistant model.CaptainAssistant
|
||||
if err := r.db.WithContext(ctx).Where("account_id = ? AND id = ?", accountID, id).First(&assistant).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &assistant, nil
|
||||
}
|
||||
|
||||
func (r *CaptainAssistantRepo) Update(ctx context.Context, assistant *model.CaptainAssistant) error {
|
||||
return r.db.WithContext(ctx).Save(assistant).Error
|
||||
}
|
||||
@@ -41,7 +49,7 @@ func (r *CaptainAssistantRepo) ListByAccount(ctx context.Context, accountID uint
|
||||
var count int64
|
||||
db := r.db.WithContext(ctx).Model(&model.CaptainAssistant{}).Where("account_id = ?", accountID)
|
||||
db.Count(&count)
|
||||
if err := db.Offset(offset).Limit(limit).Find(&assistants).Error; err != nil {
|
||||
if err := db.Order("created_at DESC").Offset(offset).Limit(limit).Find(&assistants).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return assistants, count, nil
|
||||
@@ -57,4 +65,4 @@ func (r *CaptainAssistantRepo) FindByInboxID(ctx context.Context, inboxID uint)
|
||||
return nil, err
|
||||
}
|
||||
return assistants, nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,6 +26,12 @@ func (r *CaptainInboxRepo) Delete(ctx context.Context, assistantID, inboxID uint
|
||||
Delete(&model.CaptainInbox{}).Error
|
||||
}
|
||||
|
||||
func (r *CaptainInboxRepo) DeleteByAccount(ctx context.Context, accountID, assistantID, inboxID uint) error {
|
||||
return r.db.WithContext(ctx).
|
||||
Where("account_id = ? AND captain_assistant_id = ? AND inbox_id = ?", accountID, assistantID, inboxID).
|
||||
Delete(&model.CaptainInbox{}).Error
|
||||
}
|
||||
|
||||
func (r *CaptainInboxRepo) ListByAssistant(ctx context.Context, assistantID uint) ([]model.CaptainInbox, error) {
|
||||
var inboxes []model.CaptainInbox
|
||||
if err := r.db.WithContext(ctx).Where("captain_assistant_id = ?", assistantID).Find(&inboxes).Error; err != nil {
|
||||
@@ -34,6 +40,26 @@ func (r *CaptainInboxRepo) ListByAssistant(ctx context.Context, assistantID uint
|
||||
return inboxes, nil
|
||||
}
|
||||
|
||||
func (r *CaptainInboxRepo) ListInboxesByAssistant(ctx context.Context, accountID, assistantID uint) ([]model.Inbox, error) {
|
||||
var inboxes []model.Inbox
|
||||
if err := r.db.WithContext(ctx).
|
||||
Joins("JOIN captain_inboxes ON captain_inboxes.inbox_id = inboxes.id").
|
||||
Where("captain_inboxes.account_id = ? AND captain_inboxes.captain_assistant_id = ?", accountID, assistantID).
|
||||
Order("inboxes.id DESC").
|
||||
Find(&inboxes).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return inboxes, nil
|
||||
}
|
||||
|
||||
func (r *CaptainInboxRepo) FindAccountInbox(ctx context.Context, accountID, inboxID uint) (*model.Inbox, error) {
|
||||
var inbox model.Inbox
|
||||
if err := r.db.WithContext(ctx).Where("account_id = ? AND id = ?", accountID, inboxID).First(&inbox).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &inbox, nil
|
||||
}
|
||||
|
||||
func (r *CaptainInboxRepo) FindByAssistantAndInbox(ctx context.Context, assistantID, inboxID uint) (*model.CaptainInbox, error) {
|
||||
var ci model.CaptainInbox
|
||||
if err := r.db.WithContext(ctx).Where("captain_assistant_id = ? AND inbox_id = ?", assistantID, inboxID).First(&ci).Error; err != nil {
|
||||
@@ -49,4 +75,4 @@ func (r *CaptainInboxRepo) FindByInboxID(ctx context.Context, inboxID uint) ([]m
|
||||
return nil, err
|
||||
}
|
||||
return inboxes, nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1141,16 +1141,15 @@ func registerV1Routes(g *gin.RouterGroup, h *Handlers) {
|
||||
{
|
||||
assistants.GET("/", h.CaptainAssistant.List)
|
||||
assistants.POST("/", h.CaptainAssistant.Create)
|
||||
assistants.GET("/tools", h.CaptainAssistant.Tools)
|
||||
assistants.GET("/:assistant_id", h.CaptainAssistant.Get)
|
||||
assistants.PUT("/:assistant_id", h.CaptainAssistant.Update)
|
||||
assistants.DELETE("/:assistant_id", h.CaptainAssistant.Delete)
|
||||
|
||||
// Inbox bindings
|
||||
assistants.GET("/:assistant_id/inboxes", h.CaptainAssistant.ListInboxes)
|
||||
assistants.POST("/:assistant_id/inboxes", h.CaptainAssistant.AssociateInbox)
|
||||
assistants.DELETE("/:assistant_id/inboxes/:inbox_id", h.CaptainAssistant.DissociateInbox)
|
||||
// Chatwoot member/collection routes
|
||||
assistants.GET("/:assistant_id/inboxes", h.CaptainAssistant.GetConfig)
|
||||
assistants.GET("/tools", h.CaptainAssistant.GetConfig)
|
||||
assistants.POST("/:assistant_id/playground", h.CaptainAssistant.GenerateResponse)
|
||||
|
||||
// Documents nested under assistant
|
||||
|
||||
@@ -63,6 +63,12 @@ type UpdateAssistantRequest struct {
|
||||
|
||||
// Create creates a new CaptainAssistant.
|
||||
func (s *CaptainAssistantService) Create(ctx context.Context, accountID uint, req *CreateAssistantRequest) (*model.CaptainAssistant, error) {
|
||||
if req.Name == "" {
|
||||
return nil, fmt.Errorf("name is required")
|
||||
}
|
||||
if req.Description == "" {
|
||||
return nil, fmt.Errorf("description is required")
|
||||
}
|
||||
config := req.Config
|
||||
if len(config) == 0 || string(config) == "null" {
|
||||
defaultCfg := model.DefaultAssistantConfig()
|
||||
@@ -90,9 +96,9 @@ func (s *CaptainAssistantService) Create(ctx context.Context, accountID uint, re
|
||||
return assistant, nil
|
||||
}
|
||||
|
||||
// Get retrieves an assistant by ID.
|
||||
func (s *CaptainAssistantService) Get(ctx context.Context, id uint) (*model.CaptainAssistant, error) {
|
||||
assistant, err := s.assistantRepo.GetByID(ctx, id)
|
||||
// Get retrieves an assistant by ID scoped to an account.
|
||||
func (s *CaptainAssistantService) Get(ctx context.Context, accountID, id uint) (*model.CaptainAssistant, error) {
|
||||
assistant, err := s.assistantRepo.GetByAccountAndID(ctx, accountID, id)
|
||||
if err != nil {
|
||||
applogger.L().Errorf("Get captain assistant: %v", err)
|
||||
return nil, fmt.Errorf("get assistant: %w", err)
|
||||
@@ -100,9 +106,9 @@ func (s *CaptainAssistantService) Get(ctx context.Context, id uint) (*model.Capt
|
||||
return assistant, nil
|
||||
}
|
||||
|
||||
// Update updates an existing assistant.
|
||||
func (s *CaptainAssistantService) Update(ctx context.Context, id uint, req *UpdateAssistantRequest) (*model.CaptainAssistant, error) {
|
||||
assistant, err := s.assistantRepo.GetByID(ctx, id)
|
||||
// Update updates an existing assistant scoped to an account.
|
||||
func (s *CaptainAssistantService) Update(ctx context.Context, accountID, id uint, req *UpdateAssistantRequest) (*model.CaptainAssistant, error) {
|
||||
assistant, err := s.assistantRepo.GetByAccountAndID(ctx, accountID, id)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("assistant not found: %w", err)
|
||||
}
|
||||
@@ -133,8 +139,11 @@ func (s *CaptainAssistantService) Update(ctx context.Context, id uint, req *Upda
|
||||
return assistant, nil
|
||||
}
|
||||
|
||||
// Delete deletes an assistant by ID.
|
||||
func (s *CaptainAssistantService) Delete(ctx context.Context, id uint) error {
|
||||
// Delete deletes an assistant by ID scoped to an account.
|
||||
func (s *CaptainAssistantService) Delete(ctx context.Context, accountID, id uint) error {
|
||||
if _, err := s.assistantRepo.GetByAccountAndID(ctx, accountID, id); err != nil {
|
||||
return fmt.Errorf("assistant not found: %w", err)
|
||||
}
|
||||
if err := s.assistantRepo.Delete(ctx, id); err != nil {
|
||||
applogger.L().Errorf("Delete captain assistant: %v", err)
|
||||
return fmt.Errorf("delete assistant: %w", err)
|
||||
@@ -182,14 +191,13 @@ func (s *CaptainAssistantService) SetConfig(ctx context.Context, id uint, cfg *m
|
||||
// --- Inbox Association ---
|
||||
|
||||
// AssociateInbox binds an assistant to an inbox.
|
||||
func (s *CaptainAssistantService) AssociateInbox(ctx context.Context, assistantID, inboxID, accountID uint) error {
|
||||
// Verify assistant exists and belongs to account
|
||||
assistant, err := s.assistantRepo.GetByID(ctx, assistantID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("assistant not found: %w", err)
|
||||
func (s *CaptainAssistantService) AssociateInbox(ctx context.Context, assistantID, inboxID, accountID uint) (*model.Inbox, error) {
|
||||
if _, err := s.assistantRepo.GetByAccountAndID(ctx, accountID, assistantID); err != nil {
|
||||
return nil, fmt.Errorf("assistant not found: %w", err)
|
||||
}
|
||||
if assistant.AccountID != accountID {
|
||||
return fmt.Errorf("assistant does not belong to account")
|
||||
inbox, err := s.inboxRepo.FindAccountInbox(ctx, accountID, inboxID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("inbox not found: %w", err)
|
||||
}
|
||||
|
||||
ci := &model.CaptainInbox{
|
||||
@@ -199,20 +207,47 @@ func (s *CaptainAssistantService) AssociateInbox(ctx context.Context, assistantI
|
||||
}
|
||||
if err := s.inboxRepo.Create(ctx, ci); err != nil {
|
||||
applogger.L().Errorf("AssociateInbox: %v", err)
|
||||
return fmt.Errorf("associate inbox: %w", err)
|
||||
return nil, fmt.Errorf("associate inbox: %w", err)
|
||||
}
|
||||
return nil
|
||||
return inbox, nil
|
||||
}
|
||||
|
||||
// DissociateInbox unbinds an assistant from an inbox.
|
||||
func (s *CaptainAssistantService) DissociateInbox(ctx context.Context, assistantID, inboxID uint) error {
|
||||
if err := s.inboxRepo.Delete(ctx, assistantID, inboxID); err != nil {
|
||||
func (s *CaptainAssistantService) DissociateInbox(ctx context.Context, accountID, assistantID, inboxID uint) error {
|
||||
if _, err := s.assistantRepo.GetByAccountAndID(ctx, accountID, assistantID); err != nil {
|
||||
return fmt.Errorf("assistant not found: %w", err)
|
||||
}
|
||||
if ci, err := s.inboxRepo.FindByAssistantAndInbox(ctx, assistantID, inboxID); err != nil {
|
||||
return fmt.Errorf("captain inbox not found: %w", err)
|
||||
} else if ci.AccountID != accountID {
|
||||
return fmt.Errorf("captain inbox not found")
|
||||
}
|
||||
if err := s.inboxRepo.DeleteByAccount(ctx, accountID, assistantID, inboxID); err != nil {
|
||||
applogger.L().Errorf("DissociateInbox: %v", err)
|
||||
return fmt.Errorf("dissociate inbox: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *CaptainAssistantService) ListInboxes(ctx context.Context, accountID, assistantID uint) ([]model.Inbox, error) {
|
||||
if _, err := s.assistantRepo.GetByAccountAndID(ctx, accountID, assistantID); err != nil {
|
||||
return nil, fmt.Errorf("assistant not found: %w", err)
|
||||
}
|
||||
return s.inboxRepo.ListInboxesByAssistant(ctx, accountID, assistantID)
|
||||
}
|
||||
|
||||
func (s *CaptainAssistantService) AvailableTools(ctx context.Context, accountID uint) []map[string]any {
|
||||
return []map[string]any{
|
||||
{"id": "add_contact_note", "title": "Add Contact Note", "description": "Add a note to a contact profile", "icon": "note-add"},
|
||||
{"id": "add_private_note", "title": "Add Private Note", "description": "Add a private note to a conversation (internal only)", "icon": "eye-off"},
|
||||
{"id": "update_priority", "title": "Update Priority", "description": "Update conversation priority level", "icon": "exclamation-triangle"},
|
||||
{"id": "add_label_to_conversation", "title": "Add Label to Conversation", "description": "Add a label to a conversation", "icon": "tag"},
|
||||
{"id": "faq_lookup", "title": "FAQ Lookup", "description": "Search FAQ responses using semantic similarity", "icon": "search"},
|
||||
{"id": "resolve_conversation", "title": "Resolve Conversation", "description": "Resolve a conversation when the issue has been addressed", "icon": "checkmark"},
|
||||
{"id": "handoff", "title": "Handoff to Human", "description": "Hand off the conversation to a human agent", "icon": "user-switch"},
|
||||
}
|
||||
}
|
||||
|
||||
// --- Document Management ---
|
||||
|
||||
// AddDocument creates a document linked to the assistant.
|
||||
@@ -290,4 +325,4 @@ func buildSystemPrompt(assistant *model.CaptainAssistant, cfg *model.AssistantCo
|
||||
prompt += fmt.Sprintf("\nGuardrails: %s", string(assistant.Guardrails))
|
||||
}
|
||||
return prompt
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user