feat: add agent management functionality

- Introduced a new package for managing custom agents, including CRUD operations for agent creation, retrieval, updating, and deletion.
- Implemented API endpoints for listing agents and retrieving agent placeholders.
- Added data structures for agent configuration and requests, enhancing the overall agent management capabilities.
- Enhanced the client with methods to interact with the new agent management features, improving user experience in managing agents.

These changes significantly expand the application's functionality for handling custom agents, providing users with a comprehensive toolset for agent management.
This commit is contained in:
wizardchen
2026-03-09 14:56:01 +08:00
committed by lyingbug
parent 125d3e5e4a
commit daa9ef500c
27 changed files with 5134 additions and 8 deletions
+206
View File
@@ -0,0 +1,206 @@
// Package client provides the implementation for interacting with the WeKnora API
// The Agent management interfaces are used to manage custom agents (CRUD operations)
package client
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
)
// Agent represents an agent entity
type Agent struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Avatar string `json:"avatar"`
IsBuiltin bool `json:"is_builtin"`
TenantID uint64 `json:"tenant_id"`
CreatedBy string `json:"created_by"`
Config *AgentConfig `json:"config"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// AgentConfig represents the configuration for an agent
type AgentConfig struct {
AgentMode string `json:"agent_mode"` // "quick-answer" or "smart-reasoning"
SystemPrompt string `json:"system_prompt,omitempty"`
ContextTemplate string `json:"context_template,omitempty"`
ModelID string `json:"model_id,omitempty"`
RerankModelID string `json:"rerank_model_id,omitempty"`
Temperature float64 `json:"temperature,omitempty"`
MaxCompletionTokens int `json:"max_completion_tokens,omitempty"`
MaxIterations int `json:"max_iterations,omitempty"`
AllowedTools []string `json:"allowed_tools,omitempty"`
ReflectionEnabled bool `json:"reflection_enabled,omitempty"`
MCPSelectionMode string `json:"mcp_selection_mode,omitempty"` // "all", "selected", "none"
MCPServices []string `json:"mcp_services,omitempty"`
KBSelectionMode string `json:"kb_selection_mode,omitempty"` // "all", "selected", "none"
KnowledgeBases []string `json:"knowledge_bases,omitempty"`
SupportedFileTypes []string `json:"supported_file_types,omitempty"`
FAQPriorityEnabled bool `json:"faq_priority_enabled,omitempty"`
FAQDirectAnswerThreshold float64 `json:"faq_direct_answer_threshold,omitempty"`
FAQScoreBoost float64 `json:"faq_score_boost,omitempty"`
WebSearchEnabled bool `json:"web_search_enabled,omitempty"`
WebSearchMaxResults int `json:"web_search_max_results,omitempty"`
MultiTurnEnabled bool `json:"multi_turn_enabled,omitempty"`
HistoryTurns int `json:"history_turns,omitempty"`
EmbeddingTopK int `json:"embedding_top_k,omitempty"`
KeywordThreshold float64 `json:"keyword_threshold,omitempty"`
VectorThreshold float64 `json:"vector_threshold,omitempty"`
RerankTopK int `json:"rerank_top_k,omitempty"`
RerankThreshold float64 `json:"rerank_threshold,omitempty"`
EnableQueryExpansion bool `json:"enable_query_expansion,omitempty"`
EnableRewrite bool `json:"enable_rewrite,omitempty"`
RewritePromptSystem string `json:"rewrite_prompt_system,omitempty"`
RewritePromptUser string `json:"rewrite_prompt_user,omitempty"`
FallbackStrategy string `json:"fallback_strategy,omitempty"` // "fixed" or "model"
FallbackResponse string `json:"fallback_response,omitempty"`
FallbackPrompt string `json:"fallback_prompt,omitempty"`
}
// CreateAgentRequest represents the request to create an agent
type CreateAgentRequest struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Avatar string `json:"avatar,omitempty"`
Config *AgentConfig `json:"config,omitempty"`
}
// UpdateAgentRequest represents the request to update an agent
type UpdateAgentRequest struct {
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
Avatar string `json:"avatar,omitempty"`
Config *AgentConfig `json:"config,omitempty"`
}
// AgentResponse represents the API response containing a single agent
type AgentResponse struct {
Success bool `json:"success"`
Data Agent `json:"data"`
}
// AgentListResponse represents the API response containing a list of agents
type AgentListResponse struct {
Success bool `json:"success"`
Data []Agent `json:"data"`
}
// AgentPlaceholdersResponse represents the API response for placeholder definitions
type AgentPlaceholdersResponse struct {
Success bool `json:"success"`
Data map[string]json.RawMessage `json:"data"`
}
// CreateAgent creates a new custom agent
func (c *Client) CreateAgent(ctx context.Context, request *CreateAgentRequest) (*Agent, error) {
resp, err := c.doRequest(ctx, http.MethodPost, "/api/v1/agents", request, nil)
if err != nil {
return nil, err
}
var response AgentResponse
if err := parseResponse(resp, &response); err != nil {
return nil, err
}
return &response.Data, nil
}
// ListAgents retrieves all agents for the current tenant
func (c *Client) ListAgents(ctx context.Context) ([]Agent, error) {
resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/agents", nil, nil)
if err != nil {
return nil, err
}
var response AgentListResponse
if err := parseResponse(resp, &response); err != nil {
return nil, err
}
return response.Data, nil
}
// GetAgent retrieves an agent by its ID
func (c *Client) GetAgent(ctx context.Context, agentID string) (*Agent, error) {
path := fmt.Sprintf("/api/v1/agents/%s", agentID)
resp, err := c.doRequest(ctx, http.MethodGet, path, nil, nil)
if err != nil {
return nil, err
}
var response AgentResponse
if err := parseResponse(resp, &response); err != nil {
return nil, err
}
return &response.Data, nil
}
// UpdateAgent updates an existing agent
func (c *Client) UpdateAgent(ctx context.Context, agentID string, request *UpdateAgentRequest) (*Agent, error) {
path := fmt.Sprintf("/api/v1/agents/%s", agentID)
resp, err := c.doRequest(ctx, http.MethodPut, path, request, nil)
if err != nil {
return nil, err
}
var response AgentResponse
if err := parseResponse(resp, &response); err != nil {
return nil, err
}
return &response.Data, nil
}
// DeleteAgent deletes a custom agent by its ID
func (c *Client) DeleteAgent(ctx context.Context, agentID string) error {
path := fmt.Sprintf("/api/v1/agents/%s", agentID)
resp, err := c.doRequest(ctx, http.MethodDelete, path, nil, nil)
if err != nil {
return err
}
var response struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
}
return parseResponse(resp, &response)
}
// CopyAgent creates a copy of an existing agent
func (c *Client) CopyAgent(ctx context.Context, agentID string) (*Agent, error) {
path := fmt.Sprintf("/api/v1/agents/%s/copy", agentID)
resp, err := c.doRequest(ctx, http.MethodPost, path, nil, nil)
if err != nil {
return nil, err
}
var response AgentResponse
if err := parseResponse(resp, &response); err != nil {
return nil, err
}
return &response.Data, nil
}
// GetAgentPlaceholders retrieves all available prompt placeholder definitions
func (c *Client) GetAgentPlaceholders(ctx context.Context) (map[string]json.RawMessage, error) {
resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/agents/placeholders", nil, nil)
if err != nil {
return nil, err
}
var response AgentPlaceholdersResponse
if err := parseResponse(resp, &response); err != nil {
return nil, err
}
return response.Data, nil
}
+33
View File
@@ -154,6 +154,39 @@ func (c *Client) DeleteChunk(ctx context.Context, knowledgeID string, chunkID st
return parseResponse(resp, &response)
}
// GetChunkByIDOnly retrieves a chunk by its ID without requiring knowledge ID
func (c *Client) GetChunkByIDOnly(ctx context.Context, chunkID string) (*Chunk, error) {
path := fmt.Sprintf("/api/v1/chunks/get-by-id/%s", chunkID)
resp, err := c.doRequest(ctx, http.MethodGet, path, nil, nil)
if err != nil {
return nil, err
}
var response ChunkResponse
if err := parseResponse(resp, &response); err != nil {
return nil, err
}
return &response.Data, nil
}
// DeleteGeneratedQuestion deletes a generated question from a chunk
func (c *Client) DeleteGeneratedQuestion(ctx context.Context, chunkID string, questionID string) error {
path := fmt.Sprintf("/api/v1/chunks/%s/delete-question", chunkID)
req := map[string]string{"question_id": questionID}
resp, err := c.doRequest(ctx, http.MethodDelete, path, req, nil)
if err != nil {
return err
}
var response struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
}
return parseResponse(resp, &response)
}
// DeleteChunksByKnowledgeID deletes all chunks under a knowledge document
// Batch deletes all chunks under the specified knowledge document
// Parameters:
+255
View File
@@ -0,0 +1,255 @@
package client
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
)
// InitializationConfig represents the initialization configuration for a knowledge base
type InitializationConfig struct {
ChatModelID string `json:"chat_model_id,omitempty"`
EmbeddingModelID string `json:"embedding_model_id,omitempty"`
RerankModelID string `json:"rerank_model_id,omitempty"`
MultimodalID string `json:"multimodal_id,omitempty"`
}
// OllamaModelInfo represents info about an Ollama model
type OllamaModelInfo struct {
Name string `json:"name"`
Size int64 `json:"size"`
ModifiedAt string `json:"modified_at"`
}
// DownloadTask represents an Ollama model download task
type DownloadTask struct {
ID string `json:"id"`
ModelName string `json:"modelName"`
Status string `json:"status"`
Progress float64 `json:"progress"`
Message string `json:"message"`
StartTime time.Time `json:"startTime"`
EndTime *time.Time `json:"endTime,omitempty"`
}
// ModelCheckResult represents the result of checking a remote model
type ModelCheckResult struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
}
// GetInitializationConfig gets the current initialization config for a knowledge base
func (c *Client) GetInitializationConfig(ctx context.Context, kbID string) (*InitializationConfig, error) {
resp, err := c.doRequest(ctx, http.MethodGet, fmt.Sprintf("/api/v1/initialization/config/%s", kbID), nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data *InitializationConfig `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// InitializeByKB initializes a knowledge base with model configuration
func (c *Client) InitializeByKB(ctx context.Context, kbID string, config *InitializationConfig) error {
resp, err := c.doRequest(ctx, http.MethodPost, fmt.Sprintf("/api/v1/initialization/initialize/%s", kbID), config, nil)
if err != nil {
return err
}
return parseResponse(resp, nil)
}
// UpdateKBConfig updates the model configuration for a knowledge base
func (c *Client) UpdateKBConfig(ctx context.Context, kbID string, config *InitializationConfig) error {
resp, err := c.doRequest(ctx, http.MethodPut, fmt.Sprintf("/api/v1/initialization/config/%s", kbID), config, nil)
if err != nil {
return err
}
return parseResponse(resp, nil)
}
// CheckOllamaStatus checks if Ollama is running and accessible
func (c *Client) CheckOllamaStatus(ctx context.Context) (bool, error) {
resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/initialization/ollama/status", nil, nil)
if err != nil {
return false, err
}
var result struct {
Success bool `json:"success"`
Data struct {
Available bool `json:"available"`
} `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return false, err
}
return result.Data.Available, nil
}
// ListOllamaModels lists all locally available Ollama models
func (c *Client) ListOllamaModels(ctx context.Context) ([]OllamaModelInfo, error) {
resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/initialization/ollama/models", nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data []OllamaModelInfo `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// CheckOllamaModels checks if specific Ollama models are available
func (c *Client) CheckOllamaModels(ctx context.Context, models []string) (map[string]bool, error) {
req := map[string][]string{"models": models}
resp, err := c.doRequest(ctx, http.MethodPost, "/api/v1/initialization/ollama/models/check", req, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data map[string]bool `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// DownloadOllamaModel starts downloading an Ollama model
func (c *Client) DownloadOllamaModel(ctx context.Context, modelName string) (*DownloadTask, error) {
req := map[string]string{"model": modelName}
resp, err := c.doRequest(ctx, http.MethodPost, "/api/v1/initialization/ollama/models/download", req, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data *DownloadTask `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// GetOllamaDownloadProgress gets the download progress of an Ollama model
func (c *Client) GetOllamaDownloadProgress(ctx context.Context, taskID string) (*DownloadTask, error) {
resp, err := c.doRequest(ctx, http.MethodGet, fmt.Sprintf("/api/v1/initialization/ollama/download/progress/%s", taskID), nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data *DownloadTask `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// ListOllamaDownloadTasks lists all Ollama download tasks
func (c *Client) ListOllamaDownloadTasks(ctx context.Context) ([]*DownloadTask, error) {
resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/initialization/ollama/download/tasks", nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data []*DownloadTask `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// CheckRemoteModel checks if a remote model API is accessible
func (c *Client) CheckRemoteModel(ctx context.Context, params map[string]string) (*ModelCheckResult, error) {
resp, err := c.doRequest(ctx, http.MethodPost, "/api/v1/initialization/remote/check", params, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data *ModelCheckResult `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// TestEmbeddingModel tests an embedding model
func (c *Client) TestEmbeddingModel(ctx context.Context, params map[string]string) (*ModelCheckResult, error) {
resp, err := c.doRequest(ctx, http.MethodPost, "/api/v1/initialization/embedding/test", params, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data *ModelCheckResult `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// CheckRerankModel checks if a rerank model is accessible
func (c *Client) CheckRerankModel(ctx context.Context, params map[string]string) (*ModelCheckResult, error) {
resp, err := c.doRequest(ctx, http.MethodPost, "/api/v1/initialization/rerank/check", params, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data *ModelCheckResult `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// TestMultimodalFunction tests multimodal model functionality
func (c *Client) TestMultimodalFunction(ctx context.Context, params map[string]string) (*ModelCheckResult, error) {
resp, err := c.doRequest(ctx, http.MethodPost, "/api/v1/initialization/multimodal/test", params, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data *ModelCheckResult `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// ExtractTextRelations extracts text relations for knowledge graph
func (c *Client) ExtractTextRelations(ctx context.Context, params any) (json.RawMessage, error) {
resp, err := c.doRequest(ctx, http.MethodPost, "/api/v1/initialization/extract/text-relation", params, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data json.RawMessage `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
+174
View File
@@ -432,3 +432,177 @@ func (c *Client) UpdateImageInfo(ctx context.Context,
return parseResponse(resp, &response)
}
// CreateManualKnowledgeRequest contains the parameters for creating a manual Markdown knowledge entry.
type CreateManualKnowledgeRequest struct {
Title string `json:"title"`
Content string `json:"content"`
TagID string `json:"tag_id,omitempty"`
}
// UpdateManualKnowledgeRequest contains the parameters for updating a manual Markdown knowledge entry.
type UpdateManualKnowledgeRequest struct {
Title string `json:"title,omitempty"`
Content string `json:"content,omitempty"`
}
// BatchUpdateKnowledgeTagsRequest contains the mapping of knowledge IDs to tag IDs.
type BatchUpdateKnowledgeTagsRequest struct {
Updates map[string]*string `json:"updates"` // knowledge_id -> tag_id (nil to clear)
}
// CreateManualKnowledge creates a knowledge entry from manual Markdown content.
func (c *Client) CreateManualKnowledge(ctx context.Context, knowledgeBaseID string, request *CreateManualKnowledgeRequest) (*Knowledge, error) {
path := fmt.Sprintf("/api/v1/knowledge-bases/%s/knowledge/manual", knowledgeBaseID)
resp, err := c.doRequest(ctx, http.MethodPost, path, request, nil)
if err != nil {
return nil, err
}
var response KnowledgeResponse
if err := parseResponse(resp, &response); err != nil {
return nil, err
}
return &response.Data, nil
}
// UpdateManualKnowledge updates a manual Markdown knowledge entry.
func (c *Client) UpdateManualKnowledge(ctx context.Context, knowledgeID string, request *UpdateManualKnowledgeRequest) (*Knowledge, error) {
path := fmt.Sprintf("/api/v1/knowledge/manual/%s", knowledgeID)
resp, err := c.doRequest(ctx, http.MethodPut, path, request, nil)
if err != nil {
return nil, err
}
var response KnowledgeResponse
if err := parseResponse(resp, &response); err != nil {
return nil, err
}
return &response.Data, nil
}
// FilterKnowledgeResponse represents the response from filter knowledge API
type FilterKnowledgeResponse struct {
Success bool `json:"success"`
Data []Knowledge `json:"data"`
HasMore bool `json:"has_more"`
}
// FilterKnowledge searches/filters knowledge entries across knowledge bases
func (c *Client) FilterKnowledge(ctx context.Context, keyword string, offset, limit int, fileTypes []string, agentID string) ([]Knowledge, bool, error) {
queryParams := url.Values{}
if keyword != "" {
queryParams.Set("keyword", keyword)
}
queryParams.Set("offset", strconv.Itoa(offset))
queryParams.Set("limit", strconv.Itoa(limit))
if len(fileTypes) > 0 {
for _, ft := range fileTypes {
queryParams.Add("file_types", ft)
}
}
if agentID != "" {
queryParams.Set("agent_id", agentID)
}
resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/knowledge/search", nil, queryParams)
if err != nil {
return nil, false, err
}
var response FilterKnowledgeResponse
if err := parseResponse(resp, &response); err != nil {
return nil, false, err
}
return response.Data, response.HasMore, nil
}
// MoveKnowledgeRequest contains the parameters for moving knowledge between KBs
type MoveKnowledgeRequest struct {
KnowledgeIDs []string `json:"knowledge_ids"`
SourceKBID string `json:"source_kb_id"`
TargetKBID string `json:"target_kb_id"`
Mode string `json:"mode"` // "reuse_vectors" or "reparse"
}
// MoveKnowledgeResponse represents the response from move knowledge API
type MoveKnowledgeResponse struct {
TaskID string `json:"task_id"`
SourceKBID string `json:"source_kb_id"`
TargetKBID string `json:"target_kb_id"`
KnowledgeCount int `json:"knowledge_count"`
Message string `json:"message"`
}
// MoveKnowledge moves knowledge items from one knowledge base to another (async task)
func (c *Client) MoveKnowledge(ctx context.Context, req *MoveKnowledgeRequest) (*MoveKnowledgeResponse, error) {
resp, err := c.doRequest(ctx, http.MethodPost, "/api/v1/knowledge/move", req, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data *MoveKnowledgeResponse `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// KnowledgeMoveProgress represents the progress of a knowledge move task
type KnowledgeMoveProgress struct {
TaskID string `json:"task_id"`
Status string `json:"status"`
Progress int `json:"progress"`
Total int `json:"total"`
Processed int `json:"processed"`
Message string `json:"message"`
Error string `json:"error,omitempty"`
}
// GetKnowledgeMoveProgress gets the progress of a knowledge move task
func (c *Client) GetKnowledgeMoveProgress(ctx context.Context, taskID string) (*KnowledgeMoveProgress, error) {
path := fmt.Sprintf("/api/v1/knowledge/move/progress/%s", taskID)
resp, err := c.doRequest(ctx, http.MethodGet, path, nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data *KnowledgeMoveProgress `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// PreviewKnowledgeFile returns the file content for inline preview.
// The caller is responsible for reading and closing the response body.
func (c *Client) PreviewKnowledgeFile(ctx context.Context, knowledgeID string) (*http.Response, error) {
path := fmt.Sprintf("/api/v1/knowledge/%s/preview", knowledgeID)
return c.doRequest(ctx, http.MethodGet, path, nil, nil)
}
// BatchUpdateKnowledgeTags batch updates knowledge tags.
// The updates map contains knowledge_id -> tag_id mappings. Set tag_id to nil to clear the tag.
func (c *Client) BatchUpdateKnowledgeTags(ctx context.Context, updates map[string]*string) error {
request := &BatchUpdateKnowledgeTagsRequest{Updates: updates}
resp, err := c.doRequest(ctx, http.MethodPut, "/api/v1/knowledge/tags", request, nil)
if err != nil {
return err
}
var batchResponse struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
}
return parseResponse(resp, &batchResponse)
}
+40
View File
@@ -311,6 +311,46 @@ func (c *Client) HybridSearch(ctx context.Context, knowledgeBaseID string, param
return response.Data, nil
}
// TogglePinKnowledgeBase toggles the pin status of a knowledge base
func (c *Client) TogglePinKnowledgeBase(ctx context.Context, knowledgeBaseID string) (*KnowledgeBase, error) {
path := fmt.Sprintf("/api/v1/knowledge-bases/%s/pin", knowledgeBaseID)
resp, err := c.doRequest(ctx, http.MethodPost, path, nil, nil)
if err != nil {
return nil, err
}
var response KnowledgeBaseResponse
if err := parseResponse(resp, &response); err != nil {
return nil, err
}
return &response.Data, nil
}
// MoveTarget represents a knowledge base that can receive moved knowledge
type MoveTarget struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
Description string `json:"description"`
}
// ListMoveTargets lists knowledge bases eligible as move targets for the given source KB
func (c *Client) ListMoveTargets(ctx context.Context, knowledgeBaseID string) ([]KnowledgeBase, error) {
path := fmt.Sprintf("/api/v1/knowledge-bases/%s/move-targets", knowledgeBaseID)
resp, err := c.doRequest(ctx, http.MethodGet, path, nil, nil)
if err != nil {
return nil, err
}
var response KnowledgeBaseListResponse
if err := parseResponse(resp, &response); err != nil {
return nil, err
}
return response.Data, nil
}
// CopyKnowledgeBase copies a knowledge base asynchronously and returns task info
func (c *Client) CopyKnowledgeBase(ctx context.Context, request *CopyKnowledgeBaseRequest) (*CopyKnowledgeBaseResponse, error) {
path := "/api/v1/knowledge-bases/copy"
+207
View File
@@ -0,0 +1,207 @@
package client
import (
"context"
"encoding/json"
"fmt"
"net/http"
)
// MCPTransportType represents the transport type for MCP service
type MCPTransportType string
const (
MCPTransportSSE MCPTransportType = "sse"
MCPTransportHTTPStreamable MCPTransportType = "http-streamable"
MCPTransportStdio MCPTransportType = "stdio"
)
// MCPService represents an MCP service configuration
type MCPService struct {
ID string `json:"id"`
TenantID uint64 `json:"tenant_id"`
Name string `json:"name"`
Description string `json:"description"`
Enabled bool `json:"enabled"`
TransportType MCPTransportType `json:"transport_type"`
URL *string `json:"url,omitempty"`
Headers map[string]string `json:"headers"`
AuthConfig *MCPAuthConfig `json:"auth_config"`
AdvancedConfig *MCPAdvancedConfig `json:"advanced_config"`
StdioConfig *MCPStdioConfig `json:"stdio_config,omitempty"`
EnvVars map[string]string `json:"env_vars,omitempty"`
IsBuiltin bool `json:"is_builtin"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
// MCPAuthConfig represents authentication configuration for MCP service
type MCPAuthConfig struct {
APIKey string `json:"api_key,omitempty"`
Token string `json:"token,omitempty"`
CustomHeaders map[string]string `json:"custom_headers,omitempty"`
}
// MCPAdvancedConfig represents advanced configuration for MCP service
type MCPAdvancedConfig struct {
Timeout int `json:"timeout"`
RetryCount int `json:"retry_count"`
RetryDelay int `json:"retry_delay"`
}
// MCPStdioConfig represents stdio transport configuration
type MCPStdioConfig struct {
Command string `json:"command"`
Args []string `json:"args"`
}
// MCPTool represents a tool exposed by an MCP service
type MCPTool struct {
Name string `json:"name"`
Description string `json:"description"`
InputSchema json.RawMessage `json:"inputSchema"`
}
// MCPResource represents a resource exposed by an MCP service
type MCPResource struct {
URI string `json:"uri"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
MimeType string `json:"mimeType,omitempty"`
}
// MCPTestResult represents the result of testing an MCP service connection
type MCPTestResult struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
Tools []*MCPTool `json:"tools,omitempty"`
Resources []*MCPResource `json:"resources,omitempty"`
}
// CreateMCPService creates a new MCP service
func (c *Client) CreateMCPService(ctx context.Context, service *MCPService) (*MCPService, error) {
resp, err := c.doRequest(ctx, http.MethodPost, "/api/v1/mcp-services", service, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data *MCPService `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// ListMCPServices lists all MCP services for the current tenant
func (c *Client) ListMCPServices(ctx context.Context) ([]*MCPService, error) {
resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/mcp-services", nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data []*MCPService `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// GetMCPService gets an MCP service by ID
func (c *Client) GetMCPService(ctx context.Context, serviceID string) (*MCPService, error) {
resp, err := c.doRequest(ctx, http.MethodGet, fmt.Sprintf("/api/v1/mcp-services/%s", serviceID), nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data *MCPService `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// UpdateMCPService updates an MCP service
func (c *Client) UpdateMCPService(ctx context.Context, serviceID string, updates map[string]interface{}) (*MCPService, error) {
resp, err := c.doRequest(ctx, http.MethodPut, fmt.Sprintf("/api/v1/mcp-services/%s", serviceID), updates, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data *MCPService `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// DeleteMCPService deletes an MCP service
func (c *Client) DeleteMCPService(ctx context.Context, serviceID string) error {
resp, err := c.doRequest(ctx, http.MethodDelete, fmt.Sprintf("/api/v1/mcp-services/%s", serviceID), nil, nil)
if err != nil {
return err
}
return parseResponse(resp, nil)
}
// TestMCPService tests an MCP service connection
func (c *Client) TestMCPService(ctx context.Context, serviceID string) (*MCPTestResult, error) {
resp, err := c.doRequest(ctx, http.MethodPost, fmt.Sprintf("/api/v1/mcp-services/%s/test", serviceID), nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data *MCPTestResult `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// GetMCPServiceTools gets the tools provided by an MCP service
func (c *Client) GetMCPServiceTools(ctx context.Context, serviceID string) ([]*MCPTool, error) {
resp, err := c.doRequest(ctx, http.MethodGet, fmt.Sprintf("/api/v1/mcp-services/%s/tools", serviceID), nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data []*MCPTool `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// GetMCPServiceResources gets the resources provided by an MCP service
func (c *Client) GetMCPServiceResources(ctx context.Context, serviceID string) ([]*MCPResource, error) {
resp, err := c.doRequest(ctx, http.MethodGet, fmt.Sprintf("/api/v1/mcp-services/%s/resources", serviceID), nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data []*MCPResource `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
+70
View File
@@ -102,6 +102,76 @@ func (c *Client) GetMessagesBefore(
return c.LoadMessages(ctx, sessionID, limit, &beforeTime)
}
// SearchMessagesRequest defines the request structure for searching messages
type SearchMessagesRequest struct {
Query string `json:"query"`
Mode string `json:"mode"`
Limit int `json:"limit"`
SessionIDs []string `json:"session_ids,omitempty"`
}
// MessageSearchGroupItem represents a grouped search result item
type MessageSearchGroupItem struct {
RequestID string `json:"request_id"`
SessionID string `json:"session_id"`
SessionTitle string `json:"session_title"`
QueryContent string `json:"query_content"`
AnswerContent string `json:"answer_content"`
Score float64 `json:"score"`
MatchType string `json:"match_type"`
CreatedAt time.Time `json:"created_at"`
}
// MessageSearchResult represents the result of a message search
type MessageSearchResult struct {
Items []*MessageSearchGroupItem `json:"items"`
Total int `json:"total"`
}
// ChatHistoryKBStats represents statistics about the chat history knowledge base
type ChatHistoryKBStats struct {
Enabled bool `json:"enabled"`
EmbeddingModelID string `json:"embedding_model_id,omitempty"`
KnowledgeBaseID string `json:"knowledge_base_id,omitempty"`
KnowledgeBaseName string `json:"knowledge_base_name,omitempty"`
IndexedMessageCount int64 `json:"indexed_message_count"`
HasIndexedMessages bool `json:"has_indexed_messages"`
}
// SearchMessages searches chat history messages
func (c *Client) SearchMessages(ctx context.Context, req *SearchMessagesRequest) (*MessageSearchResult, error) {
resp, err := c.doRequest(ctx, http.MethodPost, "/api/v1/messages/search", req, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data *MessageSearchResult `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// GetChatHistoryKBStats gets chat history knowledge base statistics
func (c *Client) GetChatHistoryKBStats(ctx context.Context) (*ChatHistoryKBStats, error) {
resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/messages/chat-history-stats", nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data *ChatHistoryKBStats `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// DeleteMessage deletes a message
func (c *Client) DeleteMessage(ctx context.Context, sessionID string, messageID string) error {
path := fmt.Sprintf("/api/v1/messages/%s/%s", sessionID, messageID)
+38
View File
@@ -7,6 +7,7 @@ import (
"context"
"fmt"
"net/http"
"net/url"
)
// ModelType model type
@@ -153,3 +154,40 @@ func (c *Client) DeleteModel(ctx context.Context, modelID string) error {
return parseResponse(resp, &response)
}
// ModelProvider represents a model provider with its supported types and default URLs
type ModelProvider struct {
Value string `json:"value"`
Label string `json:"label"`
Description string `json:"description"`
DefaultURLs map[string]string `json:"defaultUrls"`
ModelTypes []string `json:"modelTypes"`
}
// ModelProviderListResponse represents the API response for listing model providers
type ModelProviderListResponse struct {
Success bool `json:"success"`
Data []ModelProvider `json:"data"`
}
// ListModelProviders retrieves the list of supported model providers.
// modelType is optional and can be used to filter by type: "chat", "embedding", "rerank", "vllm".
func (c *Client) ListModelProviders(ctx context.Context, modelType string) ([]ModelProvider, error) {
var queryParams url.Values
if modelType != "" {
queryParams = url.Values{}
queryParams.Add("model_type", modelType)
}
resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/models/providers", nil, queryParams)
if err != nil {
return nil, err
}
var response ModelProviderListResponse
if err := parseResponse(resp, &response); err != nil {
return nil, err
}
return response.Data, nil
}
+630
View File
@@ -0,0 +1,630 @@
package client
import (
"context"
"fmt"
"net/http"
"net/url"
"time"
)
// Organization represents a collaboration organization
type Organization struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Avatar string `json:"avatar,omitempty"`
OwnerID string `json:"owner_id"`
InviteCode string `json:"invite_code,omitempty"`
InviteCodeExpiresAt *time.Time `json:"invite_code_expires_at,omitempty"`
InviteCodeValidityDays int `json:"invite_code_validity_days"`
RequireApproval bool `json:"require_approval"`
Searchable bool `json:"searchable"`
MemberLimit int `json:"member_limit"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// OrganizationResponse represents an organization in API responses (with counts)
type OrganizationResponse struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Avatar string `json:"avatar,omitempty"`
OwnerID string `json:"owner_id"`
InviteCode string `json:"invite_code,omitempty"`
InviteCodeExpiresAt *time.Time `json:"invite_code_expires_at,omitempty"`
InviteCodeValidityDays int `json:"invite_code_validity_days"`
RequireApproval bool `json:"require_approval"`
Searchable bool `json:"searchable"`
MemberLimit int `json:"member_limit"`
MemberCount int `json:"member_count"`
ShareCount int `json:"share_count"`
AgentShareCount int `json:"agent_share_count"`
PendingJoinRequestCount int `json:"pending_join_request_count"`
IsOwner bool `json:"is_owner"`
MyRole string `json:"my_role,omitempty"`
HasPendingUpgrade bool `json:"has_pending_upgrade"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// CreateOrganizationRequest represents a request to create an organization
type CreateOrganizationRequest struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Avatar string `json:"avatar,omitempty"`
InviteCodeValidityDays *int `json:"invite_code_validity_days,omitempty"`
MemberLimit *int `json:"member_limit,omitempty"`
}
// UpdateOrganizationRequest represents a request to update an organization
type UpdateOrganizationRequest struct {
Name *string `json:"name,omitempty"`
Description *string `json:"description,omitempty"`
Avatar *string `json:"avatar,omitempty"`
RequireApproval *bool `json:"require_approval,omitempty"`
Searchable *bool `json:"searchable,omitempty"`
InviteCodeValidityDays *int `json:"invite_code_validity_days,omitempty"`
MemberLimit *int `json:"member_limit,omitempty"`
}
// OrganizationMemberResponse represents a member in API responses
type OrganizationMemberResponse struct {
ID string `json:"id"`
UserID string `json:"user_id"`
Username string `json:"username"`
Email string `json:"email"`
Avatar string `json:"avatar"`
Role string `json:"role"`
TenantID uint64 `json:"tenant_id"`
JoinedAt time.Time `json:"joined_at"`
}
// KnowledgeBaseShareResponse represents a KB share record in API responses
type KnowledgeBaseShareResponse struct {
ID string `json:"id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
KnowledgeBaseName string `json:"knowledge_base_name"`
OrganizationID string `json:"organization_id"`
OrganizationName string `json:"organization_name"`
SharedByUserID string `json:"shared_by_user_id"`
SharedByUsername string `json:"shared_by_username"`
SourceTenantID uint64 `json:"source_tenant_id"`
Permission string `json:"permission"`
MyRoleInOrg string `json:"my_role_in_org"`
MyPermission string `json:"my_permission"`
CreatedAt time.Time `json:"created_at"`
}
// AgentShareResponse represents an agent share record in API responses
type AgentShareResponse struct {
ID string `json:"id"`
AgentID string `json:"agent_id"`
AgentName string `json:"agent_name"`
OrganizationID string `json:"organization_id"`
OrganizationName string `json:"organization_name"`
SharedByUserID string `json:"shared_by_user_id"`
SharedByUsername string `json:"shared_by_username"`
SourceTenantID uint64 `json:"source_tenant_id"`
Permission string `json:"permission"`
CreatedAt time.Time `json:"created_at"`
}
// JoinRequestResponse represents a join request in API responses
type JoinRequestResponse struct {
ID string `json:"id"`
UserID string `json:"user_id"`
Username string `json:"username"`
Email string `json:"email"`
Message string `json:"message"`
RequestType string `json:"request_type"`
PrevRole string `json:"prev_role"`
RequestedRole string `json:"requested_role"`
Status string `json:"status"`
CreatedAt time.Time `json:"created_at"`
ReviewedAt *time.Time `json:"reviewed_at,omitempty"`
}
// SharedKnowledgeBaseInfo represents a shared knowledge base
type SharedKnowledgeBaseInfo struct {
ShareID string `json:"share_id"`
OrganizationID string `json:"organization_id"`
OrgName string `json:"org_name"`
Permission string `json:"permission"`
SourceTenantID uint64 `json:"source_tenant_id"`
SharedAt time.Time `json:"shared_at"`
}
// SharedAgentInfo represents a shared agent
type SharedAgentInfo struct {
ShareID string `json:"share_id"`
OrganizationID string `json:"organization_id"`
OrgName string `json:"org_name"`
Permission string `json:"permission"`
SourceTenantID uint64 `json:"source_tenant_id"`
SharedAt time.Time `json:"shared_at"`
}
// --- Organization CRUD ---
// CreateOrganization creates a new organization
func (c *Client) CreateOrganization(ctx context.Context, req *CreateOrganizationRequest) (*OrganizationResponse, error) {
resp, err := c.doRequest(ctx, http.MethodPost, "/api/v1/organizations", req, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data *OrganizationResponse `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// ListMyOrganizations lists organizations the current user belongs to
func (c *Client) ListMyOrganizations(ctx context.Context) ([]OrganizationResponse, error) {
resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/organizations", nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data struct {
Organizations []OrganizationResponse `json:"organizations"`
} `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data.Organizations, nil
}
// GetOrganization gets an organization by ID
func (c *Client) GetOrganization(ctx context.Context, orgID string) (*OrganizationResponse, error) {
resp, err := c.doRequest(ctx, http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s", orgID), nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data *OrganizationResponse `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// UpdateOrganization updates an organization
func (c *Client) UpdateOrganization(ctx context.Context, orgID string, req *UpdateOrganizationRequest) (*OrganizationResponse, error) {
resp, err := c.doRequest(ctx, http.MethodPut, fmt.Sprintf("/api/v1/organizations/%s", orgID), req, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data *OrganizationResponse `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// DeleteOrganization deletes an organization
func (c *Client) DeleteOrganization(ctx context.Context, orgID string) error {
resp, err := c.doRequest(ctx, http.MethodDelete, fmt.Sprintf("/api/v1/organizations/%s", orgID), nil, nil)
if err != nil {
return err
}
return parseResponse(resp, nil)
}
// --- Organization membership ---
// JoinOrganizationByInviteCode joins an organization using an invite code
func (c *Client) JoinOrganizationByInviteCode(ctx context.Context, inviteCode string) error {
req := map[string]string{"invite_code": inviteCode}
resp, err := c.doRequest(ctx, http.MethodPost, "/api/v1/organizations/join", req, nil)
if err != nil {
return err
}
return parseResponse(resp, nil)
}
// SubmitJoinRequest submits a join request for organizations that require approval
func (c *Client) SubmitJoinRequest(ctx context.Context, inviteCode, message, role string) error {
req := map[string]string{
"invite_code": inviteCode,
"message": message,
"role": role,
}
resp, err := c.doRequest(ctx, http.MethodPost, "/api/v1/organizations/join-request", req, nil)
if err != nil {
return err
}
return parseResponse(resp, nil)
}
// SearchOrganizations searches for discoverable organizations
func (c *Client) SearchOrganizations(ctx context.Context, keyword string, page, pageSize int) ([]OrganizationResponse, error) {
q := url.Values{}
if keyword != "" {
q.Set("keyword", keyword)
}
if page > 0 {
q.Set("page", fmt.Sprintf("%d", page))
}
if pageSize > 0 {
q.Set("page_size", fmt.Sprintf("%d", pageSize))
}
resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/organizations/search", nil, q)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data struct {
Organizations []OrganizationResponse `json:"organizations"`
} `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data.Organizations, nil
}
// JoinByOrganizationID joins a searchable organization by its ID
func (c *Client) JoinByOrganizationID(ctx context.Context, orgID, message, role string) error {
req := map[string]string{
"organization_id": orgID,
"message": message,
"role": role,
}
resp, err := c.doRequest(ctx, http.MethodPost, "/api/v1/organizations/join-by-id", req, nil)
if err != nil {
return err
}
return parseResponse(resp, nil)
}
// PreviewOrganizationByInviteCode previews an organization before joining
func (c *Client) PreviewOrganizationByInviteCode(ctx context.Context, code string) (*OrganizationResponse, error) {
resp, err := c.doRequest(ctx, http.MethodGet, fmt.Sprintf("/api/v1/organizations/preview/%s", code), nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data *OrganizationResponse `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// LeaveOrganization leaves an organization
func (c *Client) LeaveOrganization(ctx context.Context, orgID string) error {
resp, err := c.doRequest(ctx, http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/leave", orgID), nil, nil)
if err != nil {
return err
}
return parseResponse(resp, nil)
}
// RequestRoleUpgrade requests a role upgrade in an organization
func (c *Client) RequestRoleUpgrade(ctx context.Context, orgID, requestedRole, message string) error {
req := map[string]string{
"requested_role": requestedRole,
"message": message,
}
resp, err := c.doRequest(ctx, http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/request-upgrade", orgID), req, nil)
if err != nil {
return err
}
return parseResponse(resp, nil)
}
// GenerateInviteCode generates a new invite code for an organization
func (c *Client) GenerateInviteCode(ctx context.Context, orgID string) (string, error) {
resp, err := c.doRequest(ctx, http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/invite-code", orgID), nil, nil)
if err != nil {
return "", err
}
var result struct {
Success bool `json:"success"`
Data struct {
InviteCode string `json:"invite_code"`
} `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return "", err
}
return result.Data.InviteCode, nil
}
// SearchUsersForInvite searches users to invite into an organization (admin only)
func (c *Client) SearchUsersForInvite(ctx context.Context, orgID, keyword string) ([]UserInfo, error) {
q := url.Values{}
if keyword != "" {
q.Set("keyword", keyword)
}
resp, err := c.doRequest(ctx, http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s/search-users", orgID), nil, q)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data []UserInfo `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// InviteMember directly invites a user to an organization (admin only)
func (c *Client) InviteMember(ctx context.Context, orgID, userID, role string) error {
req := map[string]string{
"user_id": userID,
"role": role,
}
resp, err := c.doRequest(ctx, http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/invite", orgID), req, nil)
if err != nil {
return err
}
return parseResponse(resp, nil)
}
// ListMembers lists members of an organization
func (c *Client) ListOrgMembers(ctx context.Context, orgID string) ([]OrganizationMemberResponse, error) {
resp, err := c.doRequest(ctx, http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s/members", orgID), nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data struct {
Members []OrganizationMemberResponse `json:"members"`
} `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data.Members, nil
}
// UpdateMemberRole updates a member's role in an organization
func (c *Client) UpdateMemberRole(ctx context.Context, orgID, userID, role string) error {
req := map[string]string{"role": role}
resp, err := c.doRequest(ctx, http.MethodPut, fmt.Sprintf("/api/v1/organizations/%s/members/%s", orgID, userID), req, nil)
if err != nil {
return err
}
return parseResponse(resp, nil)
}
// RemoveMember removes a member from an organization
func (c *Client) RemoveMember(ctx context.Context, orgID, userID string) error {
resp, err := c.doRequest(ctx, http.MethodDelete, fmt.Sprintf("/api/v1/organizations/%s/members/%s", orgID, userID), nil, nil)
if err != nil {
return err
}
return parseResponse(resp, nil)
}
// --- Join request management ---
// ListJoinRequests lists pending join requests (admin only)
func (c *Client) ListJoinRequests(ctx context.Context, orgID string) ([]JoinRequestResponse, error) {
resp, err := c.doRequest(ctx, http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s/join-requests", orgID), nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data struct {
Requests []JoinRequestResponse `json:"requests"`
} `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data.Requests, nil
}
// ReviewJoinRequest reviews a join request (approve/reject)
func (c *Client) ReviewJoinRequest(ctx context.Context, orgID, requestID string, approved bool, message, role string) error {
req := map[string]any{
"approved": approved,
"message": message,
"role": role,
}
resp, err := c.doRequest(ctx, http.MethodPut, fmt.Sprintf("/api/v1/organizations/%s/join-requests/%s/review", orgID, requestID), req, nil)
if err != nil {
return err
}
return parseResponse(resp, nil)
}
// --- Knowledge base sharing ---
// ShareKnowledgeBase shares a knowledge base with an organization
func (c *Client) ShareKnowledgeBase(ctx context.Context, kbID, orgID, permission string) (*KnowledgeBaseShareResponse, error) {
req := map[string]string{
"organization_id": orgID,
"permission": permission,
}
resp, err := c.doRequest(ctx, http.MethodPost, fmt.Sprintf("/api/v1/knowledge-bases/%s/shares", kbID), req, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data *KnowledgeBaseShareResponse `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// ListKBShares lists shares of a knowledge base
func (c *Client) ListKBShares(ctx context.Context, kbID string) ([]KnowledgeBaseShareResponse, error) {
resp, err := c.doRequest(ctx, http.MethodGet, fmt.Sprintf("/api/v1/knowledge-bases/%s/shares", kbID), nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data struct {
Shares []KnowledgeBaseShareResponse `json:"shares"`
} `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data.Shares, nil
}
// UpdateSharePermission updates a KB share's permission
func (c *Client) UpdateSharePermission(ctx context.Context, kbID, shareID, permission string) error {
req := map[string]string{"permission": permission}
resp, err := c.doRequest(ctx, http.MethodPut, fmt.Sprintf("/api/v1/knowledge-bases/%s/shares/%s", kbID, shareID), req, nil)
if err != nil {
return err
}
return parseResponse(resp, nil)
}
// RemoveKBShare removes a KB share
func (c *Client) RemoveKBShare(ctx context.Context, kbID, shareID string) error {
resp, err := c.doRequest(ctx, http.MethodDelete, fmt.Sprintf("/api/v1/knowledge-bases/%s/shares/%s", kbID, shareID), nil, nil)
if err != nil {
return err
}
return parseResponse(resp, nil)
}
// --- Agent sharing ---
// ShareAgent shares an agent with an organization
func (c *Client) ShareAgent(ctx context.Context, agentID, orgID, permission string) (*AgentShareResponse, error) {
req := map[string]string{
"organization_id": orgID,
"permission": permission,
}
resp, err := c.doRequest(ctx, http.MethodPost, fmt.Sprintf("/api/v1/agents/%s/shares", agentID), req, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data *AgentShareResponse `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// ListAgentShares lists shares of an agent
func (c *Client) ListAgentShares(ctx context.Context, agentID string) ([]AgentShareResponse, error) {
resp, err := c.doRequest(ctx, http.MethodGet, fmt.Sprintf("/api/v1/agents/%s/shares", agentID), nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data struct {
Shares []AgentShareResponse `json:"shares"`
} `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data.Shares, nil
}
// RemoveAgentShare removes an agent share
func (c *Client) RemoveAgentShare(ctx context.Context, agentID, shareID string) error {
resp, err := c.doRequest(ctx, http.MethodDelete, fmt.Sprintf("/api/v1/agents/%s/shares/%s", agentID, shareID), nil, nil)
if err != nil {
return err
}
return parseResponse(resp, nil)
}
// --- Organization shared resources ---
// ListOrgShares lists knowledge bases shared to an organization
func (c *Client) ListOrgShares(ctx context.Context, orgID string) ([]KnowledgeBaseShareResponse, error) {
resp, err := c.doRequest(ctx, http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s/shares", orgID), nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data struct {
Shares []KnowledgeBaseShareResponse `json:"shares"`
} `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data.Shares, nil
}
// ListOrgAgentShares lists agents shared to an organization
func (c *Client) ListOrgAgentShares(ctx context.Context, orgID string) ([]AgentShareResponse, error) {
resp, err := c.doRequest(ctx, http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s/agent-shares", orgID), nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data struct {
Shares []AgentShareResponse `json:"shares"`
} `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data.Shares, nil
}
// ListSharedKnowledgeBases lists all knowledge bases shared to the current user
func (c *Client) ListSharedKnowledgeBases(ctx context.Context) ([]SharedKnowledgeBaseInfo, error) {
resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/shared-knowledge-bases", nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data []SharedKnowledgeBaseInfo `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// ListSharedAgents lists all agents shared to the current user
func (c *Client) ListSharedAgents(ctx context.Context) ([]SharedAgentInfo, error) {
resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/shared-agents", nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data []SharedAgentInfo `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
+19
View File
@@ -147,6 +147,25 @@ func (c *Client) DeleteSession(ctx context.Context, sessionID string) error {
return parseResponse(resp, &response)
}
// BatchDeleteSessions deletes multiple sessions by their IDs.
func (c *Client) BatchDeleteSessions(ctx context.Context, sessionIDs []string) error {
request := struct {
IDs []string `json:"ids"`
}{IDs: sessionIDs}
resp, err := c.doRequest(ctx, http.MethodDelete, "/api/v1/sessions/batch", request, nil)
if err != nil {
return err
}
var response struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
}
return parseResponse(resp, &response)
}
// GenerateTitleRequest title generation request
type GenerateTitleRequest struct {
Messages []Message `json:"messages"`
+34
View File
@@ -0,0 +1,34 @@
package client
import (
"context"
"net/http"
)
// SkillInfo represents skill metadata
type SkillInfo struct {
Name string `json:"name"`
Description string `json:"description"`
}
// SkillListResponse represents the response from listing skills
type SkillListResponse struct {
Success bool `json:"success"`
Data []SkillInfo `json:"data"`
SkillsAvailable bool `json:"skills_available"`
}
// ListSkills lists all preloaded agent skills
func (c *Client) ListSkills(ctx context.Context) ([]SkillInfo, bool, error) {
resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/skills", nil, nil)
if err != nil {
return nil, false, err
}
var response SkillListResponse
if err := parseResponse(resp, &response); err != nil {
return nil, false, err
}
return response.Data, response.SkillsAvailable, nil
}
+174
View File
@@ -0,0 +1,174 @@
package client
import (
"context"
"encoding/json"
"net/http"
)
// SystemInfo represents system version and configuration information
type SystemInfo struct {
Version string `json:"version"`
Edition string `json:"edition"`
CommitID string `json:"commit_id,omitempty"`
BuildTime string `json:"build_time,omitempty"`
GoVersion string `json:"go_version,omitempty"`
KeywordIndexEngine string `json:"keyword_index_engine,omitempty"`
VectorStoreEngine string `json:"vector_store_engine,omitempty"`
GraphDatabaseEngine string `json:"graph_database_engine,omitempty"`
MinioEnabled bool `json:"minio_enabled,omitempty"`
DBVersion string `json:"db_version,omitempty"`
}
// ParserEngine represents a document parser engine
type ParserEngine struct {
Name string `json:"name"`
Label string `json:"label"`
Description string `json:"description"`
Available bool `json:"available"`
}
// StorageEngineStatusItem describes one storage engine's availability
type StorageEngineStatusItem struct {
Name string `json:"name"`
Available bool `json:"available"`
Description string `json:"description"`
}
// StorageEngineStatusResponse is the response for storage engine status
type StorageEngineStatusResponse struct {
Engines []StorageEngineStatusItem `json:"engines"`
MinioEnvAvailable bool `json:"minio_env_available"`
}
// StorageCheckRequest is the body for storage engine connectivity check
type StorageCheckRequest struct {
Provider string `json:"provider"`
MinIO json.RawMessage `json:"minio,omitempty"`
COS json.RawMessage `json:"cos,omitempty"`
TOS json.RawMessage `json:"tos,omitempty"`
S3 json.RawMessage `json:"s3,omitempty"`
}
// StorageCheckResponse is the response for storage engine check
type StorageCheckResponse struct {
OK bool `json:"ok"`
Message string `json:"message"`
BucketCreated bool `json:"bucket_created,omitempty"`
}
// MinioBucketInfo represents MinIO bucket information
type MinioBucketInfo struct {
Name string `json:"name"`
Policy string `json:"policy"`
CreatedAt string `json:"created_at,omitempty"`
}
// GetSystemInfo gets system version and configuration information
func (c *Client) GetSystemInfo(ctx context.Context) (*SystemInfo, error) {
resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/system/info", nil, nil)
if err != nil {
return nil, err
}
var result struct {
Code int `json:"code"`
Data *SystemInfo `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// ListParserEngines lists available document parser engines
func (c *Client) ListParserEngines(ctx context.Context) ([]ParserEngine, error) {
resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/system/parser-engines", nil, nil)
if err != nil {
return nil, err
}
var result struct {
Code int `json:"code"`
Data []ParserEngine `json:"data"`
Connected bool `json:"connected"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// CheckParserEngines checks parser engine availability with given config overrides
func (c *Client) CheckParserEngines(ctx context.Context, config any) ([]ParserEngine, error) {
resp, err := c.doRequest(ctx, http.MethodPost, "/api/v1/system/parser-engines/check", config, nil)
if err != nil {
return nil, err
}
var result struct {
Code int `json:"code"`
Data []ParserEngine `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// ReconnectDocReader reconnects the document parser service to a new address
func (c *Client) ReconnectDocReader(ctx context.Context, addr string) error {
req := map[string]string{"addr": addr}
resp, err := c.doRequest(ctx, http.MethodPost, "/api/v1/system/docreader/reconnect", req, nil)
if err != nil {
return err
}
return parseResponse(resp, nil)
}
// GetStorageEngineStatus gets the availability status of all storage engines
func (c *Client) GetStorageEngineStatus(ctx context.Context) (*StorageEngineStatusResponse, error) {
resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/system/storage-engine-status", nil, nil)
if err != nil {
return nil, err
}
var result struct {
Code int `json:"code"`
Data *StorageEngineStatusResponse `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// CheckStorageEngine tests connectivity for a storage engine
func (c *Client) CheckStorageEngine(ctx context.Context, req *StorageCheckRequest) (*StorageCheckResponse, error) {
resp, err := c.doRequest(ctx, http.MethodPost, "/api/v1/system/storage-engine-check", req, nil)
if err != nil {
return nil, err
}
var result struct {
Code int `json:"code"`
Data *StorageCheckResponse `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// ListMinioBuckets lists all MinIO buckets with their access policies
func (c *Client) ListMinioBuckets(ctx context.Context) ([]MinioBucketInfo, error) {
resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/system/minio/buckets", nil, nil)
if err != nil {
return nil, err
}
var result struct {
Code int `json:"code"`
Data struct {
Buckets []MinioBucketInfo `json:"buckets"`
} `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data.Buckets, nil
}
+90
View File
@@ -6,8 +6,11 @@ package client
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"time"
)
@@ -138,3 +141,90 @@ func (c *Client) ListTenants(ctx context.Context) ([]Tenant, error) {
return response.Data.Items, nil
}
// ListAllTenants retrieves all tenants in the system (requires cross-tenant access)
func (c *Client) ListAllTenants(ctx context.Context) ([]Tenant, error) {
resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/tenants/all", nil, nil)
if err != nil {
return nil, err
}
var response TenantListResponse
if err := parseResponse(resp, &response); err != nil {
return nil, err
}
return response.Data.Items, nil
}
// TenantSearchResponse represents the API response for searching tenants
type TenantSearchResponse struct {
Success bool `json:"success"`
Data struct {
Items []Tenant `json:"items"`
Total int64 `json:"total"`
Page int `json:"page"`
PageSize int `json:"page_size"`
} `json:"data"`
}
// SearchTenants searches tenants with pagination (requires cross-tenant access)
func (c *Client) SearchTenants(ctx context.Context, keyword string, tenantID uint64, page, pageSize int) ([]Tenant, int64, error) {
queryParams := url.Values{}
if keyword != "" {
queryParams.Set("keyword", keyword)
}
if tenantID > 0 {
queryParams.Set("tenant_id", strconv.FormatUint(tenantID, 10))
}
queryParams.Set("page", strconv.Itoa(page))
queryParams.Set("page_size", strconv.Itoa(pageSize))
resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/tenants/search", nil, queryParams)
if err != nil {
return nil, 0, err
}
var response TenantSearchResponse
if err := parseResponse(resp, &response); err != nil {
return nil, 0, err
}
return response.Data.Items, response.Data.Total, nil
}
// GetTenantKV retrieves a tenant KV configuration by key
func (c *Client) GetTenantKV(ctx context.Context, key string) (json.RawMessage, error) {
path := fmt.Sprintf("/api/v1/tenants/kv/%s", key)
resp, err := c.doRequest(ctx, http.MethodGet, path, nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data json.RawMessage `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
// UpdateTenantKV updates a tenant KV configuration by key
func (c *Client) UpdateTenantKV(ctx context.Context, key string, value any) (json.RawMessage, error) {
path := fmt.Sprintf("/api/v1/tenants/kv/%s", key)
resp, err := c.doRequest(ctx, http.MethodPut, path, value, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data json.RawMessage `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}
+32
View File
@@ -0,0 +1,32 @@
package client
import (
"context"
"encoding/json"
"net/http"
)
// WebSearchProvider represents a web search provider
type WebSearchProvider struct {
Name string `json:"name"`
Label string `json:"label"`
Description string `json:"description,omitempty"`
Enabled bool `json:"enabled"`
}
// GetWebSearchProviders returns the list of available web search providers
func (c *Client) GetWebSearchProviders(ctx context.Context) ([]json.RawMessage, error) {
resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/web-search/providers", nil, nil)
if err != nil {
return nil, err
}
var result struct {
Success bool `json:"success"`
Data []json.RawMessage `json:"data"`
}
if err := parseResponse(resp, &result); err != nil {
return nil, err
}
return result.Data, nil
}