Documentation
¶
Overview ¶
Package client provides the implementation for interacting with the WeKnora API The Agent related interfaces are used to manage agent-based question-answering
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 provides the implementation for interacting with the WeKnora API This package encapsulates CRUD operations for server resources and provides a friendly interface for callers The Chunk related interfaces are used to manage document chunks in the knowledge base
Package client provides the implementation for interacting with the WeKnora API This package encapsulates CRUD operations for server resources and provides a friendly interface for callers
Package client provides the implementation for interacting with the WeKnora API The Evaluation related interfaces are used for starting and retrieving model evaluation task results Evaluation tasks can be used to measure model performance and compare different embedding models, chat models, and reranking models
Package client provides the implementation for interacting with the WeKnora API The Knowledge related interfaces are used to manage knowledge entries in the knowledge base Knowledge entries can be created from local files, web URLs, or directly from text content They can also be retrieved, deleted, and downloaded as files
Package client provides the implementation for interacting with the WeKnora API The KnowledgeBase related interfaces are used to manage knowledge bases Knowledge bases are collections of knowledge entries that can be used for question-answering They can also be searched and queried using hybrid search
Package client uses an opt-in slog logger for SDK-internal trace output. Default behavior writes to io.Discard so SDK consumers (CLI, server) never see SDK trace output on stdout/stderr. Embedders enable debug output by calling SetDebugLevel("debug") at startup.
Package client provides the implementation for interacting with the WeKnora API The Message related interfaces are used to manage messages in a session Messages can be created, retrieved, deleted, and queried
Package client provides the implementation for interacting with the WeKnora API The Model related interfaces are used to manage models for different tasks Models can be created, retrieved, updated, deleted, and queried
Package client provides the implementation for interacting with the WeKnora API The Session related interfaces are used to manage sessions for question-answering Sessions can be created, retrieved, updated, deleted, and queried They can also be used to generate titles for sessions
Package client provides the implementation for interacting with the WeKnora API The Tenant related interfaces are used to manage tenants in the system Tenants can be created, retrieved, updated, deleted, and queried They can also be used to manage retriever engines for different tasks
Index ¶
- Constants
- Variables
- func ExampleUsage()
- func IsSSEStreamError(err error) bool
- func NewSSEStreamError(content string) error
- func SetDebugLevel(level string)
- type APIError
- type APIPrincipalConfig
- type APIPrincipalMode
- type APIPrincipalTestToken
- type ASRConfig
- type AddSimilarQuestionsPayload
- type Agent
- type AgentConfig
- type AgentEventCallback
- type AgentListResponse
- type AgentMode
- type AgentPlaceholdersResponse
- type AgentQARequest
- type AgentResponse
- type AgentResponseType
- type AgentSession
- type AgentShareResponse
- type AgentStep
- type AgentStreamResponse
- type AuthCapabilities
- type AuthConfigResponse
- type AuthMembership
- type AuthTenant
- type AuthUser
- type AutoTagConfig
- type BatchDownloadKnowledgeRequest
- type BatchUpdateKnowledgeTagsRequest
- type ChangePasswordRequest
- type ChangePasswordResponse
- type ChatHistoryKBStats
- type Chunk
- type ChunkListResponse
- type ChunkResponse
- type ChunkingConfig
- type ClearKnowledgeBaseContentsResponse
- type Client
- func (c *Client) AddSimilarQuestions(ctx context.Context, knowledgeBaseID string, entrySeqID int64, ...) (*FAQEntry, error)
- func (c *Client) AgentQAStream(ctx context.Context, sessionID string, query string, ...) error
- func (c *Client) AgentQAStreamWithRequest(ctx context.Context, sessionID string, request *AgentQARequest, ...) error
- func (c *Client) BatchDeleteSessions(ctx context.Context, sessionIDs []string) error
- func (c *Client) BatchUpdateKnowledgeTags(ctx context.Context, updates map[string]*string) error
- func (c *Client) CancelKnowledgeParse(ctx context.Context, knowledgeID string) (*Knowledge, error)
- func (c *Client) ChangePassword(ctx context.Context, req ChangePasswordRequest) (*ChangePasswordResponse, error)
- func (c *Client) CheckOllamaModels(ctx context.Context, models []string) (map[string]bool, error)
- func (c *Client) CheckOllamaStatus(ctx context.Context) (bool, error)
- func (c *Client) CheckParserEngines(ctx context.Context, config any) ([]ParserEngine, error)
- func (c *Client) CheckRemoteModel(ctx context.Context, params map[string]string) (*ModelCheckResult, error)
- func (c *Client) CheckRerankModel(ctx context.Context, params map[string]string) (*ModelCheckResult, error)
- func (c *Client) CheckStorageEngine(ctx context.Context, req *StorageCheckRequest) (*StorageCheckResponse, error)
- func (c *Client) ClearKnowledgeBaseContents(ctx context.Context, knowledgeBaseID string) (*ClearKnowledgeBaseContentsResponse, error)
- func (c *Client) ClearMemoryItems(ctx context.Context) (int64, error)
- func (c *Client) ConfirmMemoryItem(ctx context.Context, id string) (*MemoryItem, error)
- func (c *Client) ConsolidateMemory(ctx context.Context) (*MemoryConsolidationResult, error)
- func (c *Client) ContinueStream(ctx context.Context, sessionID string, messageID string, ...) error
- func (c *Client) CopyAgent(ctx context.Context, agentID string) (*Agent, error)
- func (c *Client) CopyKnowledgeBase(ctx context.Context, request *CopyKnowledgeBaseRequest) (*CopyKnowledgeBaseResponse, error)
- func (c *Client) CreateAPIPrincipalTestToken(ctx context.Context, tenantID uint64, req *CreateAPIPrincipalTestTokenRequest) (*APIPrincipalTestToken, error)
- func (c *Client) CreateAgent(ctx context.Context, request *CreateAgentRequest) (*Agent, error)
- func (c *Client) CreateFAQEntry(ctx context.Context, knowledgeBaseID string, payload *FAQEntryPayload) (*FAQEntry, error)
- func (c *Client) CreateKnowledgeBase(ctx context.Context, knowledgeBase *KnowledgeBase) (*KnowledgeBase, error)
- func (c *Client) CreateKnowledgeFromFile(ctx context.Context, knowledgeBaseID string, filePath string, ...) (*Knowledge, error)
- func (c *Client) CreateKnowledgeFromURL(ctx context.Context, knowledgeBaseID string, req CreateKnowledgeFromURLRequest) (*Knowledge, error)
- func (c *Client) CreateMCPEndpoint(ctx context.Context, req *MCPEndpointRequest) (*MCPEndpoint, error)
- func (c *Client) CreateMCPService(ctx context.Context, service *MCPService) (*MCPService, error)
- func (c *Client) CreateManualKnowledge(ctx context.Context, knowledgeBaseID string, ...) (*Knowledge, error)
- func (c *Client) CreateMemoryItem(ctx context.Context, kind, content string, importance int) (*MemoryItem, error)
- func (c *Client) CreateModel(ctx context.Context, request *CreateModelRequest) (*Model, error)
- func (c *Client) CreateOrganization(ctx context.Context, req *CreateOrganizationRequest) (*OrganizationResponse, error)
- func (c *Client) CreateSession(ctx context.Context, request *CreateSessionRequest) (*Session, error)
- func (c *Client) CreateTag(ctx context.Context, knowledgeBaseID string, payload *CreateTagPayload) (*Tag, error)
- func (c *Client) CreateTenant(ctx context.Context, tenant *Tenant) (*Tenant, error)
- func (c *Client) CreateTenantAPIKey(ctx context.Context, tenantID uint64, req *CreateTenantAPIKeyRequest) (*CreatedTenantAPIKey, error)
- func (c *Client) DeleteAgent(ctx context.Context, agentID string) error
- func (c *Client) DeleteChunk(ctx context.Context, knowledgeID string, chunkID string) error
- func (c *Client) DeleteChunksByKnowledgeID(ctx context.Context, knowledgeID string) error
- func (c *Client) DeleteFAQEntries(ctx context.Context, knowledgeBaseID string, ids []int64) error
- func (c *Client) DeleteGeneratedQuestion(ctx context.Context, chunkID string, questionID string) error
- func (c *Client) DeleteKnowledge(ctx context.Context, knowledgeID string) error
- func (c *Client) DeleteKnowledgeBase(ctx context.Context, knowledgeBaseID string) error
- func (c *Client) DeleteMCPEndpoint(ctx context.Context, endpointID string) error
- func (c *Client) DeleteMCPService(ctx context.Context, serviceID string) error
- func (c *Client) DeleteMemoryDocument(ctx context.Context, id string) error
- func (c *Client) DeleteMemoryItem(ctx context.Context, id string) error
- func (c *Client) DeleteMemoryTopic(ctx context.Context, id string) error
- func (c *Client) DeleteMessage(ctx context.Context, sessionID string, messageID string) error
- func (c *Client) DeleteModel(ctx context.Context, modelID string) error
- func (c *Client) DeleteMySandboxEnvVar(ctx context.Context, configID, name string) error
- func (c *Client) DeleteMySkillEnvVar(ctx context.Context, skillID, name string) error
- func (c *Client) DeleteOrganization(ctx context.Context, orgID string) error
- func (c *Client) DeleteSession(ctx context.Context, sessionID string) error
- func (c *Client) DeleteTag(ctx context.Context, knowledgeBaseID, tagID string, force bool, ...) error
- func (c *Client) DeleteTagBySeqID(ctx context.Context, knowledgeBaseID string, tagSeqID int64, force bool, ...) error
- func (c *Client) DeleteTenant(ctx context.Context, tenantID uint64) error
- func (c *Client) DeleteTenantAPIKey(ctx context.Context, tenantID uint64, keyID uint64) error
- func (c *Client) DownloadKnowledgeFile(ctx context.Context, knowledgeID string, destPath string) error
- func (c *Client) DownloadKnowledgeFiles(ctx context.Context, knowledgeBaseID string, ids []string, destPath string) error
- func (c *Client) DownloadOllamaModel(ctx context.Context, modelName string) (*DownloadTask, error)
- func (c *Client) DuplicateKnowledgeBase(ctx context.Context, knowledgeBaseID string) (*DuplicateKnowledgeBaseResponse, error)
- func (c *Client) EnsureMessageSuggestions(ctx context.Context, sessionID string, messageID string, regenerate bool) (*MessageSuggestionSet, error)
- func (c *Client) ExportFAQEntries(ctx context.Context, knowledgeBaseID string) ([]byte, error)
- func (c *Client) ExportMemory(ctx context.Context) (*MemoryExport, error)
- func (c *Client) ExtractTextRelations(ctx context.Context, params any) (json.RawMessage, error)
- func (c *Client) FilterKnowledge(ctx context.Context, keyword string, offset, limit int, fileTypes []string, ...) ([]Knowledge, bool, error)
- func (c *Client) GenerateInviteCode(ctx context.Context, orgID string) (string, error)
- func (c *Client) GenerateTitle(ctx context.Context, sessionID string, request *GenerateTitleRequest) (string, error)
- func (c *Client) GetAPIPrincipalConfig(ctx context.Context, tenantID uint64) (*APIPrincipalConfig, error)
- func (c *Client) GetAgent(ctx context.Context, agentID string) (*Agent, error)
- func (c *Client) GetAgentPlaceholders(ctx context.Context) (map[string]json.RawMessage, error)
- func (c *Client) GetAuthConfig(ctx context.Context) (*AuthConfigResponse, error)
- func (c *Client) GetChatHistoryKBStats(ctx context.Context) (*ChatHistoryKBStats, error)
- func (c *Client) GetChunkByIDOnly(ctx context.Context, chunkID string) (*Chunk, error)
- func (c *Client) GetCurrentUser(ctx context.Context) (*CurrentUserResponse, error)
- func (c *Client) GetDeploymentCapabilities(ctx context.Context) (*DeploymentCapabilitiesData, error)
- func (c *Client) GetEvaluationResult(ctx context.Context, taskID string) (*EvaluationResult, error)
- func (c *Client) GetFAQEntry(ctx context.Context, knowledgeBaseID string, entrySeqID int64) (*FAQEntry, error)
- func (c *Client) GetFAQImportProgress(ctx context.Context, taskID string) (*FAQImportProgress, error)
- func (c *Client) GetInitializationConfig(ctx context.Context, kbID string) (*KBModelConfigView, error)
- func (c *Client) GetKBCloneProgress(ctx context.Context, taskID string) (*KBCloneProgress, error)
- func (c *Client) GetKnowledge(ctx context.Context, knowledgeID string) (*Knowledge, error)
- func (c *Client) GetKnowledgeBase(ctx context.Context, knowledgeBaseID string) (*KnowledgeBase, error)
- func (c *Client) GetKnowledgeBatch(ctx context.Context, knowledgeIDs []string) ([]Knowledge, error)
- func (c *Client) GetKnowledgeMoveProgress(ctx context.Context, taskID string) (*KnowledgeMoveProgress, error)
- func (c *Client) GetKnowledgeProcessingSpans(ctx context.Context, knowledgeID string, attempt int) (*KnowledgeProcessingTrace, error)
- func (c *Client) GetMCPEndpoint(ctx context.Context, endpointID string) (*MCPEndpoint, error)
- func (c *Client) GetMCPEndpointToolCatalog(ctx context.Context) (*MCPEndpointToolCatalog, error)
- func (c *Client) GetMCPMetadata(ctx context.Context, serviceID string) (*MCPMetadata, error)
- func (c *Client) GetMCPService(ctx context.Context, serviceID string) (*MCPService, error)
- func (c *Client) GetMCPServiceResources(ctx context.Context, serviceID string) ([]*MCPResource, error)
- func (c *Client) GetMCPServiceTools(ctx context.Context, serviceID string) ([]*MCPTool, error)
- func (c *Client) GetMemorySettings(ctx context.Context) (*MemorySettings, error)
- func (c *Client) GetMessageSuggestions(ctx context.Context, sessionID string, messageID string) (*MessageSuggestionSet, error)
- func (c *Client) GetMessagesBefore(ctx context.Context, sessionID string, beforeTime time.Time, limit int) ([]Message, error)
- func (c *Client) GetModel(ctx context.Context, modelID string) (*Model, error)
- func (c *Client) GetOllamaDownloadProgress(ctx context.Context, taskID string) (*DownloadTask, error)
- func (c *Client) GetOrganization(ctx context.Context, orgID string) (*OrganizationResponse, error)
- func (c *Client) GetRecentMessages(ctx context.Context, sessionID string, limit int) ([]Message, error)
- func (c *Client) GetSandboxSkillFile(ctx context.Context, configID, skillID, filePath string) (*SandboxSkillFileContent, error)
- func (c *Client) GetSession(ctx context.Context, sessionID string) (*Session, error)
- func (c *Client) GetSessionsByTenant(ctx context.Context, page int, pageSize int, opts ...SessionListOptions) ([]Session, int, error)
- func (c *Client) GetStorageEngineStatus(ctx context.Context) (*StorageEngineStatusResponse, error)
- func (c *Client) GetSuggestedQuestions(ctx context.Context, agentID string, request *SuggestedQuestionsRequest) ([]SuggestedQuestion, error)
- func (c *Client) GetSystemInfo(ctx context.Context) (*SystemInfo, error)
- func (c *Client) GetTenant(ctx context.Context, tenantID uint64) (*Tenant, error)
- func (c *Client) GetTenantKV(ctx context.Context, key string) (json.RawMessage, error)
- func (c *Client) GetWebSearchProviders(ctx context.Context) ([]json.RawMessage, error)
- func (c *Client) HybridSearch(ctx context.Context, knowledgeBaseID string, params *SearchParams, ...) ([]*SearchResult, error)
- func (c *Client) HybridSearchDetailed(ctx context.Context, knowledgeBaseID string, params *SearchParams, ...) (*HybridSearchResponse, error)
- func (c *Client) InitializeByKB(ctx context.Context, kbID string, config *InitializationConfig) error
- func (c *Client) InstallSandboxSkillFromSource(ctx context.Context, configID, source string) (string, error)
- func (c *Client) InviteMember(ctx context.Context, orgID, userID, role string) error
- func (c *Client) JoinByOrganizationID(ctx context.Context, orgID, message, role string) error
- func (c *Client) JoinOrganizationByInviteCode(ctx context.Context, inviteCode string) error
- func (c *Client) KnowledgeQAStream(ctx context.Context, sessionID string, request *KnowledgeQARequest, ...) error
- func (c *Client) LeaveOrganization(ctx context.Context, orgID string) error
- func (c *Client) ListAgentShares(ctx context.Context, agentID string) ([]AgentShareResponse, error)
- func (c *Client) ListAgents(ctx context.Context) ([]Agent, error)
- func (c *Client) ListAllTenants(ctx context.Context) ([]Tenant, error)
- func (c *Client) ListFAQEntries(ctx context.Context, knowledgeBaseID string, page, pageSize int, ...) (*FAQEntriesPage, error)
- func (c *Client) ListJoinRequests(ctx context.Context, orgID string) ([]JoinRequestResponse, error)
- func (c *Client) ListKBShares(ctx context.Context, kbID string) ([]KnowledgeBaseShareResponse, error)
- func (c *Client) ListKnowledge(ctx context.Context, knowledgeBaseID string, page int, pageSize int, ...) ([]Knowledge, int64, error)
- func (c *Client) ListKnowledgeBases(ctx context.Context) ([]KnowledgeBase, error)
- func (c *Client) ListKnowledgeChunks(ctx context.Context, knowledgeID string, page int, pageSize int, ...) ([]Chunk, int64, error)
- func (c *Client) ListKnowledgeFolders(ctx context.Context, knowledgeBaseID string) (*KnowledgeFolderTree, error)
- func (c *Client) ListKnowledgeWithFilter(ctx context.Context, knowledgeBaseID string, page int, pageSize int, ...) ([]Knowledge, int64, error)
- func (c *Client) ListMCPEndpoints(ctx context.Context) ([]*MCPEndpoint, error)
- func (c *Client) ListMCPServices(ctx context.Context) ([]*MCPService, error)
- func (c *Client) ListMemoryDocuments(ctx context.Context, limit, offset int) ([]*MemoryDocument, int64, error)
- func (c *Client) ListMemoryItems(ctx context.Context, status string, limit, offset int) ([]*MemoryItem, int64, error)
- func (c *Client) ListMemoryTopics(ctx context.Context, limit, offset int) ([]*MemoryTopic, int64, error)
- func (c *Client) ListModelProviders(ctx context.Context, modelType string) ([]ModelProvider, error)
- func (c *Client) ListModels(ctx context.Context) ([]Model, error)
- func (c *Client) ListMoveTargets(ctx context.Context, knowledgeBaseID string) ([]KnowledgeBase, error)
- func (c *Client) ListMyEnvVars(ctx context.Context) ([]ConfigEnvGroup, error)
- func (c *Client) ListMyOrganizations(ctx context.Context) ([]OrganizationResponse, error)
- func (c *Client) ListOllamaDownloadTasks(ctx context.Context) ([]*DownloadTask, error)
- func (c *Client) ListOllamaModels(ctx context.Context) ([]OllamaModelInfo, error)
- func (c *Client) ListOrgAgentShares(ctx context.Context, orgID string) ([]AgentShareResponse, error)
- func (c *Client) ListOrgMembers(ctx context.Context, orgID string) ([]OrganizationMemberResponse, error)
- func (c *Client) ListOrgShares(ctx context.Context, orgID string) ([]KnowledgeBaseShareResponse, error)
- func (c *Client) ListParserEngines(ctx context.Context) ([]ParserEngine, error)
- func (c *Client) ListSandboxSkillFiles(ctx context.Context, configID, skillID string) ([]SandboxSkillFile, error)
- func (c *Client) ListSharedAgents(ctx context.Context) ([]SharedAgentInfo, error)
- func (c *Client) ListSharedKnowledgeBases(ctx context.Context) ([]SharedKnowledgeBaseInfo, error)
- func (c *Client) ListSkills(ctx context.Context, sandboxConfigID string) ([]SkillInfo, bool, error)
- func (c *Client) ListTags(ctx context.Context, knowledgeBaseID string, page, pageSize int, ...) (*TagsPage, error)
- func (c *Client) ListTenantAPIKeys(ctx context.Context, tenantID uint64) ([]TenantAPIKey, error)
- func (c *Client) ListTenants(ctx context.Context) ([]Tenant, error)
- func (c *Client) LoadMessages(ctx context.Context, sessionID string, limit int, beforeTime *time.Time, ...) ([]Message, error)
- func (c *Client) Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)
- func (c *Client) MoveKnowledge(ctx context.Context, req *MoveKnowledgeRequest) (*MoveKnowledgeResponse, error)
- func (c *Client) MoveKnowledgeToFolder(ctx context.Context, req *MoveKnowledgeToFolderRequest) (*MoveKnowledgeToFolderResponse, error)
- func (c *Client) NewAgentSession(sessionID string) *AgentSession
- func (c *Client) OpenKnowledgeFile(ctx context.Context, knowledgeID string) (string, io.ReadCloser, error)
- func (c *Client) OpenKnowledgeFilesArchive(ctx context.Context, knowledgeBaseID string, ids []string) (string, io.ReadCloser, error)
- func (c *Client) PatchAgent(ctx context.Context, agentID string, request *PatchAgentRequest) (*Agent, error)
- func (c *Client) PatchKnowledgeBase(ctx context.Context, knowledgeBaseID string, ...) (*KnowledgeBase, error)
- func (c *Client) PreviewKnowledgeFile(ctx context.Context, knowledgeID string) (*http.Response, error)
- func (c *Client) PreviewOrganizationByInviteCode(ctx context.Context, code string) (*OrganizationResponse, error)
- func (c *Client) PromoteMemoryTopic(ctx context.Context, id string) (*MemoryItem, error)
- func (c *Client) Raw(ctx context.Context, method, path string, body interface{}) (*http.Response, error)
- func (c *Client) ReconnectDocReader(ctx context.Context, addr string) error
- func (c *Client) RecordMessageSuggestionEvent(ctx context.Context, sessionID string, setID string, questionID string, ...) error
- func (c *Client) RefreshMCPMetadata(ctx context.Context, serviceID string) (*MCPMetadata, error)
- func (c *Client) RefreshToken(ctx context.Context, refreshToken string) (*RefreshTokenResponse, error)
- func (c *Client) ReinstallSandboxSkill(ctx context.Context, configID, skillID string) (string, error)
- func (c *Client) RejectMemoryItem(ctx context.Context, id string) error
- func (c *Client) RemoveAgentShare(ctx context.Context, agentID, shareID string) error
- func (c *Client) RemoveKBShare(ctx context.Context, kbID, shareID string) error
- func (c *Client) RemoveMember(ctx context.Context, orgID, userID string) error
- func (c *Client) RenameKnowledgeFolder(ctx context.Context, knowledgeBaseID string, req *RenameKnowledgeFolderRequest) (*RenameKnowledgeFolderResponse, error)
- func (c *Client) ReparseKnowledge(ctx context.Context, knowledgeID string) (*Knowledge, error)
- func (c *Client) RequestRoleUpgrade(ctx context.Context, orgID, requestedRole, message string) error
- func (c *Client) ResolveAgentPrompt(ctx context.Context, promptID string, req *ResolveAgentPromptRequest) (resumed bool, err error)
- func (c *Client) ResolveToolApproval(ctx context.Context, pendingID string, req *ResolveToolApprovalRequest) error
- func (c *Client) ReviewJoinRequest(ctx context.Context, orgID, requestID string, approved bool, ...) error
- func (c *Client) RotateMCPEndpointToken(ctx context.Context, endpointID string) (*MCPEndpoint, error)
- func (c *Client) SearchFAQEntries(ctx context.Context, knowledgeBaseID string, payload *FAQSearchRequest) ([]FAQEntry, error)
- func (c *Client) SearchKnowledge(ctx context.Context, request *SearchKnowledgeRequest, ...) ([]*SearchResult, error)
- func (c *Client) SearchKnowledgeDetailed(ctx context.Context, request *SearchKnowledgeRequest, ...) (*SearchKnowledgeResponse, error)
- func (c *Client) SearchMessages(ctx context.Context, req *SearchMessagesRequest) (*MessageSearchResult, error)
- func (c *Client) SearchOrganizations(ctx context.Context, keyword string, page, pageSize int) ([]OrganizationResponse, error)
- func (c *Client) SearchTenants(ctx context.Context, keyword string, tenantID uint64, page, pageSize int) ([]Tenant, int64, error)
- func (c *Client) SearchUsersForInvite(ctx context.Context, orgID, keyword string) ([]UserInfo, error)
- func (c *Client) SetKBModelConfig(ctx context.Context, kbID string, cfg *KBModelConfig) error
- func (c *Client) SetMySandboxEnvVar(ctx context.Context, configID, name, value string) error
- func (c *Client) SetMySkillEnvVar(ctx context.Context, skillID, name, value string) error
- func (c *Client) SetSandboxSkillEnabled(ctx context.Context, configID, skillID string, enabled bool) (*SandboxSkill, error)
- func (c *Client) SetSandboxSkillEnvValues(ctx context.Context, configID, skillID string, values map[string]string) (*SandboxSkill, error)
- func (c *Client) ShareAgent(ctx context.Context, agentID, orgID, permission string) (*AgentShareResponse, error)
- func (c *Client) ShareKnowledgeBase(ctx context.Context, kbID, orgID, permission string) (*KnowledgeBaseShareResponse, error)
- func (c *Client) StartEvaluation(ctx context.Context, request *EvaluationRequest) (*EvaluationTask, error)
- func (c *Client) StopSandboxSkill(ctx context.Context, configID, skillID string) (*SandboxSkill, error)
- func (c *Client) StopSession(ctx context.Context, sessionID string, messageID string) error
- func (c *Client) SubmitJoinRequest(ctx context.Context, inviteCode, message, role string) error
- func (c *Client) SwitchTenant(ctx context.Context, req SwitchTenantRequest) (*LoginResponse, error)
- func (c *Client) TestEmbeddingModel(ctx context.Context, params map[string]string) (*ModelCheckResult, error)
- func (c *Client) TestMCPService(ctx context.Context, serviceID string) (*MCPTestResult, error)
- func (c *Client) TestMultimodalFunction(ctx context.Context, params map[string]string) (*ModelCheckResult, error)
- func (c *Client) TogglePinKnowledgeBase(ctx context.Context, knowledgeBaseID string) (*KnowledgeBase, error)
- func (c *Client) UpdateAPIPrincipalConfig(ctx context.Context, tenantID uint64, req *UpdateAPIPrincipalConfigRequest) (*APIPrincipalConfig, error)
- func (c *Client) UpdateAgent(ctx context.Context, agentID string, request *UpdateAgentRequest) (*Agent, error)
- func (c *Client) UpdateChunk(ctx context.Context, knowledgeID string, chunkID string, ...) (*Chunk, error)
- func (c *Client) UpdateFAQEntry(ctx context.Context, knowledgeBaseID string, entrySeqID int64, ...) (*FAQEntry, error)
- func (c *Client) UpdateFAQEntryFieldsBatch(ctx context.Context, knowledgeBaseID string, ...) error
- func (c *Client) UpdateFAQEntryTagBatch(ctx context.Context, knowledgeBaseID string, updates map[int64]*int64) error
- func (c *Client) UpdateImageInfo(ctx context.Context, knowledgeID string, chunkID string, ...) error
- func (c *Client) UpdateKBConfig(ctx context.Context, kbID string, config *InitializationConfig) errordeprecated
- func (c *Client) UpdateKnowledge(ctx context.Context, knowledge *Knowledge) error
- func (c *Client) UpdateKnowledgeBase(ctx context.Context, knowledgeBaseID string, ...) (*KnowledgeBase, error)
- func (c *Client) UpdateLastFAQImportResultDisplayStatus(ctx context.Context, knowledgeBaseID string, displayStatus string) error
- func (c *Client) UpdateMCPEndpoint(ctx context.Context, endpointID string, req *MCPEndpointRequest) (*MCPEndpoint, error)
- func (c *Client) UpdateMCPService(ctx context.Context, serviceID string, updates map[string]interface{}) (*MCPService, error)
- func (c *Client) UpdateManualKnowledge(ctx context.Context, knowledgeID string, request *UpdateManualKnowledgeRequest) (*Knowledge, error)
- func (c *Client) UpdateMemberRole(ctx context.Context, orgID, userID, role string) error
- func (c *Client) UpdateMemoryItem(ctx context.Context, id, content string, importance int) (*MemoryItem, error)
- func (c *Client) UpdateMemorySettings(ctx context.Context, enabled bool) (*MemorySettings, error)
- func (c *Client) UpdateModel(ctx context.Context, modelID string, request *UpdateModelRequest) (*Model, error)
- func (c *Client) UpdateOrganization(ctx context.Context, orgID string, req *UpdateOrganizationRequest) (*OrganizationResponse, error)
- func (c *Client) UpdateSandboxSkill(ctx context.Context, configID, skillID string, update SandboxSkillUpdate) (*SandboxSkill, error)
- func (c *Client) UpdateSession(ctx context.Context, sessionID string, request *CreateSessionRequest) (*Session, error)
- func (c *Client) UpdateSharePermission(ctx context.Context, kbID, shareID, permission string) error
- func (c *Client) UpdateTag(ctx context.Context, knowledgeBaseID, tagID string, payload *UpdateTagPayload) (*Tag, error)
- func (c *Client) UpdateTagBySeqID(ctx context.Context, knowledgeBaseID string, tagSeqID int64, ...) (*Tag, error)
- func (c *Client) UpdateTenant(ctx context.Context, tenant *Tenant) (*Tenant, error)
- func (c *Client) UpdateTenantAPIKey(ctx context.Context, tenantID uint64, keyID uint64, ...) (*TenantAPIKey, error)
- func (c *Client) UpdateTenantKV(ctx context.Context, key string, value any) (json.RawMessage, error)
- func (c *Client) UploadSandboxSkill(ctx context.Context, configID, filename string, archive []byte) (string, error)
- func (c *Client) UpsertFAQEntries(ctx context.Context, knowledgeBaseID string, payload *FAQBatchUpsertPayload) (string, error)
- type ClientOption
- type ConfigEnvGroup
- type CopyKnowledgeBaseRequest
- type CopyKnowledgeBaseResponse
- type CreateAPIPrincipalTestTokenRequest
- type CreateAgentRequest
- type CreateKnowledgeFromURLRequest
- type CreateManualKnowledgeRequest
- type CreateModelRequest
- type CreateOrganizationRequest
- type CreateSessionRequest
- type CreateTagPayload
- type CreateTenantAPIKeyRequest
- type CreatedTenantAPIKey
- type CurrentUserResponse
- type DeploymentCapabilitiesData
- type DeploymentCapability
- type DownloadTask
- type DuplicateKnowledgeBaseResponse
- type EnvVarView
- type EvaluationRequest
- type EvaluationResult
- type EvaluationResultResponse
- type EvaluationTask
- type EvaluationTaskResponse
- type ExtractConfig
- type FAQBatchUpsertPayload
- type FAQConfig
- type FAQDeleteRequest
- type FAQEntriesPage
- type FAQEntriesResponse
- type FAQEntry
- type FAQEntryFieldsBatchRequest
- type FAQEntryFieldsUpdate
- type FAQEntryPayload
- type FAQEntryResponse
- type FAQEntryTagBatchRequest
- type FAQFailedEntry
- type FAQImportProgress
- type FAQImportProgressResponse
- type FAQSearchRequest
- type FAQSearchResponse
- type FAQSuccessEntry
- type FAQTaskPayload
- type FAQUpsertResponse
- type FilterKnowledgeResponse
- type FollowUpSuggestionConfig
- type FunctionCall
- type GenerateTitleRequest
- type GenerateTitleResponse
- type GraphNode
- type GraphRelation
- type HybridSearchResponse
- type ImageAttachment
- type ImageProcessingConfig
- type IndexingStrategy
- type InitializationConfig
- type JoinRequestResponse
- type KBCloneProgress
- type KBModelConfig
- type KBModelConfigView
- type KBSelectionMode
- type Knowledge
- type KnowledgeBase
- type KnowledgeBaseConfig
- type KnowledgeBaseListResponse
- type KnowledgeBaseResponse
- type KnowledgeBaseShareResponse
- type KnowledgeBatchResponse
- type KnowledgeFolderNode
- type KnowledgeFolderTree
- type KnowledgeListFilter
- type KnowledgeListResponse
- type KnowledgeMoveProgress
- type KnowledgeProcessOverrides
- type KnowledgeProcessingTrace
- type KnowledgeQARequest
- type KnowledgeResponse
- type KnowledgeSpanError
- type KnowledgeSpanNode
- type LLMToolCall
- type LoginRequest
- type LoginResponse
- type MCPAdvancedConfig
- type MCPAuthConfig
- type MCPCatalogSummary
- type MCPEndpoint
- type MCPEndpointRequest
- type MCPEndpointToolCatalog
- type MCPEndpointToolDefinition
- type MCPMetadata
- type MCPResource
- type MCPService
- type MCPStdioConfig
- type MCPTestResult
- type MCPTool
- type MCPTransportType
- type MatchType
- type MemoryConsolidationResult
- type MemoryDocument
- type MemoryExport
- type MemoryItem
- type MemorySettings
- type MemoryTopic
- type MentionedItem
- type Message
- type MessageListResponse
- type MessageSearchGroupItem
- type MessageSearchMode
- type MessageSearchResult
- type MessageSuggestionItem
- type MessageSuggestionSet
- type Model
- type ModelCheckResult
- type ModelListResponse
- type ModelParameters
- type ModelProvider
- type ModelProviderListResponse
- type ModelResponse
- type ModelSlotView
- type ModelSource
- type ModelType
- type MoveKnowledgeRequest
- type MoveKnowledgeResponse
- type MoveKnowledgeToFolderRequest
- type MoveKnowledgeToFolderResponse
- type MoveTarget
- type MultimodalSlotView
- type OllamaModelInfo
- type Organization
- type OrganizationMemberResponse
- type OrganizationResponse
- type PageContext
- type ParserEngine
- type ParserEngineRule
- type PatchASRConfig
- type PatchAgentRequest
- type PatchAutoTagConfig
- type PatchChunkingConfig
- type PatchFAQConfig
- type PatchImageProcessingConfig
- type PatchIndexingStrategy
- type PatchKnowledgeBaseRequest
- type PatchVLMConfig
- type QuestionGenerationConfig
- type QuestionOrigin
- type QuestionSuggestionConfig
- type RefreshTokenResponse
- type RenameKnowledgeFolderRequest
- type RenameKnowledgeFolderResponse
- type RerankDiagnostics
- type RerankOptions
- type RerankSlotView
- type ResolveAgentPromptRequest
- type ResolveToolApprovalRequest
- type ResourceURLMode
- type ResourceURLOptions
- type ResponseType
- type RetrievalMeta
- type RetrieverEngineParams
- type RetrieverEngines
- type SSEStreamError
- type SandboxSkill
- type SandboxSkillEnv
- type SandboxSkillFile
- type SandboxSkillFileContent
- type SandboxSkillInstallResponse
- type SandboxSkillUpdate
- type SearchKnowledgeRequest
- type SearchKnowledgeResponse
- type SearchMessagesRequest
- type SearchParams
- type SearchResult
- type Session
- type SessionListOptions
- type SessionListResponse
- type SessionResponse
- type SharedAgentInfo
- type SharedKnowledgeBaseInfo
- type SkillEnvGroup
- type SkillInfo
- type SkillListResponse
- type StarterSuggestionConfig
- type StopSessionRequest
- type StorageCheckRequest
- type StorageCheckResponse
- type StorageConfig
- type StorageEngineStatusItem
- type StorageEngineStatusResponse
- type StorageProviderConfig
- type StreamResponse
- type SuggestedQuestion
- type SuggestedQuestionTagScope
- type SuggestedQuestionsRequest
- type SuggestedQuestionsResponse
- type SummaryConfig
- type SwitchTenantRequest
- type SystemInfo
- type Tag
- type TagResponse
- type TagWithStats
- type TagsPage
- type TagsResponse
- type Tenant
- type TenantAPIKey
- type TenantAPIKeyRole
- type TenantListResponse
- type TenantResponse
- type TenantSearchResponse
- type ToolCall
- type ToolResult
- type UpdateAPIPrincipalConfigRequest
- type UpdateAgentRequest
- type UpdateChunkRequest
- type UpdateImageInfoRequest
- type UpdateKnowledgeBaseRequest
- type UpdateManualKnowledgeRequest
- type UpdateModelRequest
- type UpdateOrganizationRequest
- type UpdateTagPayload
- type UpdateTenantAPIKeyRequest
- type UserInfo
- type VLMConfig
- type WebSearchProvider
Constants ¶
const ( PathAuthLogin = "/api/v1/auth/login" PathAuthRefresh = "/api/v1/auth/refresh" PathAuthSwitchTenant = "/api/v1/auth/switch-tenant" )
Canonical paths for the auth endpoints. Exposed so callers building HTTP middleware (e.g. the CLI's 401-retry transport) can classify requests without re-hardcoding the literals.
const ( ServerErrBadRequest = 1000 ServerErrForbidden = 1002 ServerErrNotFound = 1003 ServerErrMethodNotAllowed = 1004 ServerErrConflict = 1005 ServerErrTooManyRequests = 1006 ServerErrInternalServer = 1007 ServerErrTimeout = 1009 ServerErrValidation = 1010 )
Server error codes are the values of the {"code":N} field in an error response body, surfaced as APIError.Code. These mirror the generic codes in the server's internal/errors/errors.go so consumers branch on a named constant instead of a magic number. Domain-specific codes (2xxx+) are omitted until a consumer needs to branch on one.
const ( EnvSourceUnset = "unset" EnvSourceWorkspace = "workspace" EnvSourceUser = "user" )
Environment variable sources, as reported by ListMyEnvVars. The three states are distinct: a value the workspace filled in for everybody and one the caller filled in for themselves lead to different actions, and neither is "nobody has filled this in".
Variables ¶
var ErrDuplicateFile = errors.New("file already exists")
ErrDuplicateFile is returned when attempting to create a knowledge entry with a file that already exists
var ErrDuplicateURL = errors.New("URL already exists")
ErrDuplicateURL is returned when attempting to create a knowledge entry with a URL that already exists
var ErrSSEStreamTerminal = errors.New("SSE stream terminal error")
ErrSSEStreamTerminal marks a terminal response_type=error, done=true frame from an SSE stream. The stream delivered the frame to the callback before returning the error.
Functions ¶
func ExampleUsage ¶
func ExampleUsage()
ExampleUsage demonstrates the complete usage flow of the WeKnora client, including: - Creating a client instance - Creating a knowledge base - Uploading knowledge files - Creating a session - Performing question-answering - Using streaming question-answering - Managing models - Managing knowledge chunks - Getting session messages - Cleaning up resources
func IsSSEStreamError ¶
IsSSEStreamError reports whether err is a terminal SSE stream error from the SDK readers, including wrapped *SSEStreamError values and legacy fmt.Errorf("SSE stream error: ...") chains.
func NewSSEStreamError ¶
NewSSEStreamError builds the terminal SSE stream error returned by the streaming readers after delivering the error frame to the callback.
func SetDebugLevel ¶
func SetDebugLevel(level string)
SetDebugLevel replaces the SDK's internal debug logger so callers can programmatically control SDK trace output (e.g., the CLI's --log-level flag). Accepted levels: "debug" / "info" / "warn" / "error" (case- insensitive); any other value (including "") disables output entirely (writes to io.Discard).
Not safe for concurrent use while SDK calls are in flight — call once at startup before any client method is invoked.
Types ¶
type APIError ¶
type APIError struct {
StatusCode int // HTTP status (401, 404, 409, 429, 500, …)
Body string // raw response body
Code int // server's structured error code ({"code":N}); 0 when absent/non-JSON
}
APIError is a typed non-2xx HTTP response from the WeKnora API. Recover it with errors.As to branch on the HTTP status or the server's structured error code without parsing the Error() string:
var apiErr *client.APIError
if errors.As(err, &apiErr) && apiErr.StatusCode == 404 { ... }
Error() intentionally preserves the legacy "HTTP error <status>: <body>" format so existing string-matching consumers keep working unchanged.
type APIPrincipalConfig ¶
type APIPrincipalConfig struct {
Mode APIPrincipalMode `json:"mode"`
DirectHeaderName string `json:"direct_header_name"`
SignedTokenHeaderName string `json:"signed_token_header_name"`
RequireDirectHeader bool `json:"require_direct_header"`
HasHMACSecret bool `json:"has_hmac_secret"`
HMACSecret string `json:"hmac_secret,omitempty"`
}
APIPrincipalConfig describes tenant API-key principal mapping settings.
type APIPrincipalMode ¶
type APIPrincipalMode string
APIPrincipalMode controls how X-API-Key requests map to terminal principals.
const ( APIPrincipalModeTenant APIPrincipalMode = "tenant" APIPrincipalModeDirect APIPrincipalMode = "direct_header" APIPrincipalModeSignedToken APIPrincipalMode = "signed_token" )
type APIPrincipalTestToken ¶
type APIPrincipalTestToken struct {
Token string `json:"token"`
HeaderName string `json:"header_name"`
ExpiresInSeconds int `json:"expires_in_seconds"`
ExpiresAtUnix int64 `json:"expires_at_unix"`
ExternalUserID string `json:"external_user_id"`
}
APIPrincipalTestToken is a short-lived JWT signed with the tenant API principal HMAC secret.
type ASRConfig ¶
type ASRConfig struct {
Enabled bool `json:"enabled"`
ModelID string `json:"model_id"`
Language string `json:"language,omitempty"`
}
ASRConfig represents automatic speech recognition settings for audio files.
type AddSimilarQuestionsPayload ¶
type AddSimilarQuestionsPayload struct {
SimilarQuestions []string `json:"similar_questions"`
}
AddSimilarQuestionsPayload is used to add similar questions to a FAQ entry.
type Agent ¶
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"`
CreatorName string `json:"creator_name,omitempty"`
}
Agent represents an agent entity
type AgentConfig ¶
type AgentConfig struct {
AgentMode string `json:"agent_mode"`
AgentType string `json:"agent_type,omitempty"`
SystemPrompt string `json:"system_prompt"`
SystemPromptID string `json:"system_prompt_id,omitempty"`
ContextTemplate string `json:"context_template"`
ContextTemplateID string `json:"context_template_id,omitempty"`
ModelID string `json:"model_id"`
RerankModelID string `json:"rerank_model_id"`
Temperature float64 `json:"temperature"`
MaxCompletionTokens int `json:"max_completion_tokens"`
Thinking *bool `json:"thinking"`
ReasoningEffort string `json:"reasoning_effort,omitempty"`
CitationEnabled *bool `json:"citation_enabled"`
MaxIterations int `json:"max_iterations"` // -1 = unlimited
LLMCallTimeout int `json:"llm_call_timeout,omitempty"`
AllowedTools []string `json:"allowed_tools"`
MCPSelectionMode string `json:"mcp_selection_mode"`
MCPServices []string `json:"mcp_services"`
SkillsSelectionMode string `json:"skills_selection_mode"`
SelectedSkills []string `json:"selected_skills"`
KBSelectionMode string `json:"kb_selection_mode"`
KnowledgeBases []string `json:"knowledge_bases"`
RetrieveKBOnlyWhenMentioned bool `json:"retrieve_kb_only_when_mentioned"`
RetainRetrievalHistory bool `json:"retain_retrieval_history"`
ImageUploadEnabled bool `json:"image_upload_enabled"`
VLMModelID string `json:"vlm_model_id"`
AudioUploadEnabled bool `json:"audio_upload_enabled"`
ASRModelID string `json:"asr_model_id"`
ImageStorageProvider string `json:"image_storage_provider"`
SupportedFileTypes []string `json:"supported_file_types"`
DataAnalysisEnabled bool `json:"data_analysis_enabled"`
FAQPriorityEnabled bool `json:"faq_priority_enabled"`
FAQDirectAnswerThreshold float64 `json:"faq_direct_answer_threshold"`
FAQScoreBoost float64 `json:"faq_score_boost"`
WebSearchEnabled bool `json:"web_search_enabled"`
WebSearchMaxResults int `json:"web_search_max_results"`
WebSearchProviderID string `json:"web_search_provider_id,omitempty"`
WebFetchEnabled bool `json:"web_fetch_enabled"`
WebFetchTopN int `json:"web_fetch_top_n,omitempty"`
MultiTurnEnabled bool `json:"multi_turn_enabled"`
HistoryTurns int `json:"history_turns"`
EmbeddingTopK int `json:"embedding_top_k"`
KeywordThreshold float64 `json:"keyword_threshold"`
VectorThreshold float64 `json:"vector_threshold"`
RerankTopK int `json:"rerank_top_k"`
RerankThreshold float64 `json:"rerank_threshold"`
EnableQueryExpansion bool `json:"enable_query_expansion"`
EnableRewrite bool `json:"enable_rewrite"`
RewritePromptSystem string `json:"rewrite_prompt_system"`
RewritePromptUser string `json:"rewrite_prompt_user"`
QueryUnderstandModelID string `json:"query_understand_model_id,omitempty"`
FallbackStrategy string `json:"fallback_strategy"`
FallbackResponse string `json:"fallback_response"`
FallbackPrompt string `json:"fallback_prompt"`
QuestionSuggestions *QuestionSuggestionConfig `json:"question_suggestions,omitempty"`
}
AgentConfig represents the configuration for an agent. Field names and JSON tags mirror internal/types.CustomAgentConfig. An empty ReasoningEffort retains the legacy Thinking boolean semantics.
type AgentEventCallback ¶
type AgentEventCallback func(*AgentStreamResponse) error
AgentEventCallback is called for each streaming event Return error to stop processing the stream
type AgentListResponse ¶
AgentListResponse represents the API response containing a list of agents
type AgentMode ¶
type AgentMode string
AgentMode is an agent's operating mode (AgentConfig.AgentMode). It mirrors the server constants in internal/types/custom_agent.go.
func AllAgentModes ¶
func AllAgentModes() []AgentMode
AllAgentModes returns every agent operating mode the server recognises, in a stable order. Use this instead of re-typing the set so callers can't drift from the SDK.
type AgentPlaceholdersResponse ¶
type AgentPlaceholdersResponse struct {
Success bool `json:"success"`
Data map[string]json.RawMessage `json:"data"`
}
AgentPlaceholdersResponse represents the API response for placeholder definitions
type AgentQARequest ¶
type AgentQARequest struct {
Query string `json:"query"` // Required query text
KnowledgeBaseIDs []string `json:"knowledge_base_ids,omitempty"` // Optional KBs for this query
KnowledgeIDs []string `json:"knowledge_ids,omitempty"` // Optional specific knowledge IDs for this query
AgentEnabled bool `json:"agent_enabled"` // Whether to run in agent mode
AgentID string `json:"agent_id,omitempty"` // Optional custom agent ID
WebSearchEnabled bool `json:"web_search_enabled"` // Whether to enable web search
SummaryModelID string `json:"summary_model_id,omitempty"` // Optional summary model override
MentionedItems []MentionedItem `json:"mentioned_items,omitempty"` // @mentioned knowledge bases and files
DisableTitle bool `json:"disable_title,omitempty"` // Whether to disable auto title generation
MCPServiceIDs []string `json:"mcp_service_ids,omitempty"` // Optional MCP service allow list (deprecated)
Images []ImageAttachment `json:"images,omitempty"` // Attached images for multimodal chat
Channel string `json:"channel,omitempty"` // Source channel: "web", "api", "im", etc.
QuestionOrigin *QuestionOrigin `json:"question_origin,omitempty"` // Source of a picked suggested question
PageContext *PageContext `json:"page_context,omitempty"` // Page the user has open (hint only)
}
AgentQARequest agent Q&A request payload.
type AgentResponse ¶
AgentResponse represents the API response containing a single agent
type AgentResponseType ¶
type AgentResponseType string
AgentResponseType defines the type of agent response
const ( // AgentResponseTypeThinking is emitted while the agent is reasoning. AgentResponseTypeThinking AgentResponseType = "thinking" // AgentResponseTypeToolCall is emitted when the agent invokes a tool. AgentResponseTypeToolCall AgentResponseType = "tool_call" // AgentResponseTypeToolResult is emitted when a tool returns. AgentResponseTypeToolResult AgentResponseType = "tool_result" // AgentResponseTypeReferences is emitted with knowledge references. AgentResponseTypeReferences AgentResponseType = "references" // AgentResponseTypeAnswer is emitted for answer tokens. AgentResponseTypeAnswer AgentResponseType = "answer" // AgentResponseTypeReflection is emitted for agent reflection. AgentResponseTypeReflection AgentResponseType = "reflection" // AgentResponseTypeError is emitted when the agent fails. AgentResponseTypeError AgentResponseType = "error" // AgentResponseTypeComplete is emitted when the agent run has finished. AgentResponseTypeComplete AgentResponseType = "complete" // AgentResponseTypeArtifactsPending is emitted while skill-generated files // are still being collected after the answer has streamed. AgentResponseTypeArtifactsPending AgentResponseType = "artifacts_pending" )
type AgentSession ¶
type AgentSession struct {
// contains filtered or unexported fields
}
AgentSession is a wrapper for agent-based interactions
func (*AgentSession) Ask ¶
func (as *AgentSession) Ask(ctx context.Context, query string, callback AgentEventCallback) error
Ask sends a query to the agent with default agent-enabled behavior.
func (*AgentSession) AskWithRequest ¶
func (as *AgentSession) AskWithRequest( ctx context.Context, request *AgentQARequest, callback AgentEventCallback, ) error
AskWithRequest sends a customized agent request for this session.
func (*AgentSession) GetSessionID ¶
func (as *AgentSession) GetSessionID() string
GetSessionID returns the session ID
type AgentShareResponse ¶
type AgentShareResponse struct {
}
AgentShareResponse represents an agent share record in API responses
type AgentStep ¶
type AgentStep struct {
Iteration int `json:"iteration"` // Iteration number (0-indexed)
Thought string `json:"thought"` // LLM's reasoning/thinking (Think phase)
ToolCalls []ToolCall `json:"tool_calls"` // Tools called in this step (Act phase)
Timestamp time.Time `json:"timestamp"` // When this step occurred
}
AgentStep represents one iteration of the ReAct loop
type AgentStreamResponse ¶
type AgentStreamResponse struct {
ID string `json:"id"` // Unique identifier
ResponseType AgentResponseType `json:"response_type"` // Response type
Content string `json:"content,omitempty"` // Current content fragment
Done bool `json:"done"` // Whether completed
KnowledgeReferences []*SearchResult `json:"knowledge_references"` // Knowledge references
Data map[string]interface{} `json:"data,omitempty"` // Additional event data
}
AgentStreamResponse agent streaming response
type AuthCapabilities ¶
type AuthCapabilities struct {
CanCreateTenant bool `json:"can_create_tenant"`
AutoAcceptInvitation bool `json:"auto_accept_invitation"`
}
AuthCapabilities mirrors GET /auth/me capabilities for SPA feature gates.
type AuthConfigResponse ¶
type AuthConfigResponse struct {
Success bool `json:"success"`
RegistrationMode string `json:"registration_mode"`
ComplexPasswordEnabled bool `json:"complex_password_enabled"`
}
AuthConfigResponse is returned by GET /api/v1/auth/config. The endpoint is unauthenticated so the SPA can decide whether to show the register tab and which password complexity rules to apply.
type AuthMembership ¶
type AuthMembership struct {
TenantID uint64 `json:"tenant_id"`
TenantName string `json:"tenant_name,omitempty"`
Role string `json:"role"`
}
AuthMembership pairs a tenant ID with the user's role in that tenant. Mirrors types.Membership on the server.
type AuthTenant ¶
AuthTenant is the tenant projection returned alongside AuthUser.
type AuthUser ¶
type AuthUser struct {
ID string `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
Avatar string `json:"avatar,omitempty"`
TenantID uint64 `json:"tenant_id"`
IsActive bool `json:"is_active"`
CanAccessAllTenants bool `json:"can_access_all_tenants,omitempty"`
CreatedAt time.Time `json:"created_at,omitempty"`
}
AuthUser is the principal returned by /auth/login and /auth/me.
Fields mirror the server's UserInfo projection (no PasswordHash).
type AutoTagConfig ¶
type AutoTagConfig struct {
Enabled bool `json:"enabled"`
// ModelID selects the chat model used for classification. Empty falls
// back to the knowledge base's summary model.
ModelID string `json:"model_id,omitempty"`
// MaxTags caps how many existing tags one document may auto-acquire
// (1-10, defaults to 3).
MaxTags int `json:"max_tags,omitempty"`
// SkipIfTagged leaves documents that already carry tags untouched.
// Defaults to true when omitted.
SkipIfTagged *bool `json:"skip_if_tagged,omitempty"`
}
AutoTagConfig controls optional automatic association of existing knowledge base tags after a document finishes parsing. Only applies to document-type knowledge bases; disabled by default.
type BatchDownloadKnowledgeRequest ¶
type BatchDownloadKnowledgeRequest struct {
IDs []string `json:"ids"`
}
BatchDownloadKnowledgeRequest selects documents in one knowledge base for ZIP download.
type BatchUpdateKnowledgeTagsRequest ¶
type BatchUpdateKnowledgeTagsRequest struct {
Updates map[string]*string `json:"updates,omitempty"` // knowledge_id -> tag_id (nil to clear)
KBID string `json:"kb_id,omitempty"`
KnowledgeIDs []string `json:"knowledge_ids,omitempty"`
// Keep an explicit empty array on the wire; nil remains null and is rejected in the list form.
TagIDs []string `json:"tag_ids"`
}
BatchUpdateKnowledgeTagsRequest sets tags on documents. Send Updates, or KnowledgeIDs together with TagIDs. An empty TagIDs clears the tags; omitting it while KnowledgeIDs is set is rejected.
type ChangePasswordRequest ¶
type ChangePasswordRequest struct {
OldPassword string `json:"old_password"`
NewPassword string `json:"new_password"`
}
ChangePasswordRequest is the body for POST /api/v1/auth/change-password.
type ChangePasswordResponse ¶
type ChangePasswordResponse struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
}
ChangePasswordResponse is returned on successful password rotation.
type ChatHistoryKBStats ¶
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"`
}
ChatHistoryKBStats represents statistics about the chat history knowledge base
type Chunk ¶
type Chunk struct {
ID string `json:"id"` // Unique identifier of the chunk
SeqID int64 `json:"seq_id"` // Auto-increment integer ID for external API usage
KnowledgeID string `json:"knowledge_id"` // Identifier of the parent knowledge
KnowledgeBaseID string `json:"knowledge_base_id"` // ID of the knowledge base
TenantID uint64 `json:"tenant_id"` // Tenant ID
TagID string `json:"tag_id"` // Optional tag ID for categorization
Content string `json:"content"` // Text content of the chunk
ChunkIndex int `json:"chunk_index"` // Index position of chunk in the document
IsEnabled bool `json:"is_enabled"` // Whether this chunk is enabled
Status int `json:"status"` // Status of the chunk
StartAt int `json:"start_at"` // Starting position in original text
EndAt int `json:"end_at"` // Ending position in original text
PreChunkID string `json:"pre_chunk_id"` // Previous chunk ID
NextChunkID string `json:"next_chunk_id"` // Next chunk ID
ChunkType string `json:"chunk_type"` // Chunk type (text, image_ocr, etc.)
ParentChunkID string `json:"parent_chunk_id"` // Parent chunk ID
RelationChunks any `json:"relation_chunks"` // Relation chunk IDs
IndirectRelationChunks any `json:"indirect_relation_chunks"` // Indirect relation chunk IDs
Metadata any `json:"metadata"` // Metadata for the chunk
ContentHash string `json:"content_hash"` // Content hash for quick matching
ImageInfo string `json:"image_info"` // Image information
CreatedAt string `json:"created_at"` // Creation time
UpdatedAt string `json:"updated_at"` // Last update time
}
Chunk represents the information about a document chunk Chunks are the basic units of storage and indexing in the knowledge base
type ChunkListResponse ¶
type ChunkListResponse struct {
Success bool `json:"success"` // Whether operation was successful
Data []Chunk `json:"data"` // List of chunks
Total int64 `json:"total"` // Total count
Page int `json:"page"` // Current page
PageSize int `json:"page_size"` // Items per page
}
ChunkListResponse represents the response for a list of chunks API response structure for returning a list of chunks
type ChunkResponse ¶
type ChunkResponse struct {
Success bool `json:"success"` // Whether operation was successful
Data Chunk `json:"data"` // Chunk data
}
ChunkResponse represents the response for a single chunk API response structure containing a single chunk information
type ChunkingConfig ¶
type ChunkingConfig struct {
ChunkSize int `json:"chunk_size"` // Chunk size
ChunkOverlap int `json:"chunk_overlap"` // Overlap size
Separators []string `json:"separators"` // Separators
// ParserEngineRules selects the parser engine for each group of file types.
ParserEngineRules []ParserEngineRule `json:"parser_engine_rules,omitempty"`
}
ChunkingConfig represents document chunking configuration
type ClearKnowledgeBaseContentsResponse ¶
type ClearKnowledgeBaseContentsResponse struct {
DeletedCount int `json:"deleted_count"`
}
ClearKnowledgeBaseContentsResponse represents the response from clear knowledge base contents API
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the client for interacting with the WeKnora service.
Authentication uses one of two credential kinds:
- API key (long-lived, set via X-API-Key) — see WithAPIKey
- Bearer JWT (short-lived, set via Authorization)— see WithBearerToken
Both may be configured simultaneously; X-API-Key takes precedence at the HTTP layer. The legacy WithToken is kept as an alias for WithAPIKey for two minor versions of compatibility.
func NewClient ¶
func NewClient(baseURL string, options ...ClientOption) *Client
NewClient creates a new client instance
func (*Client) AddSimilarQuestions ¶
func (c *Client) AddSimilarQuestions(ctx context.Context, knowledgeBaseID string, entrySeqID int64, payload *AddSimilarQuestionsPayload, ) (*FAQEntry, error)
AddSimilarQuestions adds similar questions to a FAQ entry. This will append the new questions to the existing similar questions list.
func (*Client) AgentQAStream ¶
func (c *Client) AgentQAStream(ctx context.Context, sessionID string, query string, callback AgentEventCallback) error
AgentQAStream performs agent-based Q&A with SSE streaming using default agent settings. Deprecated: prefer AgentQAStreamWithRequest to customize agent behavior.
func (*Client) AgentQAStreamWithRequest ¶
func (c *Client) AgentQAStreamWithRequest(ctx context.Context, sessionID string, request *AgentQARequest, callback AgentEventCallback, opts ...ResourceURLOptions, ) error
AgentQAStreamWithRequest performs agent-based Q&A with SSE streaming using the full request payload. Pass ResourceURLOptions to receive public HTTP(S) file URLs in the stream. An unfinished SSE data frame at EOF returns an error wrapping io.ErrUnexpectedEOF.
func (*Client) BatchDeleteSessions ¶
BatchDeleteSessions deletes multiple sessions by their IDs.
func (*Client) BatchUpdateKnowledgeTags ¶
BatchUpdateKnowledgeTags batch updates knowledge tags. The updates map contains knowledge_id -> tag_id mappings. Set tag_id to nil to clear the tag.
func (*Client) CancelKnowledgeParse ¶
CancelKnowledgeParse cancels an in-progress knowledge parse. The server marks the knowledge as cancelled and best-effort dequeues any pending downstream tasks (multimodal, post-process, summary, question generation, graph extract) for the same knowledge ID. Any chunks/index already written are preserved; the user can re-trigger parsing later via ReparseKnowledge.
Cancellable parse_status values:
- pending — task has not started
- processing — DocReader / chunking / embedding stage
- finalizing — primary parse done, enrichment subtasks (summary, question generation, graph extract) still running
Returns an error when the knowledge is in a terminal state (completed, failed) or already being deleted.
Parameters:
- ctx: Context for the request
- knowledgeID: The ID of the knowledge entry whose parse should be cancelled
Returns:
- *Knowledge: The updated knowledge entry with status set to "cancelled"
- error: Error information if the request fails
Example:
knowledge, err := client.CancelKnowledgeParse(ctx, "knowledge-id-123")
if err != nil {
log.Fatalf("Failed to cancel parse: %v", err)
}
fmt.Printf("Knowledge parse cancelled, status: %s\n", knowledge.ParseStatus)
func (*Client) ChangePassword ¶
func (c *Client) ChangePassword(ctx context.Context, req ChangePasswordRequest) (*ChangePasswordResponse, error)
ChangePassword rotates the caller's password. On success every outstanding session is revoked server-side; callers should discard local tokens. Maps to POST /api/v1/auth/change-password.
func (*Client) CheckOllamaModels ¶
CheckOllamaModels checks if specific Ollama models are available
func (*Client) CheckOllamaStatus ¶
CheckOllamaStatus checks if Ollama is running and accessible
func (*Client) CheckParserEngines ¶
CheckParserEngines checks parser engine availability with given config overrides
func (*Client) CheckRemoteModel ¶
func (c *Client) CheckRemoteModel(ctx context.Context, params map[string]string) (*ModelCheckResult, error)
CheckRemoteModel checks if a remote model API is accessible
func (*Client) CheckRerankModel ¶
func (c *Client) CheckRerankModel(ctx context.Context, params map[string]string) (*ModelCheckResult, error)
CheckRerankModel checks if a rerank model is accessible
func (*Client) CheckStorageEngine ¶
func (c *Client) CheckStorageEngine(ctx context.Context, req *StorageCheckRequest) (*StorageCheckResponse, error)
CheckStorageEngine tests connectivity for a storage engine
func (*Client) ClearKnowledgeBaseContents ¶
func (c *Client) ClearKnowledgeBaseContents(ctx context.Context, knowledgeBaseID string) (*ClearKnowledgeBaseContentsResponse, error)
ClearKnowledgeBaseContents deletes all knowledge entries in a knowledge base (async). The knowledge base itself is preserved; only its contents are removed.
func (*Client) ClearMemoryItems ¶
ClearMemoryItems permanently deletes every memory belonging to the caller.
func (*Client) ConfirmMemoryItem ¶
ConfirmMemoryItem accepts an inferred (pending) memory so it starts taking effect.
func (*Client) ConsolidateMemory ¶
func (c *Client) ConsolidateMemory(ctx context.Context) (*MemoryConsolidationResult, error)
ConsolidateMemory merges near-duplicate items and archives expired ones without waiting for the daily background pass.
func (*Client) ContinueStream ¶
func (c *Client) ContinueStream( ctx context.Context, sessionID string, messageID string, callback func(*StreamResponse) error, opts ...ResourceURLOptions, ) error
ContinueStream continues to receive an active stream for a session. Pass ResourceURLOptions to receive public HTTP(S) file URLs in the stream. An unfinished SSE data frame at EOF returns an error wrapping io.ErrUnexpectedEOF.
func (*Client) CopyKnowledgeBase ¶
func (c *Client) CopyKnowledgeBase(ctx context.Context, request *CopyKnowledgeBaseRequest) (*CopyKnowledgeBaseResponse, error)
CopyKnowledgeBase copies a knowledge base asynchronously and returns task info
func (*Client) CreateAPIPrincipalTestToken ¶
func (c *Client) CreateAPIPrincipalTestToken( ctx context.Context, tenantID uint64, req *CreateAPIPrincipalTestTokenRequest, ) (*APIPrincipalTestToken, error)
CreateAPIPrincipalTestToken signs a short-lived JWT with the tenant API principal HMAC secret.
func (*Client) CreateAgent ¶
CreateAgent creates a new custom agent
func (*Client) CreateFAQEntry ¶
func (c *Client) CreateFAQEntry(ctx context.Context, knowledgeBaseID string, payload *FAQEntryPayload, ) (*FAQEntry, error)
CreateFAQEntry creates a single FAQ entry synchronously.
func (*Client) CreateKnowledgeBase ¶
func (c *Client) CreateKnowledgeBase(ctx context.Context, knowledgeBase *KnowledgeBase) (*KnowledgeBase, error)
CreateKnowledgeBase creates a knowledge base
func (*Client) CreateKnowledgeFromFile ¶
func (c *Client) CreateKnowledgeFromFile(ctx context.Context, knowledgeBaseID string, filePath string, metadata map[string]string, enableMultimodel *bool, customFileName string, channel string, processConfig *KnowledgeProcessOverrides, ) (*Knowledge, error)
CreateKnowledgeFromFile creates a knowledge entry from a local file path Parameters:
- knowledgeBaseID: The ID of the knowledge base
- filePath: The local file path
- metadata: Optional metadata for the knowledge entry
- enableMultimodel: Optional flag to enable multimodal processing
- customFileName: Optional custom file name (useful for folder uploads with path)
- channel: Optional ingestion channel (e.g. "web", "api", "wechat"); empty defaults to "web"
- processConfig: Optional parse config overrides (serialized as process_config form field)
func (*Client) CreateKnowledgeFromURL ¶
func (c *Client) CreateKnowledgeFromURL( ctx context.Context, knowledgeBaseID string, req CreateKnowledgeFromURLRequest, ) (*Knowledge, error)
CreateKnowledgeFromURL creates a knowledge entry from a URL. When req.FileName or req.FileType is provided (or the URL path has a known file extension), the server automatically switches to file-download mode instead of web-page crawling.
func (*Client) CreateMCPEndpoint ¶
func (c *Client) CreateMCPEndpoint(ctx context.Context, req *MCPEndpointRequest) (*MCPEndpoint, error)
CreateMCPEndpoint publishes a new endpoint. The returned Token is shown once.
func (*Client) CreateMCPService ¶
func (c *Client) CreateMCPService(ctx context.Context, service *MCPService) (*MCPService, error)
CreateMCPService creates a new MCP service
func (*Client) CreateManualKnowledge ¶
func (c *Client) CreateManualKnowledge(ctx context.Context, knowledgeBaseID string, request *CreateManualKnowledgeRequest) (*Knowledge, error)
CreateManualKnowledge creates a knowledge entry from manual Markdown content.
func (*Client) CreateMemoryItem ¶
func (c *Client) CreateMemoryItem(ctx context.Context, kind, content string, importance int) (*MemoryItem, error)
CreateMemoryItem manually adds a long-term memory. kind is one of profile / preference / fact / task / interest.
func (*Client) CreateModel ¶
CreateModel creates a model
func (*Client) CreateOrganization ¶
func (c *Client) CreateOrganization(ctx context.Context, req *CreateOrganizationRequest) (*OrganizationResponse, error)
CreateOrganization creates a new organization
func (*Client) CreateSession ¶
func (c *Client) CreateSession(ctx context.Context, request *CreateSessionRequest) (*Session, error)
CreateSession creates a session
func (*Client) CreateTag ¶
func (c *Client) CreateTag(ctx context.Context, knowledgeBaseID string, payload *CreateTagPayload, ) (*Tag, error)
CreateTag creates a new tag under a knowledge base.
func (*Client) CreateTenant ¶
CreateTenant creates a new tenant
func (*Client) CreateTenantAPIKey ¶
func (c *Client) CreateTenantAPIKey( ctx context.Context, tenantID uint64, req *CreateTenantAPIKeyRequest, ) (*CreatedTenantAPIKey, error)
CreateTenantAPIKey creates a scoped API key.
func (*Client) DeleteAgent ¶
DeleteAgent deletes a custom agent by its ID
func (*Client) DeleteChunk ¶
DeleteChunk deletes a specific chunk Deletes a specific chunk under a knowledge document Parameters:
- ctx: Context
- knowledgeID: Knowledge ID
- chunkID: Chunk ID
Returns:
- error: Error information
func (*Client) DeleteChunksByKnowledgeID ¶
DeleteChunksByKnowledgeID deletes all chunks under a knowledge document Batch deletes all chunks under the specified knowledge document Parameters:
- ctx: Context
- knowledgeID: Knowledge ID
Returns:
- error: Error information
func (*Client) DeleteFAQEntries ¶
DeleteFAQEntries deletes FAQ entries in bulk by seq_id.
func (*Client) DeleteGeneratedQuestion ¶
func (c *Client) DeleteGeneratedQuestion(ctx context.Context, chunkID string, questionID string) error
DeleteGeneratedQuestion deletes a generated question from a chunk
func (*Client) DeleteKnowledge ¶
DeleteKnowledge enqueues an asynchronous delete for the given knowledge entry. The server returns 200 once the task has been submitted; the actual deletion is performed by a background worker (same pipeline as BatchDeleteKnowledge).
func (*Client) DeleteKnowledgeBase ¶
DeleteKnowledgeBase deletes a knowledge base
func (*Client) DeleteMCPEndpoint ¶
DeleteMCPEndpoint deletes an endpoint; connected clients lose access immediately.
func (*Client) DeleteMCPService ¶
DeleteMCPService deletes an MCP service
func (*Client) DeleteMemoryDocument ¶
DeleteMemoryDocument stops using one document for personalized retrieval.
func (*Client) DeleteMemoryItem ¶
DeleteMemoryItem permanently removes one memory.
func (*Client) DeleteMemoryTopic ¶
DeleteMemoryTopic stops tracking a topic that has not been promoted yet.
func (*Client) DeleteMessage ¶
DeleteMessage deletes a message
func (*Client) DeleteModel ¶
DeleteModel deletes a model
func (*Client) DeleteMySandboxEnvVar ¶
DeleteMySandboxEnvVar removes the caller's own config-wide variable.
func (*Client) DeleteMySkillEnvVar ¶
DeleteMySkillEnvVar removes the caller's own value. The workspace-wide value, if there is one, applies again afterwards. Deleting a value that was never set returns a 404. Clearing is a delete rather than a write of "", so there is one unambiguous way to revoke.
func (*Client) DeleteOrganization ¶
DeleteOrganization deletes an organization
func (*Client) DeleteSession ¶
DeleteSession deletes a session
func (*Client) DeleteTag ¶
func (c *Client) DeleteTag(ctx context.Context, knowledgeBaseID, tagID string, force bool, contentOnly bool, excludeIDs []int64, ) error
DeleteTag deletes a tag. tagID can be either UUID or seq_id (as string). Set force to true to delete even if the tag is referenced. Set contentOnly to true to only delete the content under the tag but keep the tag itself. excludeIDs: seq_ids of chunks to exclude from deletion.
func (*Client) DeleteTagBySeqID ¶
func (c *Client) DeleteTagBySeqID(ctx context.Context, knowledgeBaseID string, tagSeqID int64, force bool, contentOnly bool, excludeIDs []int64, ) error
DeleteTagBySeqID deletes a tag by seq_id.
func (*Client) DeleteTenant ¶
DeleteTenant removes a tenant by ID
func (*Client) DeleteTenantAPIKey ¶
DeleteTenantAPIKey revokes a tenant API key.
func (*Client) DownloadKnowledgeFile ¶
func (c *Client) DownloadKnowledgeFile(ctx context.Context, knowledgeID string, destPath string) error
DownloadKnowledgeFile downloads a knowledge file to the specified local path. The destination is replaced only after the download completes successfully. Failed downloads preserve an existing file and remove temporary data.
Callers wanting more control (stream to stdout, validate filename before touching disk) should use OpenKnowledgeFile and io.Copy directly.
func (*Client) DownloadKnowledgeFiles ¶
func (c *Client) DownloadKnowledgeFiles(ctx context.Context, knowledgeBaseID string, ids []string, destPath string) error
DownloadKnowledgeFiles downloads a ZIP of original files for the given knowledge IDs to destPath. Failed downloads preserve an existing file and remove temporary data.
func (*Client) DownloadOllamaModel ¶
DownloadOllamaModel starts downloading an Ollama model
func (*Client) DuplicateKnowledgeBase ¶
func (c *Client) DuplicateKnowledgeBase( ctx context.Context, knowledgeBaseID string, ) (*DuplicateKnowledgeBaseResponse, error)
DuplicateKnowledgeBase creates a settings-only duplicate and returns the new knowledge base info.
func (*Client) EnsureMessageSuggestions ¶
func (*Client) ExportFAQEntries ¶
ExportFAQEntries exports all FAQ entries from a knowledge base as CSV data. The CSV format matches the import example format with 8 columns: 分类(必填), 问题(必填), 相似问题(选填-多个用##分隔), 反例问题(选填-多个用##分隔), 机器人回答(必填-多个用##分隔), 是否全部回复(选填-默认FALSE), 是否停用(选填-默认FALSE), 是否禁止被推荐(选填-默认False 可被推荐)
func (*Client) ExportMemory ¶
func (c *Client) ExportMemory(ctx context.Context) (*MemoryExport, error)
ExportMemory downloads a JSON snapshot of every memory belonging to the caller. Truncated is true only if the safety ceiling clipped the file.
func (*Client) ExtractTextRelations ¶
ExtractTextRelations extracts text relations for knowledge graph
func (*Client) FilterKnowledge ¶
func (c *Client) FilterKnowledge(ctx context.Context, keyword string, offset, limit int, fileTypes []string, agentID string) ([]Knowledge, bool, error)
FilterKnowledge searches/filters knowledge entries across knowledge bases
func (*Client) GenerateInviteCode ¶
GenerateInviteCode generates a new invite code for an organization
func (*Client) GenerateTitle ¶
func (c *Client) GenerateTitle(ctx context.Context, sessionID string, request *GenerateTitleRequest) (string, error)
GenerateTitle generates a session title
func (*Client) GetAPIPrincipalConfig ¶
func (c *Client) GetAPIPrincipalConfig(ctx context.Context, tenantID uint64) (*APIPrincipalConfig, error)
GetAPIPrincipalConfig returns how X-API-Key requests map to principals for a tenant.
func (*Client) GetAgentPlaceholders ¶
GetAgentPlaceholders retrieves all available prompt placeholder definitions
func (*Client) GetAuthConfig ¶
func (c *Client) GetAuthConfig(ctx context.Context) (*AuthConfigResponse, error)
GetAuthConfig fetches public authentication settings. Maps to GET /api/v1/auth/config.
func (*Client) GetChatHistoryKBStats ¶
func (c *Client) GetChatHistoryKBStats(ctx context.Context) (*ChatHistoryKBStats, error)
GetChatHistoryKBStats gets chat history knowledge base statistics
func (*Client) GetChunkByIDOnly ¶
GetChunkByIDOnly retrieves a chunk by its ID without requiring knowledge ID
func (*Client) GetCurrentUser ¶
func (c *Client) GetCurrentUser(ctx context.Context) (*CurrentUserResponse, error)
GetCurrentUser returns the currently authenticated principal and the tenant projection. Maps to GET /api/v1/auth/me; the bearer token must already be set on the client (use WithBearerToken).
Used by `weknora auth status` and `weknora whoami`.
func (*Client) GetDeploymentCapabilities ¶
func (c *Client) GetDeploymentCapabilities(ctx context.Context) (*DeploymentCapabilitiesData, error)
GetDeploymentCapabilities returns the deployment feature snapshot for SPA menu gating.
func (*Client) GetEvaluationResult ¶
GetEvaluationResult retrieves evaluation results Retrieves detailed results for an evaluation task by task ID Parameters:
- ctx: Context, used for passing request context information
- taskID: Evaluation task ID, used to identify the specific evaluation task to query
Returns:
- *EvaluationResult: Detailed evaluation task results
- error: Error information if the request fails
func (*Client) GetFAQEntry ¶
func (c *Client) GetFAQEntry(ctx context.Context, knowledgeBaseID string, entrySeqID int64, ) (*FAQEntry, error)
GetFAQEntry retrieves a single FAQ entry by seq_id.
func (*Client) GetFAQImportProgress ¶
func (c *Client) GetFAQImportProgress(ctx context.Context, taskID string) (*FAQImportProgress, error)
GetFAQImportProgress retrieves the progress of an async FAQ import task. This works for both regular imports and dry run validations.
func (*Client) GetInitializationConfig ¶
func (c *Client) GetInitializationConfig(ctx context.Context, kbID string) (*KBModelConfigView, error)
GetInitializationConfig returns a knowledge base's model configuration as a secret-free KBModelConfigView. The server response nests config under embedding/llm/rerank/multimodal and includes provider apiKey/baseUrl; this parses ONLY the non-secret fields (apiKey/baseUrl are never read into the struct, so they cannot leak through the CLI) and remaps to snake_case.
func (*Client) GetKBCloneProgress ¶
GetKBCloneProgress gets the progress of a knowledge base clone task
func (*Client) GetKnowledge ¶
GetKnowledge retrieves a knowledge entry by its ID
func (*Client) GetKnowledgeBase ¶
func (c *Client) GetKnowledgeBase(ctx context.Context, knowledgeBaseID string) (*KnowledgeBase, error)
GetKnowledgeBase gets a knowledge base
func (*Client) GetKnowledgeBatch ¶
GetKnowledgeBatch retrieves multiple knowledge entries by their IDs
func (*Client) GetKnowledgeMoveProgress ¶
func (c *Client) GetKnowledgeMoveProgress(ctx context.Context, taskID string) (*KnowledgeMoveProgress, error)
GetKnowledgeMoveProgress gets the progress of a knowledge move task
func (*Client) GetKnowledgeProcessingSpans ¶
func (c *Client) GetKnowledgeProcessingSpans( ctx context.Context, knowledgeID string, attempt int, ) (*KnowledgeProcessingTrace, error)
GetKnowledgeProcessingSpans fetches the document-parsing trace tree for a knowledge entry. The response always contains the five canonical stages; stages that have not produced rows yet are synthesized as "pending" placeholders so the timeline is stable to render.
Parameters:
- ctx: Context for the request
- knowledgeID: The ID of the knowledge entry
- attempt: A specific parse attempt number; pass 0 for the latest attempt
Returns:
- *KnowledgeProcessingTrace: The trace for the selected attempt
- error: Error information if the request fails
Example:
trace, err := client.GetKnowledgeProcessingSpans(ctx, "knowledge-id-123", 0)
if err != nil {
log.Fatalf("Failed to get parsing trace: %v", err)
}
fmt.Printf("parse_status=%s current_stage=%s\n", trace.ParseStatus, trace.CurrentStage)
func (*Client) GetMCPEndpoint ¶
GetMCPEndpoint returns one endpoint.
func (*Client) GetMCPEndpointToolCatalog ¶
func (c *Client) GetMCPEndpointToolCatalog(ctx context.Context) (*MCPEndpointToolCatalog, error)
GetMCPEndpointToolCatalog returns the tools an endpoint may expose.
func (*Client) GetMCPMetadata ¶
GetMCPMetadata reads the saved tool directory without connecting upstream. Server route: GET /api/v1/mcp-services/{id}/metadata.
func (*Client) GetMCPService ¶
GetMCPService gets an MCP service by ID
func (*Client) GetMCPServiceResources ¶
func (c *Client) GetMCPServiceResources(ctx context.Context, serviceID string) ([]*MCPResource, error)
GetMCPServiceResources gets the resources provided by an MCP service
func (*Client) GetMCPServiceTools ¶
GetMCPServiceTools gets the tools provided by an MCP service
func (*Client) GetMemorySettings ¶
func (c *Client) GetMemorySettings(ctx context.Context) (*MemorySettings, error)
GetMemorySettings returns the merged workspace + personal memory switch.
func (*Client) GetMessageSuggestions ¶
func (*Client) GetMessagesBefore ¶
func (c *Client) GetMessagesBefore( ctx context.Context, sessionID string, beforeTime time.Time, limit int, ) ([]Message, error)
GetMessagesBefore gets messages before a specified time
func (*Client) GetOllamaDownloadProgress ¶
func (c *Client) GetOllamaDownloadProgress(ctx context.Context, taskID string) (*DownloadTask, error)
GetOllamaDownloadProgress gets the download progress of an Ollama model
func (*Client) GetOrganization ¶
GetOrganization gets an organization by ID
func (*Client) GetRecentMessages ¶
func (c *Client) GetRecentMessages(ctx context.Context, sessionID string, limit int) ([]Message, error)
GetRecentMessages gets recent messages from a session
func (*Client) GetSandboxSkillFile ¶
func (c *Client) GetSandboxSkillFile( ctx context.Context, configID, skillID, filePath string, ) (*SandboxSkillFileContent, error)
GetSandboxSkillFile reads one skill-root-relative file from an installed skill.
func (*Client) GetSession ¶
GetSession gets a session
func (*Client) GetSessionsByTenant ¶
func (c *Client) GetSessionsByTenant( ctx context.Context, page int, pageSize int, opts ...SessionListOptions, ) ([]Session, int, error)
GetSessionsByTenant gets normal sessions unless an explicit kind is requested.
func (*Client) GetStorageEngineStatus ¶
func (c *Client) GetStorageEngineStatus(ctx context.Context) (*StorageEngineStatusResponse, error)
GetStorageEngineStatus gets the availability status of all storage engines
func (*Client) GetSuggestedQuestions ¶
func (c *Client) GetSuggestedQuestions(ctx context.Context, agentID string, request *SuggestedQuestionsRequest) ([]SuggestedQuestion, error)
GetSuggestedQuestions retrieves suggested questions for the given agent, based on its associated knowledge bases. The returned questions can be displayed as quick-start prompts in the chat UI.
When request is nil, uses the agent's default knowledge base configuration.
func (*Client) GetSystemInfo ¶
func (c *Client) GetSystemInfo(ctx context.Context) (*SystemInfo, error)
GetSystemInfo gets system version and configuration information
func (*Client) GetTenantKV ¶
GetTenantKV retrieves a tenant KV configuration by key
func (*Client) GetWebSearchProviders ¶
GetWebSearchProviders returns the list of available web search providers
func (*Client) HybridSearch ¶
func (c *Client) HybridSearch( ctx context.Context, knowledgeBaseID string, params *SearchParams, opts ...ResourceURLOptions, ) ([]*SearchResult, error)
HybridSearch performs hybrid search. Pass ResourceURLOptions to receive public HTTP(S) file URLs in results.
func (*Client) HybridSearchDetailed ¶
func (c *Client) HybridSearchDetailed( ctx context.Context, knowledgeBaseID string, params *SearchParams, opts ...ResourceURLOptions, ) (*HybridSearchResponse, error)
HybridSearchDetailed performs hybrid search and returns the whole response, including the rerank diagnostics in Meta.
func (*Client) InitializeByKB ¶
func (c *Client) InitializeByKB(ctx context.Context, kbID string, config *InitializationConfig) error
InitializeByKB initializes a knowledge base with model configuration
func (*Client) InstallSandboxSkillFromSource ¶
func (c *Client) InstallSandboxSkillFromSource( ctx context.Context, configID, source string, ) (string, error)
InstallSandboxSkillFromSource installs a skill onto a sandbox config from a public locator. Use "@owner/slug" (ClawHub), a github.com / gitlab.com / skills.sh / skillhub URL, a ClawHub skills-sh catalog page (https://clawhub.ai/skills-sh/owner/repo/slug), a skills-sh:owner/repo/slug locator, or a direct zip/SKILL.md URL. Bare "owner/slug" is rejected as ambiguous. The call is accepted asynchronously; follow progress on the skill ID.
func (*Client) InviteMember ¶
InviteMember directly invites a user to an organization (admin only)
func (*Client) JoinByOrganizationID ¶
JoinByOrganizationID joins a searchable organization by its ID
func (*Client) JoinOrganizationByInviteCode ¶
JoinOrganizationByInviteCode joins an organization using an invite code
func (*Client) KnowledgeQAStream ¶
func (c *Client) KnowledgeQAStream( ctx context.Context, sessionID string, request *KnowledgeQARequest, callback func(*StreamResponse) error, opts ...ResourceURLOptions, ) error
KnowledgeQAStream knowledge Q&A streaming API. Pass ResourceURLOptions to receive public HTTP(S) file URLs in the stream. An unfinished SSE data frame at EOF returns an error wrapping io.ErrUnexpectedEOF.
func (*Client) LeaveOrganization ¶
LeaveOrganization leaves an organization
func (*Client) ListAgentShares ¶
ListAgentShares lists shares of an agent
func (*Client) ListAgents ¶
ListAgents retrieves all agents for the current tenant
func (*Client) ListAllTenants ¶
ListAllTenants retrieves all tenants in the system (requires cross-tenant access)
func (*Client) ListFAQEntries ¶
func (c *Client) ListFAQEntries(ctx context.Context, knowledgeBaseID string, page, pageSize int, tagSeqID int64, keyword string, searchField string, sortOrder string, ) (*FAQEntriesPage, error)
ListFAQEntries returns paginated FAQ entries under a knowledge base. tagSeqID: filter by tag seq_id (0 means no filter) searchField: specifies which field to search in ("standard_question", "similar_questions", "answers", "" for all) sortOrder: "asc" for time ascending (updated_at ASC), default is time descending (updated_at DESC)
func (*Client) ListJoinRequests ¶
ListJoinRequests lists pending join requests (admin only)
func (*Client) ListKBShares ¶
func (c *Client) ListKBShares(ctx context.Context, kbID string) ([]KnowledgeBaseShareResponse, error)
ListKBShares lists shares of a knowledge base
func (*Client) ListKnowledge ¶
func (c *Client) ListKnowledge(ctx context.Context, knowledgeBaseID string, page int, pageSize int, tagID string, ) ([]Knowledge, int64, error)
ListKnowledge lists knowledge entries in a knowledge base with pagination. For richer filtering (keyword, file type, parse status, source, time range) use ListKnowledgeWithFilter.
func (*Client) ListKnowledgeBases ¶
func (c *Client) ListKnowledgeBases(ctx context.Context) ([]KnowledgeBase, error)
ListKnowledgeBases lists knowledge bases
func (*Client) ListKnowledgeChunks ¶
func (c *Client) ListKnowledgeChunks(ctx context.Context, knowledgeID string, page int, pageSize int, chunkTypes ...string, ) ([]Chunk, int64, error)
ListKnowledgeChunks lists all chunks under a knowledge document Queries all chunks by knowledge ID with pagination support Parameters:
- ctx: Context
- knowledgeID: Knowledge ID
- page: Page number, starts from 1
- pageSize: Number of items per page
- chunkTypes: Optional chunk type filter (e.g. "text", "image_caption", "image_ocr"). When empty, the server defaults to text chunks only.
Returns:
- []Chunk: List of chunks
- int64: Total count
- error: Error information
func (*Client) ListKnowledgeFolders ¶
func (c *Client) ListKnowledgeFolders(ctx context.Context, knowledgeBaseID string) (*KnowledgeFolderTree, error)
ListKnowledgeFolders returns the folder hierarchy of a knowledge base.
func (*Client) ListKnowledgeWithFilter ¶
func (c *Client) ListKnowledgeWithFilter(ctx context.Context, knowledgeBaseID string, page int, pageSize int, filter KnowledgeListFilter, ) ([]Knowledge, int64, error)
ListKnowledgeWithFilter lists knowledge entries with the full filter surface.
func (*Client) ListMCPEndpoints ¶
func (c *Client) ListMCPEndpoints(ctx context.Context) ([]*MCPEndpoint, error)
ListMCPEndpoints lists the workspace's MCP endpoints (tokens are never included).
func (*Client) ListMCPServices ¶
func (c *Client) ListMCPServices(ctx context.Context) ([]*MCPService, error)
ListMCPServices lists all MCP services for the current tenant
func (*Client) ListMemoryDocuments ¶
func (c *Client) ListMemoryDocuments(ctx context.Context, limit, offset int) ([]*MemoryDocument, int64, error)
ListMemoryDocuments pages through documents this person keeps citing.
func (*Client) ListMemoryItems ¶
func (c *Client) ListMemoryItems(ctx context.Context, status string, limit, offset int) ([]*MemoryItem, int64, error)
ListMemoryItems pages through the caller's memories. status may be empty (all) or one of active / superseded / archived / pending.
func (*Client) ListMemoryTopics ¶
func (c *Client) ListMemoryTopics(ctx context.Context, limit, offset int) ([]*MemoryTopic, int64, error)
ListMemoryTopics pages through subjects the extractor is still counting.
func (*Client) ListModelProviders ¶
ListModelProviders retrieves the list of supported model providers. modelType is optional and can be used to filter by type: "chat", "embedding", "rerank", "vllm".
func (*Client) ListModels ¶
ListModels lists all models
func (*Client) ListMoveTargets ¶
func (c *Client) ListMoveTargets(ctx context.Context, knowledgeBaseID string) ([]KnowledgeBase, error)
ListMoveTargets lists knowledge bases eligible as move targets for the given source KB
func (*Client) ListMyEnvVars ¶
func (c *Client) ListMyEnvVars(ctx context.Context) ([]ConfigEnvGroup, error)
ListMyEnvVars returns every sandbox config of the workspace with the caller's own config-wide variables and the credentials its skills declared, each reporting whether it is unset, filled in workspace-wide, or filled in by the caller. Values are never returned.
Values are stored per calling identity, not per user: a run driven by an API key does not see values entered through the web UI, and vice versa. Use SetSandboxSkillEnvValues for a credential that should apply to everybody.
func (*Client) ListMyOrganizations ¶
func (c *Client) ListMyOrganizations(ctx context.Context) ([]OrganizationResponse, error)
ListMyOrganizations lists organizations the current user belongs to
func (*Client) ListOllamaDownloadTasks ¶
func (c *Client) ListOllamaDownloadTasks(ctx context.Context) ([]*DownloadTask, error)
ListOllamaDownloadTasks lists all Ollama download tasks
func (*Client) ListOllamaModels ¶
func (c *Client) ListOllamaModels(ctx context.Context) ([]OllamaModelInfo, error)
ListOllamaModels lists all locally available Ollama models
func (*Client) ListOrgAgentShares ¶
func (c *Client) ListOrgAgentShares(ctx context.Context, orgID string) ([]AgentShareResponse, error)
ListOrgAgentShares lists agents shared to an organization
func (*Client) ListOrgMembers ¶
func (c *Client) ListOrgMembers(ctx context.Context, orgID string) ([]OrganizationMemberResponse, error)
ListMembers lists members of an organization
func (*Client) ListOrgShares ¶
func (c *Client) ListOrgShares(ctx context.Context, orgID string) ([]KnowledgeBaseShareResponse, error)
ListOrgShares lists knowledge bases shared to an organization
func (*Client) ListParserEngines ¶
func (c *Client) ListParserEngines(ctx context.Context) ([]ParserEngine, error)
ListParserEngines lists available document parser engines
func (*Client) ListSandboxSkillFiles ¶
func (c *Client) ListSandboxSkillFiles( ctx context.Context, configID, skillID string, ) ([]SandboxSkillFile, error)
ListSandboxSkillFiles lists the stored archive of one installed skill.
func (*Client) ListSharedAgents ¶
func (c *Client) ListSharedAgents(ctx context.Context) ([]SharedAgentInfo, error)
ListSharedAgents lists all agents shared to the current user
func (*Client) ListSharedKnowledgeBases ¶
func (c *Client) ListSharedKnowledgeBases(ctx context.Context) ([]SharedKnowledgeBaseInfo, error)
ListSharedKnowledgeBases lists all knowledge bases shared to the current user
func (*Client) ListSkills ¶
ListSkills lists the installed skills a chat turn can invoke on one sandbox config. An empty sandboxConfigID returns an empty list.
func (*Client) ListTags ¶
func (c *Client) ListTags(ctx context.Context, knowledgeBaseID string, page, pageSize int, keyword string, ) (*TagsPage, error)
ListTags returns paginated tags under a knowledge base.
func (*Client) ListTenantAPIKeys ¶
ListTenantAPIKeys lists API keys for a tenant.
func (*Client) ListTenants ¶
ListTenants retrieves all tenants
func (*Client) LoadMessages ¶
func (c *Client) LoadMessages( ctx context.Context, sessionID string, limit int, beforeTime *time.Time, opts ...ResourceURLOptions, ) ([]Message, error)
LoadMessages loads session messages, supports pagination and time filtering. Pass ResourceURLOptions to request public HTTP(S) file URLs instead of resource:// handles.
func (*Client) Login ¶
func (c *Client) Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)
Login authenticates with email + password and returns the JWT access token, refresh token, and principal info. Maps to POST /api/v1/auth/login.
Used by `weknora auth login`.
func (*Client) MoveKnowledge ¶
func (c *Client) MoveKnowledge(ctx context.Context, req *MoveKnowledgeRequest) (*MoveKnowledgeResponse, error)
MoveKnowledge moves knowledge items from one knowledge base to another (async task)
func (*Client) MoveKnowledgeToFolder ¶
func (c *Client) MoveKnowledgeToFolder(ctx context.Context, req *MoveKnowledgeToFolderRequest) (*MoveKnowledgeToFolderResponse, error)
MoveKnowledgeToFolder updates folder_path for the given knowledge entries. An empty FolderPath moves documents back to the knowledge base root.
func (*Client) NewAgentSession ¶
func (c *Client) NewAgentSession(sessionID string) *AgentSession
NewAgentSession creates a new agent session wrapper
func (*Client) OpenKnowledgeFile ¶
func (c *Client) OpenKnowledgeFile(ctx context.Context, knowledgeID string) (string, io.ReadCloser, error)
OpenKnowledgeFile starts a download for the given knowledge entry and returns the server-suggested filename (parsed from Content-Disposition; empty when the server didn't send one) and a streaming reader for the body. Callers MUST Close the returned reader. The default ordinary-request timeout does not cut off the transfer; WithTimeout and context deadlines apply.
Used by `weknora doc download` so the CLI can inspect the filename before opening the destination file — avoids streaming the full body to a temp file just to discover the request would have been rejected (overwrite without --force, missing --out for unnamed downloads, etc.).
func (*Client) OpenKnowledgeFilesArchive ¶
func (c *Client) OpenKnowledgeFilesArchive(ctx context.Context, knowledgeBaseID string, ids []string) (string, io.ReadCloser, error)
OpenKnowledgeFilesArchive starts a batch download and returns the server-suggested ZIP filename and a streaming reader. Callers MUST Close the returned reader. The request uses the streaming HTTP client so the default 30s timeout does not cut off large archives.
func (*Client) PatchAgent ¶
func (c *Client) PatchAgent(ctx context.Context, agentID string, request *PatchAgentRequest) (*Agent, error)
PatchAgent changes only the fields set in request, keeping the rest of the agent, unlike UpdateAgent, which replaces the whole config.
func (*Client) PatchKnowledgeBase ¶
func (c *Client) PatchKnowledgeBase(ctx context.Context, knowledgeBaseID string, request *PatchKnowledgeBaseRequest, ) (*KnowledgeBase, error)
PatchKnowledgeBase changes the supplied settings and preserves omitted fields.
func (*Client) PreviewKnowledgeFile ¶
func (c *Client) PreviewKnowledgeFile(ctx context.Context, knowledgeID string) (*http.Response, error)
PreviewKnowledgeFile returns the file content for inline preview. The caller is responsible for reading and closing the response body.
func (*Client) PreviewOrganizationByInviteCode ¶
func (c *Client) PreviewOrganizationByInviteCode(ctx context.Context, code string) (*OrganizationResponse, error)
PreviewOrganizationByInviteCode previews an organization before joining
func (*Client) PromoteMemoryTopic ¶
PromoteMemoryTopic turns a counted topic into a long-term interest without waiting for the remaining hits.
func (*Client) Raw ¶
func (c *Client) Raw(ctx context.Context, method, path string, body interface{}) (*http.Response, error)
Raw performs a raw HTTP request against the WeKnora API with the client's auth headers, X-Request-ID, and X-Tenant-ID injection applied.
Experimental: this method is intended for one-off integrations and the `weknora api` CLI passthrough. The signature, return type, and behavior may change in any minor version. Prefer typed methods (ListKnowledgeBases, GetKnowledgeBase, etc.) when they exist.
func (*Client) ReconnectDocReader ¶
ReconnectDocReader reconnects the document parser service to a new address
func (*Client) RecordMessageSuggestionEvent ¶
func (*Client) RefreshMCPMetadata ¶
RefreshMCPMetadata connects upstream and atomically replaces the saved directory. OAuth services store a snapshot for the calling user (Viewer+). Static-auth services write a tenant-wide snapshot and require Admin, or an API key that can manage MCP services. Server route: POST /api/v1/mcp-services/{id}/metadata/refresh.
func (*Client) RefreshToken ¶
func (c *Client) RefreshToken(ctx context.Context, refreshToken string) (*RefreshTokenResponse, error)
RefreshToken renews the JWT access token using a refresh token. Maps to POST /api/v1/auth/refresh.
Callers (`weknora auth refresh`) read the refresh token from secrets, invoke this method, and persist both new tokens. The SDK does not touch the secrets store directly — it stays a transport-only layer.
func (*Client) ReinstallSandboxSkill ¶
func (c *Client) ReinstallSandboxSkill( ctx context.Context, configID, skillID string, ) (string, error)
ReinstallSandboxSkill runs the install of one skill again from the archive the server already stores, so a failure that had nothing to do with the bundle can be retried without re-uploading it. Like the install it is accepted asynchronously. A skill already serving the current image is left alone rather than rebuilt.
func (*Client) RejectMemoryItem ¶
RejectMemoryItem declines an inferred memory and records the rejection so the extractor does not silently re-add it.
func (*Client) RemoveAgentShare ¶
RemoveAgentShare removes an agent share
func (*Client) RemoveKBShare ¶
RemoveKBShare removes a KB share
func (*Client) RemoveMember ¶
RemoveMember removes a member from an organization
func (*Client) RenameKnowledgeFolder ¶
func (c *Client) RenameKnowledgeFolder( ctx context.Context, knowledgeBaseID string, req *RenameKnowledgeFolderRequest, ) (*RenameKnowledgeFolderResponse, error)
RenameKnowledgeFolder rewrites folder_path for a folder and every descendant.
func (*Client) ReparseKnowledge ¶
ReparseKnowledge triggers re-parsing of a knowledge entry This method deletes existing document content and re-parses the knowledge asynchronously. It's useful when you want to refresh the knowledge content with updated parsing configurations or when the original parsing failed and you want to retry.
Parameters:
- ctx: Context for the request
- knowledgeID: The ID of the knowledge entry to reparse
Returns:
- *Knowledge: The updated knowledge entry with status set to "pending"
- error: Error information if the request fails
Example:
knowledge, err := client.ReparseKnowledge(ctx, "knowledge-id-123")
if err != nil {
log.Fatalf("Failed to reparse knowledge: %v", err)
}
fmt.Printf("Knowledge reparse task submitted, status: %s\n", knowledge.ParseStatus)
func (*Client) RequestRoleUpgrade ¶
func (c *Client) RequestRoleUpgrade(ctx context.Context, orgID, requestedRole, message string) error
RequestRoleUpgrade requests a role upgrade in an organization
func (*Client) ResolveAgentPrompt ¶
func (c *Client) ResolveAgentPrompt( ctx context.Context, promptID string, req *ResolveAgentPromptRequest, ) (resumed bool, err error)
ResolveAgentPrompt answers a pending agent prompt by id. Resumed reports that the run had been suspended and now continues in the background; its output lands in the same assistant message. Server route: POST /api/v1/agent/prompts/{prompt_id}.
func (*Client) ResolveToolApproval ¶
func (c *Client) ResolveToolApproval(ctx context.Context, pendingID string, req *ResolveToolApprovalRequest) error
ResolveToolApproval resolves a pending tool approval by id. Server route: POST /api/v1/agent/tool-approvals/{pending_id}.
func (*Client) ReviewJoinRequest ¶
func (c *Client) ReviewJoinRequest(ctx context.Context, orgID, requestID string, approved bool, message, role string) error
ReviewJoinRequest reviews a join request (approve/reject)
func (*Client) RotateMCPEndpointToken ¶
func (c *Client) RotateMCPEndpointToken(ctx context.Context, endpointID string) (*MCPEndpoint, error)
RotateMCPEndpointToken replaces the bearer token. The new Token is shown once.
func (*Client) SearchFAQEntries ¶
func (c *Client) SearchFAQEntries(ctx context.Context, knowledgeBaseID string, payload *FAQSearchRequest, ) ([]FAQEntry, error)
SearchFAQEntries performs hybrid FAQ search inside a knowledge base.
func (*Client) SearchKnowledge ¶
func (c *Client) SearchKnowledge( ctx context.Context, request *SearchKnowledgeRequest, opts ...ResourceURLOptions, ) ([]*SearchResult, error)
SearchKnowledge performs knowledge base search without LLM summarization. Pass ResourceURLOptions to receive public HTTP(S) file URLs in results.
func (*Client) SearchKnowledgeDetailed ¶
func (c *Client) SearchKnowledgeDetailed( ctx context.Context, request *SearchKnowledgeRequest, opts ...ResourceURLOptions, ) (*SearchKnowledgeResponse, error)
SearchKnowledgeDetailed performs knowledge base search and returns the whole response, including the rerank diagnostics in Meta.
func (*Client) SearchMessages ¶
func (c *Client) SearchMessages(ctx context.Context, req *SearchMessagesRequest) (*MessageSearchResult, error)
SearchMessages searches chat history messages
func (*Client) SearchOrganizations ¶
func (c *Client) SearchOrganizations(ctx context.Context, keyword string, page, pageSize int) ([]OrganizationResponse, error)
SearchOrganizations searches for discoverable organizations
func (*Client) SearchTenants ¶
func (c *Client) SearchTenants(ctx context.Context, keyword string, tenantID uint64, page, pageSize int) ([]Tenant, int64, error)
SearchTenants searches tenants with pagination (requires cross-tenant access)
func (*Client) SearchUsersForInvite ¶
func (c *Client) SearchUsersForInvite(ctx context.Context, orgID, keyword string) ([]UserInfo, error)
SearchUsersForInvite searches users to invite into an organization (admin only)
func (*Client) SetKBModelConfig ¶
SetKBModelConfig binds a knowledge base to already-registered models via PUT /initialization/config/:kbId. Register models first with CreateModel; the server rejects unknown model ids and refuses to change the embedding model of a KB that already has documents.
func (*Client) SetMySandboxEnvVar ¶
SetMySandboxEnvVar stores the caller's own value for one config-wide variable. Unlike a skill variable the name is free-form, and the value is injected into every skill script and shell command this caller runs on that sandbox config. Names starting with WEKNORA_, and names the sandbox relies on such as PATH, are refused.
func (*Client) SetMySkillEnvVar ¶
SetMySkillEnvVar stores the caller's own value for one variable a skill declared. It overrides the workspace-wide value for this caller only, and is injected only into executions that name the skill. A name the skill did not declare is refused.
func (*Client) SetSandboxSkillEnabled ¶
func (c *Client) SetSandboxSkillEnabled( ctx context.Context, configID, skillID string, enabled bool, ) (*SandboxSkill, error)
SetSandboxSkillEnabled is the visibility half of UpdateSandboxSkill.
func (*Client) SetSandboxSkillEnvValues ¶
func (c *Client) SetSandboxSkillEnvValues( ctx context.Context, configID, skillID string, values map[string]string, ) (*SandboxSkill, error)
SetSandboxSkillEnvValues is the credentials half of UpdateSandboxSkill: it stores values that apply to everybody in the workspace. For a value that applies to the calling identity alone, use SetMySkillEnvVar.
func (*Client) ShareAgent ¶
func (c *Client) ShareAgent(ctx context.Context, agentID, orgID, permission string) (*AgentShareResponse, error)
ShareAgent shares an agent with an organization
func (*Client) ShareKnowledgeBase ¶
func (c *Client) ShareKnowledgeBase(ctx context.Context, kbID, orgID, permission string) (*KnowledgeBaseShareResponse, error)
ShareKnowledgeBase shares a knowledge base with an organization
func (*Client) StartEvaluation ¶
func (c *Client) StartEvaluation(ctx context.Context, request *EvaluationRequest) (*EvaluationTask, error)
StartEvaluation starts an evaluation task Creates and starts a new evaluation task based on provided parameters Parameters:
- ctx: Context, used for passing request context information such as deadline, cancellation signals, etc.
- request: Evaluation request parameters, including dataset ID and model IDs
Returns:
- *EvaluationTask: Created evaluation task information
- error: Error information if the request fails
func (*Client) StopSandboxSkill ¶
func (c *Client) StopSandboxSkill( ctx context.Context, configID, skillID string, ) (*SandboxSkill, error)
StopSandboxSkill aborts an in-flight install so the operator can retry or uninstall. After a process restart the row may still say installing with no live process; this rewrites it immediately instead of waiting for the stuck-run reaper. Removal is not stopped.
func (*Client) StopSession ¶
StopSession stops the generation for a specific assistant message under a session.
func (*Client) SubmitJoinRequest ¶
SubmitJoinRequest submits a join request for organizations that require approval
func (*Client) SwitchTenant ¶
func (c *Client) SwitchTenant(ctx context.Context, req SwitchTenantRequest) (*LoginResponse, error)
SwitchTenant re-issues a token pair scoped to TenantID and records that tenant as the user's last-active preference (next login and refresh land there). A preference-write failure fails the whole call — no new tokens are issued. Maps to POST /api/v1/auth/switch-tenant.
func (*Client) TestEmbeddingModel ¶
func (c *Client) TestEmbeddingModel(ctx context.Context, params map[string]string) (*ModelCheckResult, error)
TestEmbeddingModel tests an embedding model
func (*Client) TestMCPService ¶
TestMCPService tests an MCP service connection
func (*Client) TestMultimodalFunction ¶
func (c *Client) TestMultimodalFunction(ctx context.Context, params map[string]string) (*ModelCheckResult, error)
TestMultimodalFunction tests multimodal model functionality
func (*Client) TogglePinKnowledgeBase ¶
func (c *Client) TogglePinKnowledgeBase(ctx context.Context, knowledgeBaseID string) (*KnowledgeBase, error)
TogglePinKnowledgeBase toggles the pin status of a knowledge base. Server route is PUT (see internal/router/router.go); using POST silently 404s — the router treats unknown method on a known path as not-found, not 405.
func (*Client) UpdateAPIPrincipalConfig ¶
func (c *Client) UpdateAPIPrincipalConfig( ctx context.Context, tenantID uint64, req *UpdateAPIPrincipalConfigRequest, ) (*APIPrincipalConfig, error)
UpdateAPIPrincipalConfig updates how X-API-Key requests map to principals for a tenant.
func (*Client) UpdateAgent ¶
func (c *Client) UpdateAgent(ctx context.Context, agentID string, request *UpdateAgentRequest) (*Agent, error)
UpdateAgent updates an existing agent
func (*Client) UpdateChunk ¶
func (c *Client) UpdateChunk(ctx context.Context, knowledgeID string, chunkID string, request *UpdateChunkRequest, ) (*Chunk, error)
UpdateChunk updates a chunk's information Updates information for a specific chunk under a knowledge document Parameters:
- ctx: Context
- knowledgeID: Knowledge ID
- chunkID: Chunk ID
- request: Update request
Returns:
- *Chunk: Updated chunk
- error: Error information
func (*Client) UpdateFAQEntry ¶
func (c *Client) UpdateFAQEntry(ctx context.Context, knowledgeBaseID string, entrySeqID int64, payload *FAQEntryPayload, ) (*FAQEntry, error)
UpdateFAQEntry updates a single FAQ entry.
func (*Client) UpdateFAQEntryFieldsBatch ¶
func (c *Client) UpdateFAQEntryFieldsBatch(ctx context.Context, knowledgeBaseID string, byID map[int64]FAQEntryFieldsUpdate, byTag map[int64]FAQEntryFieldsUpdate, excludeIDs []int64, ) error
UpdateFAQEntryFieldsBatch updates multiple fields for FAQ entries in bulk. Supports updating is_enabled, is_recommended, tag_id in a single call. Supports two modes:
- byID: update by entry seq_id, key is entry seq_id
- byTag: update all entries under a tag, key is tag seq_id (0 for uncategorized)
func (*Client) UpdateFAQEntryTagBatch ¶
func (c *Client) UpdateFAQEntryTagBatch(ctx context.Context, knowledgeBaseID string, updates map[int64]*int64, ) error
UpdateFAQEntryTagBatch updates FAQ entry tags in bulk. key: entry seq_id, value: tag seq_id (nil to remove tag)
func (*Client) UpdateImageInfo ¶
func (c *Client) UpdateImageInfo(ctx context.Context, knowledgeID string, chunkID string, request *UpdateImageInfoRequest, ) error
UpdateChunk updates a chunk's information Updates information for a specific chunk under a knowledge document Parameters:
- ctx: Context
- knowledgeID: Knowledge ID
- chunkID: Chunk ID
- request: Update request
Returns:
- *Chunk: Updated chunk
- error: Error information
func (*Client) UpdateKBConfig
deprecated
func (c *Client) UpdateKBConfig(ctx context.Context, kbID string, config *InitializationConfig) error
UpdateKBConfig updates the model configuration for a knowledge base.
Deprecated: the PUT /initialization/config endpoint binds KBModelConfigRequest (fields llmModelId / embeddingModelId), not InitializationConfig, so this method sends a shape the server rejects. Use SetKBModelConfig instead.
func (*Client) UpdateKnowledge ¶
func (*Client) UpdateKnowledgeBase ¶
func (c *Client) UpdateKnowledgeBase(ctx context.Context, knowledgeBaseID string, request *UpdateKnowledgeBaseRequest, ) (*KnowledgeBase, error)
UpdateKnowledgeBase updates a knowledge base
func (*Client) UpdateLastFAQImportResultDisplayStatus ¶
func (c *Client) UpdateLastFAQImportResultDisplayStatus(ctx context.Context, knowledgeBaseID string, displayStatus string) error
UpdateLastFAQImportResultDisplayStatus updates the display status (open/close) of the last FAQ import result.
func (*Client) UpdateMCPEndpoint ¶
func (c *Client) UpdateMCPEndpoint( ctx context.Context, endpointID string, req *MCPEndpointRequest, ) (*MCPEndpoint, error)
UpdateMCPEndpoint applies a partial update; omitted fields are kept.
func (*Client) UpdateMCPService ¶
func (c *Client) UpdateMCPService(ctx context.Context, serviceID string, updates map[string]interface{}) (*MCPService, error)
UpdateMCPService updates an MCP service
func (*Client) UpdateManualKnowledge ¶
func (c *Client) UpdateManualKnowledge(ctx context.Context, knowledgeID string, request *UpdateManualKnowledgeRequest) (*Knowledge, error)
UpdateManualKnowledge updates a manual Markdown knowledge entry.
func (*Client) UpdateMemberRole ¶
UpdateMemberRole updates a member's role in an organization
func (*Client) UpdateMemoryItem ¶
func (c *Client) UpdateMemoryItem(ctx context.Context, id, content string, importance int) (*MemoryItem, error)
UpdateMemoryItem changes content and importance. After an edit the extractor will not overwrite the row.
func (*Client) UpdateMemorySettings ¶
UpdateMemorySettings turns the caller's own long-term memory on or off.
func (*Client) UpdateModel ¶
func (c *Client) UpdateModel(ctx context.Context, modelID string, request *UpdateModelRequest) (*Model, error)
UpdateModel updates a model
func (*Client) UpdateOrganization ¶
func (c *Client) UpdateOrganization(ctx context.Context, orgID string, req *UpdateOrganizationRequest) (*OrganizationResponse, error)
UpdateOrganization updates an organization
func (*Client) UpdateSandboxSkill ¶
func (c *Client) UpdateSandboxSkill( ctx context.Context, configID, skillID string, update SandboxSkillUpdate, ) (*SandboxSkill, error)
UpdateSandboxSkill shows or hides an installed skill and sets the workspace-wide values of the environment variables it declared. Visibility is metadata only: the files stay in the image either way.
Only declared names are written; a name outside the declaration is ignored rather than refused, so a stale form cannot fail an otherwise valid save. An empty string clears a value and keeps the declaration, because "nobody filled this in" and "this is not needed" are different states.
A stored value is never read back: the returned Envs report IsSet only.
func (*Client) UpdateSession ¶
func (c *Client) UpdateSession(ctx context.Context, sessionID string, request *CreateSessionRequest) (*Session, error)
UpdateSession updates a session
func (*Client) UpdateSharePermission ¶
UpdateSharePermission updates a KB share's permission
func (*Client) UpdateTag ¶
func (c *Client) UpdateTag(ctx context.Context, knowledgeBaseID, tagID string, payload *UpdateTagPayload, ) (*Tag, error)
UpdateTag updates an existing tag. tagID can be either UUID or seq_id (as string).
func (*Client) UpdateTagBySeqID ¶
func (c *Client) UpdateTagBySeqID(ctx context.Context, knowledgeBaseID string, tagSeqID int64, payload *UpdateTagPayload, ) (*Tag, error)
UpdateTagBySeqID updates an existing tag by seq_id.
func (*Client) UpdateTenant ¶
UpdateTenant updates an existing tenant
func (*Client) UpdateTenantAPIKey ¶
func (c *Client) UpdateTenantAPIKey( ctx context.Context, tenantID uint64, keyID uint64, req *UpdateTenantAPIKeyRequest, ) (*TenantAPIKey, error)
UpdateTenantAPIKey replaces an existing tenant API key's configuration.
func (*Client) UpdateTenantKV ¶
func (c *Client) UpdateTenantKV(ctx context.Context, key string, value any) (json.RawMessage, error)
UpdateTenantKV updates a tenant KV configuration by key
func (*Client) UploadSandboxSkill ¶
func (c *Client) UploadSandboxSkill( ctx context.Context, configID, filename string, archive []byte, ) (string, error)
UploadSandboxSkill installs a skill onto a sandbox config from a zip archive.
func (*Client) UpsertFAQEntries ¶
func (c *Client) UpsertFAQEntries(ctx context.Context, knowledgeBaseID string, payload *FAQBatchUpsertPayload, ) (string, error)
UpsertFAQEntries imports or appends FAQ entries asynchronously and returns the task ID.
type ClientOption ¶
type ClientOption func(*Client)
ClientOption defines client configuration options
func WithAPIKey ¶
func WithAPIKey(key string) ClientOption
WithAPIKey sets the long-lived API key sent as the X-API-Key header.
func WithBearerToken ¶
func WithBearerToken(token string) ClientOption
WithBearerToken sets the JWT bearer token sent as the Authorization header. Used after a successful auth.login to call authenticated endpoints with the short-lived access token.
func WithTenantID ¶
func WithTenantID(tenantID uint64) ClientOption
WithTenantID sets X-Tenant-ID on every request. Use only for explicit cross-tenant access by callers with CanAccessAllTenants — the server's auth middleware runs the cross-tenant gate whenever this header is present on a bearer request, even when the value matches the credential's own tenant, and 403s normal users. JWT bearer tokens and tenant-scoped API keys carry tenant identity intrinsically, so the header is redundant (and harmful) for default-tenant traffic. Per-request override via the "TenantID" context value still applies.
func WithTimeout ¶
func WithTimeout(timeout time.Duration) ClientOption
WithTimeout sets the timeout for ordinary and streaming HTTP requests. Streaming requests have no timeout by default; callers that set this option explicitly are asking for the same upper bound to apply to streams and downloads.
func WithToken
deprecated
func WithToken(token string) ClientOption
WithToken is the v0.x compatibility alias for WithAPIKey. Prefer WithAPIKey (or WithBearerToken for JWT). Will be removed in the next major; the alias is preserved for two minor versions per ADR.
Deprecated: use WithAPIKey for X-API-Key, WithBearerToken for JWT.
func WithTransport ¶
func WithTransport(rt http.RoundTripper) ClientOption
WithTransport overrides the underlying http.RoundTripper on the SDK's HTTP client. The default Timeout (and any WithTimeout override) is preserved. Intended for callers (the CLI's authretry layer; metrics or signing middleware) that want to wrap the transport without replacing the whole http.Client.
Passing nil restores http.DefaultTransport.
type ConfigEnvGroup ¶
type ConfigEnvGroup struct {
SandboxConfigID string `json:"sandbox_config_id"`
SandboxConfigName string `json:"sandbox_config_name"`
Description string `json:"description,omitempty"`
Vars []EnvVarView `json:"vars"`
Skills []SkillEnvGroup `json:"skills"`
}
ConfigEnvGroup is one sandbox config: the caller's own config-wide variables plus the declared credentials of the skills installed on it.
type CopyKnowledgeBaseResponse ¶
type CopyKnowledgeBaseResponse struct {
TaskID string `json:"task_id"`
SourceID string `json:"source_id"`
TargetID string `json:"target_id"`
Message string `json:"message"`
}
CopyKnowledgeBaseResponse represents the response from copy knowledge base API
type CreateAPIPrincipalTestTokenRequest ¶
type CreateAPIPrincipalTestTokenRequest struct {
ExternalUserID string `json:"external_user_id"`
ExpiresInSeconds int `json:"expires_in_seconds,omitempty"`
}
CreateAPIPrincipalTestTokenRequest signs a short-lived JWT for API integration testing.
type CreateAgentRequest ¶
type CreateAgentRequest struct {
Name string `json:"name"`
Description string `json:"description"`
Avatar string `json:"avatar"`
Config *AgentConfig `json:"config"`
}
CreateAgentRequest represents the request to create an agent. JSON field names mirror internal/handler.CreateAgentRequest.
type CreateKnowledgeFromURLRequest ¶
type CreateKnowledgeFromURLRequest struct {
// URL is the target URL (required)
URL string `json:"url"`
// FileName is the optional file name; used to hint file-download mode when URL has no extension
FileName string `json:"file_name,omitempty"`
// FileType is the optional file type (e.g. "pdf"); used to hint file-download mode
FileType string `json:"file_type,omitempty"`
// EnableMultimodel is the optional flag to enable multimodal processing
EnableMultimodel *bool `json:"enable_multimodel,omitempty"`
// Title is the optional title for the knowledge entry
Title string `json:"title,omitempty"`
// TagID is the optional tag ID to associate with the knowledge entry
TagID string `json:"tag_id,omitempty"`
// Channel identifies the ingestion channel (e.g. "web", "browser_extension", "api")
Channel string `json:"channel,omitempty"`
// ProcessConfig is optional per-upload parse config overrides (KnowledgeProcessOverrides).
ProcessConfig *KnowledgeProcessOverrides `json:"process_config,omitempty"`
}
CreateKnowledgeFromURLRequest contains the parameters for creating a knowledge entry from a URL. When FileName or FileType is provided (or the URL path has a known file extension such as .pdf/.docx/.doc/.txt/.md), the server automatically switches to file-download mode instead of web-page crawling.
type CreateManualKnowledgeRequest ¶
type CreateManualKnowledgeRequest struct {
Title string `json:"title"`
Content string `json:"content"`
TagID string `json:"tag_id,omitempty"`
Channel string `json:"channel,omitempty"`
}
CreateManualKnowledgeRequest contains the parameters for creating a manual Markdown knowledge entry.
type CreateModelRequest ¶
type CreateModelRequest struct {
Name string `json:"name"`
DisplayName string `json:"display_name"`
Type ModelType `json:"type"`
Source ModelSource `json:"source"`
Description string `json:"description"`
Parameters ModelParameters `json:"parameters"`
IsDefault bool `json:"is_default"`
}
CreateModelRequest model creation request
type CreateOrganizationRequest ¶
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"`
}
CreateOrganizationRequest represents a request to create an organization
type CreateSessionRequest ¶
type CreateSessionRequest struct {
Kind string `json:"kind,omitempty"`
Title string `json:"title"` // Session title (optional)
Description string `json:"description"` // Session description (optional)
}
CreateSessionRequest session creation request Sessions are now knowledge-base-independent and serve as conversation containers. All configuration comes from custom agent at query time.
type CreateTagPayload ¶
type CreateTagPayload struct {
Name string `json:"name"`
Color string `json:"color,omitempty"`
SortOrder int `json:"sort_order,omitempty"`
}
CreateTagPayload is used to create a new tag.
type CreateTenantAPIKeyRequest ¶
type CreateTenantAPIKeyRequest struct {
Name string `json:"name"`
Role TenantAPIKeyRole `json:"role,omitempty"`
FullAccess bool `json:"full_access,omitempty"`
KnowledgeBaseIDs []string `json:"knowledge_base_ids,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
ExpiresAtUnix *int64 `json:"expires_at_unix,omitempty"`
}
CreateTenantAPIKeyRequest creates a revocable tenant API key.
type CreatedTenantAPIKey ¶
type CreatedTenantAPIKey struct {
TenantAPIKey
Token string `json:"token,omitempty"`
}
CreatedTenantAPIKey includes the created API key. Token is kept for backward-compatible clients; APIKey is also returned by list APIs.
type CurrentUserResponse ¶
type CurrentUserResponse struct {
Success bool `json:"success"`
Data struct {
User *AuthUser `json:"user,omitempty"`
Tenant *AuthTenant `json:"tenant,omitempty"`
Memberships []AuthMembership `json:"memberships,omitempty"`
TenantRequired bool `json:"tenant_required,omitempty"`
Capabilities *AuthCapabilities `json:"capabilities,omitempty"`
} `json:"data"`
}
CurrentUserResponse is the body of GET /api/v1/auth/me.
type DeploymentCapabilitiesData ¶
type DeploymentCapabilitiesData struct {
Edition string `json:"edition"`
Capabilities map[string]DeploymentCapability `json:"capabilities"`
}
DeploymentCapabilitiesData is the payload of GET /system/capabilities.
type DeploymentCapability ¶
type DeploymentCapability struct {
Supported bool `json:"supported"`
Reason string `json:"reason,omitempty"`
}
DeploymentCapability describes whether a deployment exposes a feature route.
type DownloadTask ¶
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"`
}
DownloadTask represents an Ollama model download task
type DuplicateKnowledgeBaseResponse ¶
type DuplicateKnowledgeBaseResponse struct {
SourceID string `json:"source_id"`
TargetID string `json:"target_id"`
Message string `json:"message"`
KnowledgeBase KnowledgeBase `json:"knowledge_base"`
}
type EnvVarView ¶
type EnvVarView struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Required bool `json:"required,omitempty"`
// Source is one of EnvSourceUnset, EnvSourceWorkspace or EnvSourceUser,
// and reports which layer an execution would actually take the value from.
Source string `json:"source"`
// UpdatedAt is set only for the caller's own value.
UpdatedAt *time.Time `json:"updated_at,omitempty"`
}
EnvVarView is one environment variable as its owner may see it. There is deliberately no value field: the API never reads a stored value back out.
type EvaluationRequest ¶
type EvaluationRequest struct {
DatasetID string `json:"dataset_id"` // Dataset ID to evaluate
EmbeddingModelID string `json:"embedding_id"` // Embedding model ID
ChatModelID string `json:"chat_id"` // Chat model ID
RerankModelID string `json:"rerank_id"` // Reranking model ID
}
EvaluationRequest represents an evaluation request Parameters used to start a new evaluation task
type EvaluationResult ¶
type EvaluationResult struct {
TaskID string `json:"task_id"` // Associated task ID
Status string `json:"status"` // Task status
Progress int `json:"progress"` // Task progress
TotalQueries int `json:"total_queries"` // Total number of queries
TotalSamples int `json:"total_samples"` // Total number of samples
Metrics map[string]float64 `json:"metrics"` // Evaluation metrics collection
QueriesStat []map[string]interface{} `json:"queries_stat"` // Statistics for each query
CreatedAt string `json:"created_at"` // Creation time
CompleteAt string `json:"complete_at"` // Completion time
ErrorMsg string `json:"error_msg"` // Error message
}
EvaluationResult represents the evaluation results Contains detailed evaluation result information
type EvaluationResultResponse ¶
type EvaluationResultResponse struct {
Success bool `json:"success"` // Whether operation was successful
Data EvaluationResult `json:"data"` // Evaluation result data
}
EvaluationResultResponse represents an evaluation result response API response structure for evaluation results
type EvaluationTask ¶
type EvaluationTask struct {
ID string `json:"id"` // Task unique identifier
Status string `json:"status"` // Task status: pending, running, completed, failed
Progress int `json:"progress"` // Task progress, integer value 0-100
DatasetID string `json:"dataset_id"` // Evaluation dataset ID
EmbeddingID string `json:"embedding_id"` // Embedding model ID
ChatID string `json:"chat_id"` // Chat model ID
RerankID string `json:"rerank_id"` // Reranking model ID
CreatedAt string `json:"created_at"` // Task creation time
CompleteAt string `json:"complete_at"` // Task completion time
ErrorMsg string `json:"error_msg"` // Error message, has value when task fails
}
EvaluationTask represents an evaluation task Contains basic information about a model evaluation task
type EvaluationTaskResponse ¶
type EvaluationTaskResponse struct {
Success bool `json:"success"` // Whether operation was successful
Data EvaluationTask `json:"data"` // Evaluation task data
}
EvaluationTaskResponse represents an evaluation task response API response structure for evaluation tasks
type ExtractConfig ¶
type ExtractConfig struct {
Enabled bool `json:"enabled"`
Text string `json:"text,omitempty"`
Tags []string `json:"tags,omitempty"`
Nodes []*GraphNode `json:"nodes,omitempty"`
Relations []*GraphRelation `json:"relations,omitempty"`
}
ExtractConfig represents the extract configuration for a knowledge base
type FAQBatchUpsertPayload ¶
type FAQBatchUpsertPayload struct {
Entries []FAQEntryPayload `json:"entries"`
Mode string `json:"mode"`
KnowledgeID string `json:"knowledge_id,omitempty"`
TaskID string `json:"task_id,omitempty"` // Optional, if not provided, a UUID will be generated
DryRun bool `json:"dry_run,omitempty"` // If true, only validate without importing
}
FAQBatchUpsertPayload represents the request body for batch import (append/replace).
type FAQConfig ¶
type FAQConfig struct {
IndexMode string `json:"index_mode"`
QuestionIndexMode string `json:"question_index_mode"`
}
FAQConfig represents faq-specific configuration
type FAQDeleteRequest ¶
type FAQDeleteRequest struct {
IDs []int64 `json:"ids"`
}
FAQDeleteRequest deletes entries in bulk.
type FAQEntriesPage ¶
type FAQEntriesPage struct {
Total int64 `json:"total"`
Page int `json:"page"`
PageSize int `json:"page_size"`
Entries []FAQEntry `json:"data"`
}
FAQEntriesPage contains paginated FAQ results.
type FAQEntriesResponse ¶
type FAQEntriesResponse struct {
Success bool `json:"success"`
Data *FAQEntriesPage `json:"data"`
Message string `json:"message,omitempty"`
Code string `json:"code,omitempty"`
}
FAQEntriesResponse wraps the paginated FAQ response.
type FAQEntry ¶
type FAQEntry struct {
ID int64 `json:"id"`
ChunkID string `json:"chunk_id"`
KnowledgeID string `json:"knowledge_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
TagID int64 `json:"tag_id"`
TagName string `json:"tag_name"`
IsEnabled bool `json:"is_enabled"`
IsRecommended bool `json:"is_recommended"`
StandardQuestion string `json:"standard_question"`
SimilarQuestions []string `json:"similar_questions"`
NegativeQuestions []string `json:"negative_questions"`
Answers []string `json:"answers"`
AnswerStrategy string `json:"answer_strategy"`
IndexMode string `json:"index_mode"`
UpdatedAt time.Time `json:"updated_at"`
CreatedAt time.Time `json:"created_at"`
Score float64 `json:"score,omitempty"`
MatchType string `json:"match_type,omitempty"`
ChunkType string `json:"chunk_type"`
// MatchedQuestion is the actual question text that was matched in FAQ search
// Could be the standard question or one of the similar questions
MatchedQuestion string `json:"matched_question,omitempty"`
}
FAQEntry represents a FAQ item stored under a knowledge base.
type FAQEntryFieldsBatchRequest ¶
type FAQEntryFieldsBatchRequest struct {
// ByID updates by entry ID (seq_id), key is entry seq_id
ByID map[int64]FAQEntryFieldsUpdate `json:"by_id,omitempty"`
// ByTag updates all entries under a tag, key is tag seq_id (0 for uncategorized)
ByTag map[int64]FAQEntryFieldsUpdate `json:"by_tag,omitempty"`
// ExcludeIDs IDs (seq_id) to exclude from the ByTag update
ExcludeIDs []int64 `json:"exclude_ids,omitempty"`
}
FAQEntryFieldsBatchRequest updates multiple fields for FAQ entries in bulk. Supports two modes: 1. By entry ID: use ByID field 2. By Tag: use ByTag field to apply the same update to all entries under a tag
type FAQEntryFieldsUpdate ¶
type FAQEntryFieldsUpdate struct {
IsEnabled *bool `json:"is_enabled,omitempty"`
IsRecommended *bool `json:"is_recommended,omitempty"`
TagID *int64 `json:"tag_id,omitempty"`
}
FAQEntryFieldsUpdate represents the fields that can be updated for a single FAQ entry.
type FAQEntryPayload ¶
type FAQEntryPayload struct {
// ID is optional, used for data migration to specify seq_id (must be less than auto-increment start value 100000000)
ID *int64 `json:"id,omitempty"`
StandardQuestion string `json:"standard_question"`
SimilarQuestions []string `json:"similar_questions,omitempty"`
NegativeQuestions []string `json:"negative_questions,omitempty"`
Answers []string `json:"answers"`
AnswerStrategy *string `json:"answer_strategy,omitempty"`
TagID int64 `json:"tag_id,omitempty"`
TagName string `json:"tag_name,omitempty"`
IsEnabled *bool `json:"is_enabled,omitempty"`
IsRecommended *bool `json:"is_recommended,omitempty"`
}
FAQEntryPayload is used to create or update a FAQ entry.
type FAQEntryResponse ¶
type FAQEntryResponse struct {
Success bool `json:"success"`
Data *FAQEntry `json:"data"`
Message string `json:"message,omitempty"`
Code string `json:"code,omitempty"`
}
FAQEntryResponse wraps the single FAQ entry creation response.
type FAQEntryTagBatchRequest ¶
FAQEntryTagBatchRequest updates tags in bulk. key: entry seq_id, value: tag seq_id (nil to remove tag)
type FAQFailedEntry ¶
type FAQFailedEntry struct {
Index int `json:"index"`
Reason string `json:"reason"`
TagName string `json:"tag_name,omitempty"`
StandardQuestion string `json:"standard_question"`
SimilarQuestions []string `json:"similar_questions,omitempty"`
NegativeQuestions []string `json:"negative_questions,omitempty"`
Answers []string `json:"answers,omitempty"`
AnswerAll bool `json:"answer_all,omitempty"`
IsDisabled bool `json:"is_disabled,omitempty"`
}
FAQFailedEntry represents a failed entry during FAQ import/validation.
type FAQImportProgress ¶
type FAQImportProgress struct {
TaskID string `json:"task_id"`
KBID string `json:"kb_id"`
KnowledgeID string `json:"knowledge_id"`
Status string `json:"status"`
Progress int `json:"progress"`
Total int `json:"total"`
Processed int `json:"processed"`
SuccessCount int `json:"success_count"`
FailedCount int `json:"failed_count"`
SkippedCount int `json:"skipped_count,omitempty"`
FailedEntries []FAQFailedEntry `json:"failed_entries,omitempty"`
SuccessEntries []FAQSuccessEntry `json:"success_entries,omitempty"` // Successfully imported entries (when count is small)
FailedEntriesURL string `json:"failed_entries_url,omitempty"` // CSV download URL when too many failures
Message string `json:"message"`
Error string `json:"error,omitempty"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
DryRun bool `json:"dry_run,omitempty"` // Whether this is a dry run validation
// Result fields (populated when Status == "completed")
ImportMode string `json:"import_mode,omitempty"`
ImportedAt time.Time `json:"imported_at,omitempty"`
DisplayStatus string `json:"display_status,omitempty"`
ProcessingTime int64 `json:"processing_time,omitempty"`
}
FAQImportProgress represents the progress of an async FAQ import task. When Status is "completed", the result fields (SkippedCount, ImportMode, ImportedAt, DisplayStatus, ProcessingTime) are populated.
type FAQImportProgressResponse ¶
type FAQImportProgressResponse struct {
Success bool `json:"success"`
Data *FAQImportProgress `json:"data"`
Message string `json:"message,omitempty"`
Code string `json:"code,omitempty"`
}
FAQImportProgressResponse wraps the FAQ import progress response.
type FAQSearchRequest ¶
type FAQSearchRequest struct {
QueryText string `json:"query_text"`
VectorThreshold float64 `json:"vector_threshold"`
MatchCount int `json:"match_count"`
FirstPriorityTagIDs []int64 `json:"first_priority_tag_ids"` // First priority tag seq_ids, highest priority
SecondPriorityTagIDs []int64 `json:"second_priority_tag_ids"` // Second priority tag seq_ids, lower than first
OnlyRecommended bool `json:"only_recommended"` // Only return recommended entries
}
FAQSearchRequest represents the hybrid FAQ search request.
type FAQSearchResponse ¶
type FAQSearchResponse struct {
Success bool `json:"success"`
Data []FAQEntry `json:"data"`
Message string `json:"message,omitempty"`
Code string `json:"code,omitempty"`
}
FAQSearchResponse wraps the hybrid FAQ search results.
type FAQSuccessEntry ¶
type FAQSuccessEntry struct {
Index int `json:"index"` // Entry index in the batch (0-based)
SeqID int64 `json:"seq_id"` // Entry sequence ID after import
TagID int64 `json:"tag_id,omitempty"` // Tag ID (seq_id)
TagName string `json:"tag_name,omitempty"` // Tag name
StandardQuestion string `json:"standard_question"` // Standard question
}
FAQSuccessEntry represents a successfully imported FAQ entry.
type FAQTaskPayload ¶
type FAQTaskPayload struct {
TaskID string `json:"task_id"`
}
FAQTaskPayload carries the task identifier for async imports.
type FAQUpsertResponse ¶
type FAQUpsertResponse struct {
Success bool `json:"success"`
Data *FAQTaskPayload `json:"data"`
Message string `json:"message,omitempty"`
Code string `json:"code,omitempty"`
}
FAQUpsertResponse wraps the asynchronous import response.
type FilterKnowledgeResponse ¶
type FilterKnowledgeResponse struct {
Success bool `json:"success"`
Data []Knowledge `json:"data"`
HasMore bool `json:"has_more"`
}
FilterKnowledgeResponse represents the response from filter knowledge API
type FollowUpSuggestionConfig ¶
type FollowUpSuggestionConfig struct {
Enabled bool `json:"enabled"`
Mode string `json:"mode"`
Count int `json:"count"`
ModelID string `json:"model_id,omitempty"`
AdditionalInstruction string `json:"additional_instruction,omitempty"`
Categories []string `json:"categories,omitempty"`
MaxContextTurns int `json:"max_context_turns"`
SuppressOnFallback bool `json:"suppress_on_fallback"`
SuppressWhenAnswerAsksQuestion bool `json:"suppress_when_answer_asks_question"`
KnowledgeFallback bool `json:"knowledge_fallback"`
AllowRegenerate bool `json:"allow_regenerate"`
}
type FunctionCall ¶
type FunctionCall struct {
Name string `json:"name"`
Arguments string `json:"arguments"` // JSON string
}
FunctionCall represents the function details
type GenerateTitleRequest ¶
type GenerateTitleRequest struct {
Messages []Message `json:"messages"`
}
GenerateTitleRequest title generation request
type GenerateTitleResponse ¶
GenerateTitleResponse title generation response
type GraphNode ¶
type GraphNode struct {
Name string `json:"name"`
}
GraphNode represents a node in the graph extraction configuration
type GraphRelation ¶
type GraphRelation struct {
Node1 string `json:"node1"`
Node2 string `json:"node2"`
Type string `json:"type"`
}
GraphRelation represents a relation in the graph extraction configuration
type HybridSearchResponse ¶
type HybridSearchResponse struct {
Success bool `json:"success"`
Data []*SearchResult `json:"data"`
// Meta is present when the request carried a rerank object.
Meta *RetrievalMeta `json:"meta,omitempty"`
}
HybridSearchResponse hybrid search response
type ImageAttachment ¶
type ImageAttachment struct {
Data string `json:"data,omitempty"` // base64 data URI (data:image/png;base64,...)
URL string `json:"url,omitempty"` // serving URL after saving to storage
Caption string `json:"caption,omitempty"` // VLM analysis result
}
ImageAttachment represents an image in a chat request. Frontend sends base64 data in the Data field; the backend saves, runs VLM analysis, and populates URL/Caption before proceeding with the chat pipeline.
type ImageProcessingConfig ¶
type ImageProcessingConfig struct {
ModelID string `json:"model_id"` // Multimodal model ID
}
ImageProcessingConfig represents image processing configuration
type IndexingStrategy ¶
type IndexingStrategy struct {
VectorEnabled bool `json:"vector_enabled"`
KeywordEnabled bool `json:"keyword_enabled"`
WikiEnabled bool `json:"wiki_enabled"`
GraphEnabled bool `json:"graph_enabled"`
}
IndexingStrategy selects which indexing pipelines are active.
type InitializationConfig ¶
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"`
}
InitializationConfig is the WRITE payload for InitializeByKB / UpdateKBConfig (the server's write endpoint accepts these flat model ids). It is NOT the shape the read endpoint returns — see KBModelConfigView / GetInitializationConfig.
type JoinRequestResponse ¶
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"`
}
JoinRequestResponse represents a join request in API responses
type KBCloneProgress ¶
type KBCloneProgress struct {
TaskID string `json:"task_id"`
SourceID string `json:"source_id"`
TargetID string `json:"target_id"`
Status string `json:"status"` // pending, processing, completed, failed
Progress int `json:"progress"` // 0-100
Total int `json:"total"` // Total operations count
Processed int `json:"processed"` // Processed operations count
Message string `json:"message"`
Error string `json:"error,omitempty"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
}
KBCloneProgress represents the progress of a knowledge base clone task
type KBModelConfig ¶
type KBModelConfig struct {
LLMModelID string `json:"llmModelId"`
EmbeddingModelID string `json:"embeddingModelId,omitempty"`
}
KBModelConfig points a knowledge base at already-registered models. Field names match the server's KBModelConfigRequest (PUT /initialization/config/:kbId). LLMModelID is required server-side; EmbeddingModelID is optional (omitted when RAG indexing is disabled).
type KBModelConfigView ¶
type KBModelConfigView struct {
RetrievalReady bool `json:"retrieval_ready"` // embedding model bound → KB can embed/retrieve
Embedding ModelSlotView `json:"embedding"`
LLM ModelSlotView `json:"llm"`
Rerank RerankSlotView `json:"rerank"`
Multimodal MultimodalSlotView `json:"multimodal"`
}
KBModelConfigView is the secret-free, read-only model configuration of a knowledge base, returned by GetInitializationConfig. The server's read response nests config under embedding/llm/rerank/multimodal and INCLUDES provider apiKey/baseUrl (for the web config form); this view intentionally parses only the non-secret fields, so credentials can never leak through the CLI. Field tags are snake_case (the CLI envelope convention), remapped from the server's camelCase.
type KBSelectionMode ¶
type KBSelectionMode string
KBSelectionMode controls how an agent selects knowledge bases (AgentConfig.KBSelectionMode). It mirrors the server's documented values ("all" | "selected" | "none") in internal/types/custom_agent.go.
const ( // KBSelectionModeAll retrieves across every knowledge base. KBSelectionModeAll KBSelectionMode = "all" // KBSelectionModeSelected retrieves only the agent's attached KBs // (AgentConfig.KnowledgeBases). KBSelectionModeSelected KBSelectionMode = "selected" // KBSelectionModeNone disables knowledge base retrieval. KBSelectionModeNone KBSelectionMode = "none" )
func AllKBSelectionModes ¶
func AllKBSelectionModes() []KBSelectionMode
AllKBSelectionModes returns every KB selection mode the server recognises, in a stable order. Use this instead of re-typing the set so callers can't drift from the SDK.
type Knowledge ¶
type Knowledge struct {
ID string `json:"id"`
TenantID uint64 `json:"tenant_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
TagID string `json:"tag_id"`
Type string `json:"type"`
Title string `json:"title"`
Description string `json:"description"`
Source string `json:"source"`
Channel string `json:"channel"`
ParseStatus string `json:"parse_status"`
SummaryStatus string `json:"summary_status"`
EnableStatus string `json:"enable_status"`
EmbeddingModelID string `json:"embedding_model_id"`
FileName string `json:"file_name"`
FolderPath string `json:"folder_path"`
FileType string `json:"file_type"`
FileSize int64 `json:"file_size"`
FileHash string `json:"file_hash"`
FilePath string `json:"file_path"`
StorageSize int64 `json:"storage_size"`
Metadata json.RawMessage `json:"metadata"` // Extensible metadata for storing machine information, paths, etc.
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ProcessedAt *time.Time `json:"processed_at"`
ErrorMessage string `json:"error_message"`
}
Knowledge represents knowledge information
type KnowledgeBase ¶
type KnowledgeBase struct {
ID string `json:"id"`
Name string `json:"name"` // Name must be unique within the same tenant
Type string `json:"type"`
IsTemporary bool `json:"is_temporary"`
IsPinned bool `json:"is_pinned"`
Description string `json:"description"`
TenantID uint64 `json:"tenant_id"`
ChunkingConfig ChunkingConfig `json:"chunking_config"`
ImageProcessingConfig ImageProcessingConfig `json:"image_processing_config"`
FAQConfig *FAQConfig `json:"faq_config"`
EmbeddingModelID string `json:"embedding_model_id"`
SummaryModelID string `json:"summary_model_id"`
VLMConfig VLMConfig `json:"vlm_config"`
StorageProviderConfig *StorageProviderConfig `json:"storage_provider_config"`
StorageConfig StorageConfig `json:"storage_config"`
ExtractConfig *ExtractConfig `json:"extract_config"`
AutoTagConfig *AutoTagConfig `json:"auto_tag_config"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
// Computed fields (not stored in database)
KnowledgeCount int64 `json:"knowledge_count"`
ChunkCount int64 `json:"chunk_count"`
IsProcessing bool `json:"is_processing"`
ProcessingCount int64 `json:"processing_count"`
}
KnowledgeBase represents a knowledge base
func (*KnowledgeBase) UnmarshalJSON ¶
func (kb *KnowledgeBase) UnmarshalJSON(data []byte) error
UnmarshalJSON keeps backward compatibility for legacy responses that still use `cos_config` instead of `storage_config`.
type KnowledgeBaseConfig ¶
type KnowledgeBaseConfig struct {
ChunkingConfig ChunkingConfig `json:"chunking_config"`
ImageProcessingConfig ImageProcessingConfig `json:"image_processing_config"`
FAQConfig *FAQConfig `json:"faq_config"`
AutoTagConfig *AutoTagConfig `json:"auto_tag_config,omitempty"`
}
KnowledgeBaseConfig represents knowledge base configuration
type KnowledgeBaseListResponse ¶
type KnowledgeBaseListResponse struct {
Success bool `json:"success"`
Data []KnowledgeBase `json:"data"`
}
KnowledgeBaseListResponse knowledge base list response
type KnowledgeBaseResponse ¶
type KnowledgeBaseResponse struct {
Success bool `json:"success"`
Data KnowledgeBase `json:"data"`
}
KnowledgeBaseResponse knowledge base response
type KnowledgeBaseShareResponse ¶
type KnowledgeBaseShareResponse struct {
}
KnowledgeBaseShareResponse represents a KB share record in API responses
type KnowledgeBatchResponse ¶
KnowledgeBatchResponse represents the API response for batch knowledge retrieval
type KnowledgeFolderNode ¶
type KnowledgeFolderNode struct {
Path string `json:"path"`
Name string `json:"name"`
DocumentCount int64 `json:"document_count"`
TotalCount int64 `json:"total_count"`
Children []*KnowledgeFolderNode `json:"children,omitempty"`
}
KnowledgeFolderNode is one node of the knowledge base folder tree.
type KnowledgeFolderTree ¶
type KnowledgeFolderTree struct {
RootDocumentCount int64 `json:"root_document_count"`
TotalDocumentCount int64 `json:"total_document_count"`
Folders []*KnowledgeFolderNode `json:"folders"`
}
KnowledgeFolderTree is returned by ListKnowledgeFolders.
type KnowledgeListFilter ¶
type KnowledgeListFilter struct {
TagID string
Keyword string
FileType string
ParseStatus string
Source string
// StartTime / EndTime filter on knowledge updated_at. Zero values are skipped.
// They are serialized in RFC3339 format.
StartTime time.Time
EndTime time.Time
FolderPath *string
FolderRecursive bool
}
KnowledgeListFilter mirrors the server-side filters accepted by GET /api/v1/knowledge-bases/{id}/knowledge. Empty / zero fields are omitted from the request. FolderPath, when non-nil, selects a folder scope; the empty string means the knowledge base root. Omit FolderPath entirely for a flat listing across every folder.
type KnowledgeListResponse ¶
type KnowledgeListResponse struct {
Success bool `json:"success"`
Data []Knowledge `json:"data"`
Total int64 `json:"total"`
Page int `json:"page"`
PageSize int `json:"page_size"`
}
KnowledgeListResponse represents the API response containing a list of knowledge entries with pagination
type KnowledgeMoveProgress ¶
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"`
}
KnowledgeMoveProgress represents the progress of a knowledge move task
type KnowledgeProcessOverrides ¶
type KnowledgeProcessOverrides struct {
ParserEngineRules []ParserEngineRule `json:"parser_engine_rules,omitempty"`
ChunkingConfig *ChunkingConfig `json:"chunking_config,omitempty"`
EnableMultimodel *bool `json:"enable_multimodel,omitempty"`
VLMConfig *VLMConfig `json:"vlm_config,omitempty"`
ASRConfig *ASRConfig `json:"asr_config,omitempty"`
QuestionGenerationConfig *QuestionGenerationConfig `json:"question_generation_config,omitempty"`
GraphEnabled *bool `json:"graph_enabled,omitempty"`
ExtractConfig *ExtractConfig `json:"extract_config,omitempty"`
}
KnowledgeProcessOverrides stores per-upload parse config overrides sent as process_config. When nil, the server uses the knowledge base defaults only.
type KnowledgeProcessingTrace ¶
type KnowledgeProcessingTrace struct {
KnowledgeID string `json:"knowledge_id"`
ParseStatus string `json:"parse_status"`
CurrentAttempt int `json:"current_attempt"`
CurrentStage string `json:"current_stage"`
Trace *KnowledgeSpanNode `json:"trace"`
LastError *KnowledgeSpanError `json:"last_error,omitempty"`
}
KnowledgeProcessingTrace is the document-parsing trace for one parse attempt: a five-segment stage timeline (docreader, chunking, embedding, multimodal, postprocess) plus any subspans, with the current stage and last error surfaced for convenience.
type KnowledgeQARequest ¶
type KnowledgeQARequest struct {
Query string `json:"query"` // Query text for knowledge base search
KnowledgeBaseIDs []string `json:"knowledge_base_ids"` // Selected knowledge base IDs for this request
KnowledgeIDs []string `json:"knowledge_ids"` // Selected knowledge IDs for this request
AgentEnabled bool `json:"agent_enabled"` // Whether agent mode is enabled for this request
AgentID string `json:"agent_id"` // Selected custom agent ID for this request
WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search is enabled for this request
SummaryModelID string `json:"summary_model_id"` // Optional summary model ID (overrides session default)
DisableTitle bool `json:"disable_title"` // Whether to disable auto title generation
Images []ImageAttachment `json:"images,omitempty"` // Attached images for multimodal chat
Channel string `json:"channel,omitempty"` // Source channel: "web", "api", "im", etc.
QuestionOrigin *QuestionOrigin `json:"question_origin,omitempty"` // Source of a picked suggested question
}
KnowledgeQARequest knowledge Q&A request
type KnowledgeResponse ¶
type KnowledgeResponse struct {
Success bool `json:"success"`
Data Knowledge `json:"data"`
Code string `json:"code"`
Message string `json:"message"`
}
KnowledgeResponse represents the API response containing a single knowledge entry
type KnowledgeSpanError ¶
type KnowledgeSpanError struct {
Stage string `json:"stage"`
Code string `json:"code"`
Message string `json:"message"`
FinishedAt *time.Time `json:"finished_at,omitempty"`
}
KnowledgeSpanError describes the most recent failed span in a trace.
type KnowledgeSpanNode ¶
type KnowledgeSpanNode struct {
KnowledgeID string `json:"knowledge_id"`
Attempt int `json:"attempt"`
SpanID string `json:"span_id"`
ParentSpanID string `json:"parent_span_id,omitempty"`
Name string `json:"name"`
Kind string `json:"kind"` // root / stage / subspan / generation
Status string `json:"status"` // pending / running / done / failed / skipped / cancelled
Input map[string]interface{} `json:"input,omitempty"`
Output map[string]interface{} `json:"output,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
ErrorCode string `json:"error_code,omitempty"`
ErrorMessage string `json:"error_message,omitempty"`
StartedAt *time.Time `json:"started_at,omitempty"`
FinishedAt *time.Time `json:"finished_at,omitempty"`
DurationMs int64 `json:"duration_ms,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Children []*KnowledgeSpanNode `json:"children,omitempty"`
}
KnowledgeSpanNode mirrors one node of the server's document-parsing trace tree (root → stage → subspan). Children carries nested subspans such as per-image multimodal calls or LLM generations under a stage.
type LLMToolCall ¶
type LLMToolCall struct {
ID string `json:"id"`
Type string `json:"type"` // "function"
Function FunctionCall `json:"function"`
}
LLMToolCall represents a function/tool call from the LLM
type LoginRequest ¶
LoginRequest is the body for POST /api/v1/auth/login.
type LoginResponse ¶
type LoginResponse struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
User *AuthUser `json:"user,omitempty"`
// ActiveTenant is the tenant whose ID is encoded in the JWT. Use
// this field; Tenant is preserved as a compatibility alias only.
ActiveTenant *AuthTenant `json:"active_tenant,omitempty"`
// Tenant is a deprecated alias kept so SDK callers compiled against
// the pre-RBAC release continue to find the field by name. The
// server emits active_tenant; this field is populated on the client
// side by GetTenant() and will be removed in a future major release.
//
// Deprecated: use ActiveTenant.
Tenant *AuthTenant `json:"-"`
Memberships []AuthMembership `json:"memberships,omitempty"`
Token string `json:"token,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
}
LoginResponse is the body returned by POST /api/v1/auth/login.
Token is the JWT access token; RefreshToken renews it via Auth.Refresh. ActiveTenant is the tenant whose ID is encoded in the JWT — every subsequent request is scoped to it until /auth/switch-tenant is called. A successful switch also records that tenant as the user's last-active preference, so the next login and refresh land in the same workspace. Memberships lists every tenant the user can access along with their role in each, so callers can build a tenant switcher UI without a follow-up request.
func (*LoginResponse) GetTenant ¶
func (r *LoginResponse) GetTenant() *AuthTenant
GetTenant returns the active tenant, preferring ActiveTenant and falling back to the deprecated Tenant alias. SDK code should prefer reading ActiveTenant directly; this helper exists to keep callers that only know about the old field name compiling and working.
type MCPAdvancedConfig ¶
type MCPAdvancedConfig struct {
Timeout int `json:"timeout"`
RetryCount int `json:"retry_count"`
RetryDelay int `json:"retry_delay"`
}
MCPAdvancedConfig represents advanced configuration for MCP service
type MCPAuthConfig ¶
type MCPAuthConfig struct {
APIKey string `json:"api_key,omitempty"`
Token string `json:"token,omitempty"`
CustomHeaders map[string]string `json:"custom_headers,omitempty"`
}
MCPAuthConfig represents authentication configuration for MCP service.
Secret fields (APIKey, Token) are accepted on create but are never returned by the server. To mutate credentials on an existing service, use the dedicated /credentials subresource — see the MCP credentials API for the PUT / DELETE shape. Sending secret fields in a main PUT body is silently ignored server-side.
type MCPCatalogSummary ¶
type MCPCatalogSummary struct {
ToolCount int `json:"tool_count"`
Stale bool `json:"stale"`
SyncedAt string `json:"synced_at"`
}
MCPCatalogSummary is the list-card view of a saved MCP directory.
type MCPEndpoint ¶
type MCPEndpoint struct {
ID string `json:"id"`
TenantID uint64 `json:"tenant_id"`
Name string `json:"name"`
Description string `json:"description"`
Enabled bool `json:"enabled"`
TokenHint string `json:"token_hint"`
KnowledgeBaseIDs []string `json:"knowledge_base_ids"`
Tools []string `json:"tools"`
DefaultAgentID string `json:"default_agent_id"`
RateLimitPerMinute int `json:"rate_limit_per_minute"`
// Path is the public MCP path relative to the server origin (/mcp/<id>).
Path string `json:"path"`
LastUsedAt *string `json:"last_used_at,omitempty"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
// Token is only present on create and rotate responses and is never
// returned again.
Token string `json:"token,omitempty"`
}
MCPEndpoint is one workspace-published MCP server endpoint that external MCP clients connect to over Streamable HTTP at Path.
type MCPEndpointRequest ¶
type MCPEndpointRequest struct {
Name *string `json:"name,omitempty"`
Description *string `json:"description,omitempty"`
Enabled *bool `json:"enabled,omitempty"`
KnowledgeBaseIDs *[]string `json:"knowledge_base_ids,omitempty"`
Tools *[]string `json:"tools,omitempty"`
DefaultAgentID *string `json:"default_agent_id,omitempty"`
RateLimitPerMinute *int `json:"rate_limit_per_minute,omitempty"`
}
MCPEndpointRequest is the create/update payload. Nil pointers are omitted so an update only touches the fields you set.
type MCPEndpointToolCatalog ¶
type MCPEndpointToolCatalog struct {
Groups []string `json:"groups"`
Tools []MCPEndpointToolDefinition `json:"tools"`
DefaultTools []string `json:"default_tools"`
}
MCPEndpointToolCatalog lists the tools an endpoint can expose.
type MCPEndpointToolDefinition ¶
type MCPEndpointToolDefinition struct {
Name string `json:"name"`
Group string `json:"group"`
Destructive bool `json:"destructive"`
}
MCPEndpointToolDefinition describes one tool an endpoint may expose.
type MCPMetadata ¶
type MCPMetadata struct {
ServiceID string `json:"service_id"`
Tools []*MCPTool `json:"tools"`
Instructions string `json:"instructions"`
ServerName string `json:"server_name"`
ServerVersion string `json:"server_version"`
ServerDescription string `json:"server_description"`
SyncedAt string `json:"synced_at"`
Stale bool `json:"stale"`
}
MCPMetadata is a persisted MCP tool directory. A nil result from GetMCPMetadata means the service has never been synchronized. Stale is true when the saved connection no longer matches the current configuration.
type MCPResource ¶
type MCPResource struct {
URI string `json:"uri"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
MimeType string `json:"mimeType,omitempty"`
}
MCPResource represents a resource exposed by an MCP service
type MCPService ¶
type MCPService struct {
ID string `json:"id"`
TenantID uint64 `json:"tenant_id"`
Name string `json:"name"`
Description string `json:"description"`
UsageInstructions string `json:"usage_instructions,omitempty"`
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"`
Catalog *MCPCatalogSummary `json:"catalog,omitempty"`
}
MCPService represents an MCP service configuration
type MCPStdioConfig ¶
MCPStdioConfig represents stdio transport configuration
type MCPTestResult ¶
type MCPTestResult struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
Description string `json:"description,omitempty"`
Tools []*MCPTool `json:"tools,omitempty"`
Resources []*MCPResource `json:"resources,omitempty"`
}
MCPTestResult represents the result of testing an MCP service connection
type MCPTool ¶
type MCPTool struct {
Name string `json:"name"`
Description string `json:"description"`
InputSchema json.RawMessage `json:"inputSchema"`
}
MCPTool represents a tool exposed by an MCP service
type MCPTransportType ¶
type MCPTransportType string
MCPTransportType represents the transport type for MCP service
const ( MCPTransportSSE MCPTransportType = "sse" MCPTransportHTTPStreamable MCPTransportType = "http-streamable" MCPTransportStdio MCPTransportType = "stdio" )
type MatchType ¶
type MatchType int
MatchType records which retrieval channel produced a SearchResult. Numeric values are the wire contract; they mirror the iota order in server-side internal/types/embedding.go — do not reorder without coordinating a server bump. Server-side names are preserved as trailing comments so cross-repo grep works in both directions.
Channel grouping: 0-1 primary text channels (vector + keyword); 2-5 enrichment chunks (added in addition to primary matches, score=0); 6-9 alternate sources (graph DB, web search, raw load, data analysis).
const ( MatchTypeVector MatchType = 0 // server: MatchTypeEmbedding MatchTypeKeyword MatchType = 1 // server: MatchTypeKeywords MatchTypeNearby MatchType = 2 // server: MatchTypeNearByChunk MatchTypeHistory MatchType = 3 // server: MatchTypeHistory MatchTypeParent MatchType = 4 // server: MatchTypeParentChunk MatchTypeRelation MatchType = 5 // server: MatchTypeRelationChunk MatchTypeGraph MatchType = 6 // server: MatchTypeGraph MatchTypeWeb MatchType = 7 // server: MatchTypeWebSearch MatchTypeDirect MatchType = 8 // server: MatchTypeDirectLoad — chunk loaded by ID without scoring MatchTypeData MatchType = 9 // server: MatchTypeDataAnalysis — produced by analytical pipeline, not retrieval )
type MemoryConsolidationResult ¶
type MemoryConsolidationResult struct {
Merged int `json:"merged"`
Demoted int `json:"demoted"`
Expired int `json:"expired"`
Reviewed int `json:"reviewed"`
Candidates int `json:"candidates"`
Skipped string `json:"skipped,omitempty"`
}
MemoryConsolidationResult is what POST /memory/consolidate returns.
type MemoryDocument ¶
type MemoryDocument struct {
ID string `json:"id"`
KnowledgeID string `json:"knowledge_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
Title string `json:"title"`
Hits int `json:"hits"`
LastUsedAt time.Time `json:"last_used_at"`
}
MemoryDocument is a knowledge entry this person keeps drawing answers from.
type MemoryExport ¶
type MemoryExport struct {
Total int64 `json:"total"`
Truncated bool `json:"truncated"`
Items []*MemoryItem `json:"data"`
}
MemoryExport is the JSON snapshot from GET /memory/export.
type MemoryItem ¶
type MemoryItem struct {
ID string `json:"id"`
Kind string `json:"kind"`
Content string `json:"content"`
Topic string `json:"topic,omitempty"`
Importance int `json:"importance"`
Origin string `json:"origin"`
Status string `json:"status"`
SourceSessionID string `json:"source_session_id,omitempty"`
SourceMessageID string `json:"source_message_id,omitempty"`
ValidFrom time.Time `json:"valid_from"`
InvalidAt *time.Time `json:"invalid_at,omitempty"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
SupersededBy string `json:"superseded_by,omitempty"`
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
UseCount int `json:"use_count"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
MemoryItem is one long-term memory row as returned by the API.
type MemorySettings ¶
type MemorySettings struct {
WorkspaceEnabled bool `json:"workspace_enabled"`
UserEnabled bool `json:"user_enabled"`
Effective bool `json:"effective"`
WriteMode string `json:"write_mode"`
ItemCount int `json:"item_count"`
MaxItems int `json:"max_items"`
}
MemorySettings is the merged workspace + personal memory switch.
type MemoryTopic ¶
type MemoryTopic struct {
ID string `json:"id"`
Topic string `json:"topic"`
Aliases []string `json:"aliases"`
Hits int `json:"hits"`
Threshold int `json:"threshold"`
LastSeenAt time.Time `json:"last_seen_at"`
}
MemoryTopic is a subject the extractor is still counting before promoting it to a long-term interest.
type MentionedItem ¶
type MentionedItem struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"` // "kb", "file", "tag", "mcp", or "skill"
KBType string `json:"kb_type"` // "document" or "faq" (only for kb type)
KBID string `json:"kb_id"` // Parent knowledge base for file/tag mentions
KBName string `json:"kb_name"` // Display name for parent KB
}
MentionedItem represents a mentioned item in the request
type Message ¶
type Message struct {
ID string `json:"id"`
SessionID string `json:"session_id"`
RequestID string `json:"request_id"`
Content string `json:"content"`
Role string `json:"role"`
KnowledgeReferences []*SearchResult `json:"knowledge_references"`
AgentSteps []AgentStep `json:"agent_steps,omitempty"` // Agent execution steps (only for assistant messages)
IsCompleted bool `json:"is_completed"`
Channel string `json:"channel,omitempty"` // Source channel: "web", "api", "im", etc.
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
Message message information
type MessageListResponse ¶
MessageListResponse message list response
type MessageSearchGroupItem ¶
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"`
}
MessageSearchGroupItem represents a grouped search result item
type MessageSearchMode ¶
type MessageSearchMode string
MessageSearchMode is the search strategy for SearchMessages. It mirrors the server enum in internal/types/message.go.
const ( // MessageSearchModeKeyword searches by keyword only. MessageSearchModeKeyword MessageSearchMode = "keyword" // MessageSearchModeVector searches by vector similarity only. MessageSearchModeVector MessageSearchMode = "vector" // MessageSearchModeHybrid combines keyword and vector search (server default). MessageSearchModeHybrid MessageSearchMode = "hybrid" )
func AllMessageSearchModes ¶
func AllMessageSearchModes() []MessageSearchMode
AllMessageSearchModes returns every search mode the server recognises, in a stable order. Callers (CLI flag validation, docs) should use this instead of re-typing the set so they can't drift from the SDK.
type MessageSearchResult ¶
type MessageSearchResult struct {
Items []*MessageSearchGroupItem `json:"items"`
Total int `json:"total"`
}
MessageSearchResult represents the result of a message search
type MessageSuggestionItem ¶
type MessageSuggestionSet ¶
type MessageSuggestionSet struct {
ID string `json:"id"`
SessionID string `json:"session_id"`
AssistantMessageID string `json:"assistant_message_id"`
Status string `json:"status"`
AllowRegenerate bool `json:"allow_regenerate"`
SuppressionReason string `json:"suppression_reason,omitempty"`
Questions []MessageSuggestionItem `json:"questions"`
}
type Model ¶
type Model struct {
ID string `json:"id"`
TenantID uint `json:"tenant_id"`
Name string `json:"name"`
DisplayName string `json:"display_name"`
Type ModelType `json:"type"`
Source ModelSource `json:"source"`
Description string `json:"description"`
Parameters ModelParameters `json:"parameters"`
IsDefault bool `json:"is_default"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
Model model information
type ModelCheckResult ¶
type ModelCheckResult struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
}
ModelCheckResult represents the result of checking a remote model
type ModelListResponse ¶
ModelListResponse model list response
type ModelProvider ¶
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"`
}
ModelProvider represents a model provider with its supported types and default URLs
type ModelProviderListResponse ¶
type ModelProviderListResponse struct {
Success bool `json:"success"`
Data []ModelProvider `json:"data"`
}
ModelProviderListResponse represents the API response for listing model providers
type ModelResponse ¶
ModelResponse model response
type ModelSlotView ¶
type ModelSlotView struct {
Configured bool `json:"configured"`
ModelName string `json:"model_name,omitempty"`
Source string `json:"source,omitempty"`
Dimension int `json:"dimension,omitempty"`
}
ModelSlotView is one non-secret model slot (embedding / llm).
type ModelSource ¶
type ModelSource string
ModelSource represents the source of the model
const ( ModelSourceLocal ModelSource = "local" // Local model ModelSourceRemote ModelSource = "remote" // Remote model ModelSourceAliyun ModelSource = "aliyun" // Aliyun DashScope model ModelSourceZhipu ModelSource = "zhipu" // Zhipu model ModelSourceVolcengine ModelSource = "volcengine" // Volcengine model ModelSourceDeepseek ModelSource = "deepseek" // Deepseek model ModelSourceHunyuan ModelSource = "hunyuan" // Hunyuan model ModelSourceMinimax ModelSource = "minimax" // Minimax mode ModelSourceOpenAI ModelSource = "openai" // OpenAI model ModelSourceGemini ModelSource = "gemini" // Gemini model ModelSourceMimo ModelSource = "mimo" // Mimo model ModelSourceSiliconFlow ModelSource = "siliconflow" // SiliconFlow model ModelSourceJina ModelSource = "jina" // Jina AI model ModelSourceOpenRouter ModelSource = "openrouter" // OpenRouter model ModelSourceLiteLLM ModelSource = "litellm" // LiteLLM proxy model ModelSourceRequesty ModelSource = "requesty" // Requesty model ModelSourceNvidia ModelSource = "nvidia" // NVIDIA model ModelSourceNovita ModelSource = "novita" // Novita AI model ModelSourceAzureOpenAI ModelSource = "azure_openai" // Azure OpenAI model )
func AllModelSources ¶
func AllModelSources() []ModelSource
AllModelSources returns every model source the server recognises, in a stable order. This is the broad set used for FILTERING existing records (model list --source); creating a model only supports local/remote (the provider identity goes in ModelParameters.provider). Use this instead of re-typing the set so callers can't drift from the SDK.
type ModelType ¶
type ModelType string
ModelType represents the type of AI model
const ( ModelTypeEmbedding ModelType = "Embedding" // Embedding model ModelTypeRerank ModelType = "Rerank" // Rerank model ModelTypeKnowledgeQA ModelType = "KnowledgeQA" // KnowledgeQA model ModelTypeVLLM ModelType = "VLLM" // VLLM model ModelTypeASR ModelType = "ASR" // ASR (Automatic Speech Recognition) model )
func AllModelTypes ¶
func AllModelTypes() []ModelType
AllModelTypes returns every model type the server recognises, in a stable order. Callers (CLI flag validation, docs) should use this instead of re-typing the string set, so they can't drift from the SDK.
type MoveKnowledgeRequest ¶
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"
}
MoveKnowledgeRequest contains the parameters for moving knowledge between KBs
type MoveKnowledgeResponse ¶
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"`
}
MoveKnowledgeResponse represents the response from move knowledge API
type MoveKnowledgeToFolderRequest ¶
type MoveKnowledgeToFolderRequest struct {
KBID string `json:"kb_id"`
IDs []string `json:"knowledge_ids"`
FolderPath string `json:"folder_path"`
}
MoveKnowledgeToFolderRequest re-files knowledge entries under a folder path.
type MoveKnowledgeToFolderResponse ¶
type MoveKnowledgeToFolderResponse struct {
MovedCount int64 `json:"moved_count"`
FolderPath string `json:"folder_path"`
}
MoveKnowledgeToFolderResponse is the payload of POST /knowledge/folder.
type MoveTarget ¶
type MoveTarget struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
Description string `json:"description"`
}
MoveTarget represents a knowledge base that can receive moved knowledge
type MultimodalSlotView ¶
type MultimodalSlotView struct {
Enabled bool `json:"enabled"`
}
MultimodalSlotView reports whether multimodal processing is enabled.
type OllamaModelInfo ¶
type OllamaModelInfo struct {
Name string `json:"name"`
Size int64 `json:"size"`
ModifiedAt string `json:"modified_at"`
}
OllamaModelInfo represents info about an Ollama model
type 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"`
}
Organization represents a collaboration organization
type OrganizationMemberResponse ¶
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"`
}
OrganizationMemberResponse represents a member in API responses
type OrganizationResponse ¶
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"`
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"`
}
OrganizationResponse represents an organization in API responses (with counts)
type PageContext ¶
type PageContext struct {
AgentID string `json:"agent_id,omitempty"`
KnowledgeBaseID string `json:"knowledge_base_id,omitempty"`
KnowledgeID string `json:"knowledge_id,omitempty"`
WikiSlug string `json:"wiki_slug,omitempty"`
WikiIssueIDs []string `json:"wiki_issue_ids,omitempty"` // At most 20 are kept
}
PageContext identifies the open page. Knowledge-base resources must be in the retrieval scope; agents must be visible in the current tenant.
type ParserEngine ¶
type ParserEngine struct {
Name string `json:"name"`
Label string `json:"label"`
Description string `json:"description"`
Available bool `json:"available"`
}
ParserEngine represents a document parser engine
type ParserEngineRule ¶
type ParserEngineRule struct {
FileTypes []string `json:"file_types"`
Engine string `json:"engine"`
}
ParserEngineRule maps a set of file types to a specific parser engine.
type PatchASRConfig ¶
type PatchASRConfig struct {
Enabled *bool `json:"enabled,omitempty"`
ModelID *string `json:"model_id,omitempty"`
Language *string `json:"language,omitempty"`
}
PatchASRConfig changes only the speech-recognition fields provided.
type PatchAgentRequest ¶
type PatchAgentRequest struct {
Name *string `json:"name,omitempty"`
Description *string `json:"description,omitempty"`
// AgentMode is "quick-answer" or "smart-reasoning". MCP and skills only
// run in smart-reasoning, and switching to it turns multi-turn on.
AgentMode *string `json:"agent_mode,omitempty"`
SystemPrompt *string `json:"system_prompt,omitempty"`
ModelID *string `json:"model_id,omitempty"`
// KBSelectionMode is "all", "selected" or "none".
KBSelectionMode *string `json:"kb_selection_mode,omitempty"`
// KnowledgeBases replaces the selected knowledge bases; without
// KBSelectionMode it also switches the mode to "selected".
KnowledgeBases *[]string `json:"knowledge_bases,omitempty"`
// MCPSelectionMode is "all", "selected" or "none".
MCPSelectionMode *string `json:"mcp_selection_mode,omitempty"`
// MCPServices replaces the selected MCP services; without
// MCPSelectionMode it also switches the mode to "selected".
MCPServices *[]string `json:"mcp_services,omitempty"`
// SkillsSelectionMode is "all", "selected" or "none"; all/none clears SelectedSkills.
SkillsSelectionMode *string `json:"skills_selection_mode,omitempty"`
// SelectedSkills replaces the selected skill names; without
// SkillsSelectionMode it also switches the mode to "selected".
SelectedSkills *[]string `json:"selected_skills,omitempty"`
WebSearchEnabled *bool `json:"web_search_enabled,omitempty"`
MultiTurnEnabled *bool `json:"multi_turn_enabled,omitempty"`
}
PatchAgentRequest changes only the fields that are set; the rest of the agent is kept. JSON field names mirror internal/handler.PatchAgentRequest.
type PatchAutoTagConfig ¶
type PatchAutoTagConfig struct {
Enabled *bool `json:"enabled,omitempty"`
ModelID *string `json:"model_id,omitempty"`
MaxTags *int `json:"max_tags,omitempty"`
SkipIfTagged *bool `json:"skip_if_tagged,omitempty"`
}
PatchAutoTagConfig changes only the automatic tagging fields provided.
type PatchChunkingConfig ¶
type PatchChunkingConfig struct {
ChunkSize *int `json:"chunk_size,omitempty"`
ChunkOverlap *int `json:"chunk_overlap,omitempty"`
Separators *[]string `json:"separators,omitempty"`
}
PatchChunkingConfig is the partial chunking update. Nil fields stay as they are.
type PatchFAQConfig ¶
type PatchFAQConfig struct {
IndexMode *string `json:"index_mode,omitempty"`
QuestionIndexMode *string `json:"question_index_mode,omitempty"`
}
PatchFAQConfig changes only the FAQ indexing fields provided.
type PatchImageProcessingConfig ¶
type PatchImageProcessingConfig struct {
ModelID *string `json:"model_id,omitempty"`
}
PatchImageProcessingConfig changes only the image settings provided.
type PatchIndexingStrategy ¶
type PatchIndexingStrategy struct {
VectorEnabled *bool `json:"vector_enabled,omitempty"`
KeywordEnabled *bool `json:"keyword_enabled,omitempty"`
WikiEnabled *bool `json:"wiki_enabled,omitempty"`
GraphEnabled *bool `json:"graph_enabled,omitempty"`
}
PatchIndexingStrategy is the partial indexing update. Nil flags stay as they are.
type PatchKnowledgeBaseRequest ¶
type PatchKnowledgeBaseRequest struct {
Name *string `json:"name,omitempty"`
Description *string `json:"description,omitempty"`
EmbeddingModelID *string `json:"embedding_model_id,omitempty"`
SummaryModelID *string `json:"summary_model_id,omitempty"`
StorageBackendID *string `json:"storage_backend_id,omitempty"`
ChunkingConfig *PatchChunkingConfig `json:"chunking_config,omitempty"`
IndexingStrategy *PatchIndexingStrategy `json:"indexing_strategy,omitempty"`
VLMConfig *PatchVLMConfig `json:"vlm_config,omitempty"`
ASRConfig *PatchASRConfig `json:"asr_config,omitempty"`
FAQConfig *PatchFAQConfig `json:"faq_config,omitempty"`
AutoTagConfig *PatchAutoTagConfig `json:"auto_tag_config,omitempty"`
ImageProcessing *PatchImageProcessingConfig `json:"image_processing_config,omitempty"`
}
PatchKnowledgeBaseRequest changes only the fields it carries. A nil field is left unchanged. Nested objects use pointers so a false or zero value can be sent without the other fields being cleared.
type PatchVLMConfig ¶
type PatchVLMConfig struct {
Enabled *bool `json:"enabled,omitempty"`
ModelID *string `json:"model_id,omitempty"`
}
PatchVLMConfig is the partial caption-model update.
type QuestionGenerationConfig ¶
type QuestionGenerationConfig struct {
Enabled bool `json:"enabled"`
QuestionCount int `json:"question_count"`
}
QuestionGenerationConfig controls LLM-generated questions per chunk during parsing.
type QuestionOrigin ¶
type QuestionOrigin struct {
KnowledgeBaseID string `json:"knowledge_base_id"`
KnowledgeID string `json:"knowledge_id,omitempty"`
}
QuestionOrigin names the knowledge source a suggested question was generated from (SuggestedQuestion.KnowledgeBaseID / KnowledgeID). Send it with the question the user picked: the agent searches that source before answering. It is a hint inside the request's retrieval scope and never widens it; for an agent that retrieves only on @mention, it selects the origin base when the agent may read it.
type QuestionSuggestionConfig ¶
type QuestionSuggestionConfig struct {
Starters StarterSuggestionConfig `json:"starters"`
FollowUps FollowUpSuggestionConfig `json:"follow_ups"`
}
type RefreshTokenResponse ¶
type RefreshTokenResponse struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
}
RefreshTokenResponse is the body of POST /api/v1/auth/refresh.
type RenameKnowledgeFolderRequest ¶
RenameKnowledgeFolderRequest moves a folder and its subtree to a new path.
type RenameKnowledgeFolderResponse ¶
type RenameKnowledgeFolderResponse struct {
MovedCount int64 `json:"moved_count"`
FolderPath string `json:"folder_path"`
}
RenameKnowledgeFolderResponse is the payload of PUT .../knowledge/folders.
type RerankDiagnostics ¶
type RerankDiagnostics struct {
// Applied is true when rerank scores decided the returned order.
Applied bool `json:"applied"`
// Outcome is one of ok, threshold_degraded, fallback_top1,
// all_below_threshold, model_error, model_unavailable, no_model,
// disabled, no_candidates.
Outcome string `json:"outcome"`
// ModelSource is request, tenant or auto.
ModelID string `json:"model_id,omitempty"`
ModelSource string `json:"model_source,omitempty"`
Threshold float64 `json:"threshold"`
EffectiveThreshold float64 `json:"effective_threshold"`
TopScore float64 `json:"top_score"`
CandidateCount int `json:"candidate_count"`
ResultCount int `json:"result_count"`
Error string `json:"error,omitempty"`
}
RerankDiagnostics reports what the rerank stage did with a request.
type RerankOptions ¶
type RerankOptions struct {
// Enabled turns rerank off when explicitly false. Nil means on.
Enabled *bool `json:"enabled,omitempty"`
// ModelID selects the rerank model. Empty uses the tenant retrieval
// config, then the tenant's first rerank model.
ModelID string `json:"model_id,omitempty"`
// TopK caps the reranked results. Zero uses the endpoint's result count.
TopK int `json:"top_k,omitempty"`
// Threshold is the minimum rerank model score. Nil uses the tenant
// retrieval config.
Threshold *float64 `json:"threshold,omitempty"`
}
RerankOptions controls the rerank stage of the knowledge-search and hybrid-search endpoints.
On hybrid-search, a nil *RerankOptions means no rerank. On knowledge-search, nil reranks with the tenant retrieval config; set Enabled to false to turn rerank off.
type RerankSlotView ¶
type RerankSlotView struct {
Enabled bool `json:"enabled"`
ModelName string `json:"model_name,omitempty"`
}
RerankSlotView is the rerank slot (may be disabled).
type ResolveAgentPromptRequest ¶
type ResolveAgentPromptRequest struct {
Kind string `json:"kind"`
Response json.RawMessage `json:"response"`
}
ResolveAgentPromptRequest answers a prompt an agent run is waiting on. Kind must match the prompt ("ask_user" or "tool_approval"); Response is the kind's answer, e.g. {"text": "..."} or {"selected": ["..."]} for ask_user, {"approved": true} or {"approved": false, "reason": "..."} for tool_approval (approval may add "modified_args": {...}). Unknown fields are rejected.
type ResolveToolApprovalRequest ¶
type ResolveToolApprovalRequest struct {
Decision string `json:"decision"`
Reason string `json:"reason,omitempty"`
ModifiedArgs json.RawMessage `json:"modified_args,omitempty"`
}
ResolveToolApprovalRequest is the body for resolving a pending tool-approval raised during an agent run (session ask). Decision is "approve" or "reject". ModifiedArgs optionally replaces the tool call arguments on approve; it must be a JSON object when present.
type ResourceURLMode ¶
type ResourceURLMode string
ResourceURLMode selects how file references are returned in API responses. Empty leaves the choice to the server (handle by default, or RESOURCE_URL_MODE when set).
const ( // ResourceURLModeHandle returns internal resource:// handles; clients fetch // bytes through the authenticated /files proxy. ResourceURLModeHandle ResourceURLMode = "handle" // ResourceURLModePublic returns time-limited HTTP(S) URLs loadable without // WeKnora credentials. ResourceURLModePublic ResourceURLMode = "public" )
type ResourceURLOptions ¶
type ResourceURLOptions struct {
ResourceURLs ResourceURLMode
}
ResourceURLOptions carries the optional resource_urls query parameter shared by chat, message-history, knowledge-search, and hybrid-search endpoints.
type ResponseType ¶
type ResponseType string
const ( ResponseTypeAnswer ResponseType = "answer" ResponseTypeReferences ResponseType = "references" ResponseTypeThinking ResponseType = "thinking" ResponseTypeToolCall ResponseType = "tool_call" ResponseTypeToolResult ResponseType = "tool_result" ResponseTypeError ResponseType = "error" ResponseTypeReflection ResponseType = "reflection" ResponseTypeSessionTitle ResponseType = "session_title" ResponseTypeAgentQuery ResponseType = "agent_query" ResponseTypeComplete ResponseType = "complete" )
type RetrievalMeta ¶
type RetrievalMeta struct {
Rerank *RerankDiagnostics `json:"rerank,omitempty"`
}
RetrievalMeta carries the diagnostics returned beside retrieval results.
type RetrieverEngineParams ¶
type RetrieverEngineParams struct {
RetrieverType string `json:"retriever_type"` // Type of retriever (e.g., keywords, vector)
RetrieverEngineType string `json:"retriever_engine_type"` // Type of engine implementing the retriever
}
RetrieverEngineParams contains configuration for retriever engines
type RetrieverEngines ¶
type RetrieverEngines struct {
Engines []RetrieverEngineParams `json:"engines"`
}
RetrieverEngines defines a collection of retriever engine parameters
type SSEStreamError ¶
type SSEStreamError struct {
Content string
}
SSEStreamError is returned when the server emits a terminal error frame on an SSE stream.
func (*SSEStreamError) Error ¶
func (e *SSEStreamError) Error() string
func (*SSEStreamError) Unwrap ¶
func (e *SSEStreamError) Unwrap() error
type SandboxSkill ¶
type SandboxSkill struct {
ID string `json:"id"`
Name string `json:"name"`
Version string `json:"version,omitempty"`
Description string `json:"description,omitempty"`
Enabled bool `json:"enabled"`
Status string `json:"status"`
Error string `json:"error,omitempty"`
BundleSHA256 string `json:"bundle_sha256,omitempty"`
InstalledSnapshotID string `json:"installed_snapshot_id,omitempty"`
InstallSessionID string `json:"install_session_id,omitempty"`
InstallMessageID string `json:"install_message_id,omitempty"`
Envs []SandboxSkillEnv `json:"envs,omitempty"`
}
SandboxSkill is one installed skill of a sandbox config.
type SandboxSkillEnv ¶
type SandboxSkillEnv struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Required bool `json:"required,omitempty"`
IsSet bool `json:"is_set"`
}
SandboxSkillEnv is one environment variable an installed skill declared. It reports whether a workspace-wide value exists and never what it is.
type SandboxSkillFile ¶
SandboxSkillFile is one path in an installed skill's stored archive.
type SandboxSkillFileContent ¶
type SandboxSkillFileContent struct {
Path string `json:"path"`
Size int64 `json:"size"`
Encoding string `json:"encoding"`
Content string `json:"content,omitempty"`
MediaType string `json:"media_type,omitempty"`
Truncated bool `json:"truncated,omitempty"`
Binary bool `json:"binary,omitempty"`
}
SandboxSkillFileContent is one file opened from an installed skill.
type SandboxSkillInstallResponse ¶
type SandboxSkillInstallResponse struct {
Success bool `json:"success"`
Data struct {
SkillID string `json:"skill_id"`
} `json:"data"`
}
SandboxSkillInstallResponse is returned when a skill install is accepted.
type SandboxSkillUpdate ¶
type SandboxSkillUpdate struct {
Enabled *bool `json:"enabled,omitempty"`
Envs *map[string]string `json:"envs,omitempty"`
}
SandboxSkillUpdate is what one PATCH may change. Both fields are optional, but a request carrying neither is refused: a nil Enabled is not a request to hide the skill, and a nil Envs must leave every stored value alone.
type SearchKnowledgeRequest ¶
type SearchKnowledgeRequest struct {
Query string `json:"query"` // Query content
KnowledgeBaseID string `json:"knowledge_base_id,omitempty"` // Single knowledge base ID (for backward compatibility)
KnowledgeBaseIDs []string `json:"knowledge_base_ids,omitempty"` // Knowledge base IDs (multi-KB support)
KnowledgeIDs []string `json:"knowledge_ids,omitempty"` // Specific knowledge (file) IDs
TagIDs []string `json:"tag_ids,omitempty"` // Tag IDs for filtering within a single KB
MentionedItems []MentionedItem `json:"mentioned_items,omitempty"` // Optional scoped tag mentions
// Optional overrides of the tenant retrieval config.
VectorThreshold *float64 `json:"vector_threshold,omitempty"` // Minimum vector similarity
KeywordThreshold *float64 `json:"keyword_threshold,omitempty"` // Minimum keyword score
MatchCount int `json:"match_count,omitempty"` // Number of results to return
DisableKeywordsMatch bool `json:"disable_keywords_match,omitempty"` // Vector recall only
DisableVectorMatch bool `json:"disable_vector_match,omitempty"` // Keyword recall only
Rerank *RerankOptions `json:"rerank,omitempty"` // Rerank override
}
SearchKnowledgeRequest knowledge search request
type SearchKnowledgeResponse ¶
type SearchKnowledgeResponse struct {
Success bool `json:"success"`
Data []*SearchResult `json:"data"`
// Meta reports what the rerank stage did.
Meta *RetrievalMeta `json:"meta,omitempty"`
}
SearchKnowledgeResponse search results response
type SearchMessagesRequest ¶
type SearchMessagesRequest struct {
Query string `json:"query"`
Mode string `json:"mode"`
Limit int `json:"limit"`
SessionIDs []string `json:"session_ids,omitempty"`
}
SearchMessagesRequest defines the request structure for searching messages. Mode is a plain string mirroring the server's request DTO; pass a MessageSearchMode constant cast to string, or leave empty for the server default (hybrid).
type SearchParams ¶
type SearchParams struct {
QueryText string `json:"query_text"`
VectorThreshold float64 `json:"vector_threshold"`
KeywordThreshold float64 `json:"keyword_threshold"`
MatchCount int `json:"match_count"`
DisableKeywordsMatch bool `json:"disable_keywords_match"`
DisableVectorMatch bool `json:"disable_vector_match"`
// KnowledgeBaseIDs searches several knowledge bases that share one
// embedding model; the path ID must be one of them.
KnowledgeBaseIDs []string `json:"knowledge_base_ids,omitempty"`
// KnowledgeIDs limits the search to these documents.
KnowledgeIDs []string `json:"knowledge_ids,omitempty"`
// TagIDs limits the search to these tags.
TagIDs []string `json:"tag_ids,omitempty"`
// Rerank, when set and enabled, reranks the candidates before cutting to
// MatchCount. Nil keeps the raw retrieval order.
Rerank *RerankOptions `json:"rerank,omitempty"`
}
SearchParams represents the search parameters for hybrid search
type SearchResult ¶
type SearchResult struct {
ID string `json:"id"`
Content string `json:"content"`
KnowledgeID string `json:"knowledge_id"`
ChunkIndex int `json:"chunk_index"`
KnowledgeTitle string `json:"knowledge_title"`
StartAt int `json:"start_at"`
EndAt int `json:"end_at"`
Seq int `json:"seq"`
Score float64 `json:"score"`
MatchType MatchType `json:"match_type"`
ChunkType string `json:"chunk_type"`
ImageInfo string `json:"image_info"`
Metadata map[string]string `json:"metadata"`
KnowledgeFilename string `json:"knowledge_filename"`
KnowledgeSource string `json:"knowledge_source"`
KnowledgeChannel string `json:"knowledge_channel"`
// MatchedContent is the actual content that was matched in vector search
// For FAQ: this is the matched question text (standard or similar question)
MatchedContent string `json:"matched_content,omitempty"`
// KnowledgeBaseID identifies the KB that produced this hit. It is required
// for agent runs that search more than one knowledge base.
KnowledgeBaseID string `json:"knowledge_base_id,omitempty"`
// ParentChunkID / SubChunkID describe the chunk hierarchy: a retrieval
// "hit" id may be a sub-chunk, while the parent holds the self-contained
// passage an agent fetches via `chunk view <parent_chunk_id>`. The server
// ships these in the references event; without fields here Go silently
// drops them during unmarshal.
ParentChunkID string `json:"parent_chunk_id,omitempty"`
SubChunkID []string `json:"sub_chunk_id,omitempty"`
}
SearchResult represents search result.
Score is the RRF (reciprocal-rank-fusion) score combining vector and keyword channels — typically in the [0, ~0.03] range when both channels hit, NOT the raw vector similarity. Use MatchType to tell which channel produced each result. Per-channel thresholds (vector_threshold, keyword_threshold) filter pre-fusion at retrieval time, before RRF runs.
type Session ¶
type Session struct {
Kind string `json:"kind"`
ID string `json:"id"`
TenantID uint64 `json:"tenant_id"`
Title string `json:"title"`
Description string `json:"description"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
Session session information
type SessionListOptions ¶
type SessionListOptions struct {
Kind string
}
SessionListOptions keeps assistant history opt-in for existing callers.
type SessionListResponse ¶
type SessionListResponse struct {
Success bool `json:"success"`
Data []Session `json:"data"`
Total int `json:"total"`
Page int `json:"page"`
PageSize int `json:"page_size"`
}
SessionListResponse session list response
type SessionResponse ¶
SessionResponse session response
type SharedKnowledgeBaseInfo ¶
type SharedKnowledgeBaseInfo struct {
}
SharedKnowledgeBaseInfo represents a shared knowledge base
type SkillEnvGroup ¶
type SkillEnvGroup struct {
SkillID string `json:"skill_id"`
SkillName string `json:"skill_name"`
Description string `json:"description,omitempty"`
Vars []EnvVarView `json:"vars"`
}
SkillEnvGroup is one skill's declared credentials.
type SkillListResponse ¶
type SkillListResponse struct {
Success bool `json:"success"`
Data []SkillInfo `json:"data"`
SkillsAvailable bool `json:"skills_available"`
}
SkillListResponse represents the response from listing skills
type StarterSuggestionConfig ¶
type StopSessionRequest ¶
type StopSessionRequest struct {
MessageID string `json:"message_id"`
}
StopSessionRequest stop generation payload.
type StorageCheckRequest ¶
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"`
OBS json.RawMessage `json:"obs,omitempty"`
}
StorageCheckRequest is the body for storage engine connectivity check
type StorageCheckResponse ¶
type StorageCheckResponse struct {
OK bool `json:"ok"`
Message string `json:"message"`
BucketCreated bool `json:"bucket_created,omitempty"`
}
StorageCheckResponse is the response for storage engine check
type StorageConfig ¶
type StorageConfig struct {
SecretID string `json:"secret_id"`
SecretKey string `json:"secret_key"`
Region string `json:"region"`
BucketName string `json:"bucket_name"`
AppID string `json:"app_id"`
PathPrefix string `json:"path_prefix"`
Provider string `json:"provider"`
}
StorageConfig represents the legacy storage configuration (cos_config). Deprecated: use StorageProviderConfig for provider selection.
type StorageEngineStatusItem ¶
type StorageEngineStatusItem struct {
Name string `json:"name"`
Allowed bool `json:"allowed"`
Available bool `json:"available"`
Description string `json:"description"`
}
StorageEngineStatusItem describes one storage engine's availability
type StorageEngineStatusResponse ¶
type StorageEngineStatusResponse struct {
Engines []StorageEngineStatusItem `json:"engines"`
AllowedProviders []string `json:"allowed_providers"`
MinioEnvAvailable bool `json:"minio_env_available"`
}
StorageEngineStatusResponse is the response for storage engine status
type StorageProviderConfig ¶
type StorageProviderConfig struct {
Provider string `json:"provider"`
}
StorageProviderConfig stores the KB-level storage provider selection.
type StreamResponse ¶
type StreamResponse struct {
ID string `json:"id"` // Unique identifier
ResponseType ResponseType `json:"response_type"` // Response type
Content string `json:"content"` // Current content fragment
Done bool `json:"done"` // Whether completed
KnowledgeReferences []*SearchResult `json:"knowledge_references,omitempty"` // Knowledge references
SessionID string `json:"session_id,omitempty"` // Session ID (for agent_query event)
AssistantMessageID string `json:"assistant_message_id,omitempty"` // Assistant Message ID (for agent_query event)
ToolCalls []LLMToolCall `json:"tool_calls,omitempty"` // Tool calls for streaming (partial)
Data map[string]interface{} `json:"data,omitempty"` // Additional metadata for enhanced display
}
StreamResponse streaming response
type SuggestedQuestion ¶
type SuggestedQuestion struct {
Question string `json:"question"` // Question text
Source string `json:"source"` // Source: "faq", "document", or "agent_config"
KnowledgeBaseID string `json:"knowledge_base_id,omitempty"` // Source knowledge base ID
KnowledgeID string `json:"knowledge_id,omitempty"` // Source document ID (faq/document sources)
}
SuggestedQuestion represents a suggested question for an agent
type SuggestedQuestionTagScope ¶
type SuggestedQuestionTagScope struct {
KnowledgeBaseID string `json:"knowledge_base_id"`
TagIDs []string `json:"tag_ids"`
}
SuggestedQuestionTagScope preserves the KB-local identity of tag IDs.
type SuggestedQuestionsRequest ¶
type SuggestedQuestionsRequest struct {
KnowledgeBaseIDs []string // Optional: override agent's KB scope
KnowledgeIDs []string // Optional: limit to specific knowledge items
TagScopes []SuggestedQuestionTagScope // Optional: limit to tags within their parent KBs
Limit int // Optional: max questions to return (default 6)
}
SuggestedQuestionsRequest represents the options for getting suggested questions
type SuggestedQuestionsResponse ¶
type SuggestedQuestionsResponse struct {
Success bool `json:"success"`
Data struct {
Questions []SuggestedQuestion `json:"questions"`
} `json:"data"`
}
SuggestedQuestionsResponse represents the API response for suggested questions
type SummaryConfig ¶
type SummaryConfig struct {
MaxTokens int `json:"max_tokens"`
TopP float64 `json:"top_p"`
TopK int `json:"top_k"`
FrequencyPenalty float64 `json:"frequency_penalty"`
PresencePenalty float64 `json:"presence_penalty"`
RepeatPenalty float64 `json:"repeat_penalty"`
Prompt string `json:"prompt"`
ContextTemplate string `json:"context_template"`
NoMatchPrefix string `json:"no_match_prefix"`
Temperature float64 `json:"temperature"`
Seed int `json:"seed"`
MaxCompletionTokens int `json:"max_completion_tokens"`
Thinking *bool `json:"thinking"`
}
SummaryConfig defines summary configuration
type SwitchTenantRequest ¶
type SwitchTenantRequest struct {
TenantID uint64 `json:"tenant_id"`
RefreshToken string `json:"refresh_token,omitempty"`
}
SwitchTenantRequest is the body for POST /api/v1/auth/switch-tenant.
type SystemInfo ¶
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"`
DBMigrationError string `json:"db_migration_error,omitempty"`
StartedAt string `json:"started_at,omitempty"`
UptimeSeconds int64 `json:"uptime_seconds,omitempty"`
}
SystemInfo represents system version and configuration information
type Tag ¶
type Tag struct {
ID string `json:"id"`
SeqID int64 `json:"seq_id"`
TenantID uint64 `json:"tenant_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
Name string `json:"name"`
Color string `json:"color"`
SortOrder int `json:"sort_order"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
Tag represents a knowledge base tag.
type TagResponse ¶
type TagResponse struct {
Success bool `json:"success"`
Data *Tag `json:"data"`
Message string `json:"message,omitempty"`
Code string `json:"code,omitempty"`
}
TagResponse wraps a single tag response.
type TagWithStats ¶
type TagWithStats struct {
Tag
KnowledgeCount int64 `json:"knowledge_count"`
ChunkCount int64 `json:"chunk_count"`
}
TagWithStats represents tag information along with usage statistics.
type TagsPage ¶
type TagsPage struct {
Total int64 `json:"total"`
Page int `json:"page"`
PageSize int `json:"page_size"`
Tags []TagWithStats `json:"data"`
}
TagsPage contains paginated tag results.
type TagsResponse ¶
type TagsResponse struct {
Success bool `json:"success"`
Data *TagsPage `json:"data"`
Message string `json:"message,omitempty"`
Code string `json:"code,omitempty"`
}
TagsResponse wraps the paginated tags response.
type Tenant ¶
type Tenant struct {
ID uint64 `yaml:"id" json:"id" gorm:"primaryKey"`
// Tenant name
Name string `yaml:"name" json:"name"`
// Tenant description
Description string `yaml:"description" json:"description"`
// Tenant status (active, inactive)
Status string `yaml:"status" json:"status" gorm:"default:'active'"`
// Configured retrieval engines
RetrieverEngines RetrieverEngines `yaml:"retriever_engines" json:"retriever_engines" gorm:"type:json"`
// Business/department information
Business string `yaml:"business" json:"business"`
// Storage quota (Bytes), default is 10GB
StorageQuota int64 `yaml:"storage_quota" json:"storage_quota" gorm:"default:10737418240"`
// Storage used (Bytes)
StorageUsed int64 `yaml:"storage_used" json:"storage_used" gorm:"default:0"`
// APIKey is only populated by CreateTenant when the server has
// tenant.auto_create_api_key (env WEKNORA_TENANT_AUTO_CREATE_API_KEY)
// enabled: it carries the plaintext token of an auto-created full_access
// key. Empty otherwise. Save it on receipt — it is never returned again.
APIKey string `yaml:"api_key,omitempty" json:"api_key,omitempty"`
// Creation timestamp
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
// Last update timestamp
UpdatedAt time.Time `yaml:"updated_at" json:"updated_at"`
}
Tenant represents tenant information in the system
type TenantAPIKey ¶
type TenantAPIKey struct {
ID uint64 `json:"id"`
TenantID uint64 `json:"tenant_id"`
ScopeType string `json:"scope_type"`
Name string `json:"name"`
APIKey string `json:"api_key"`
Role TenantAPIKeyRole `json:"role"`
FullAccess bool `json:"full_access"`
KnowledgeBaseIDs []string `json:"knowledge_base_ids"`
Capabilities []string `json:"capabilities"`
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
TenantAPIKey is the API key metadata returned by list/create APIs.
type TenantAPIKeyRole ¶
type TenantAPIKeyRole string
TenantAPIKeyRole is the tenant RBAC role bound to a revocable API key.
const ( TenantAPIKeyRoleViewer TenantAPIKeyRole = "viewer" TenantAPIKeyRoleContributor TenantAPIKeyRole = "contributor" TenantAPIKeyRoleAdmin TenantAPIKeyRole = "admin" )
type TenantListResponse ¶
type TenantListResponse struct {
Success bool `json:"success"` // Whether the operation was successful
Data struct {
Items []Tenant `json:"items"` // List of tenant items
} `json:"data"`
}
TenantListResponse represents the API response structure for listing tenants
type TenantResponse ¶
type TenantResponse struct {
Success bool `json:"success"` // Whether the operation was successful
Data Tenant `json:"data"` // Tenant data
}
TenantResponse represents the API response structure for tenant operations
type TenantSearchResponse ¶
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"`
}
TenantSearchResponse represents the API response for searching tenants
type ToolCall ¶
type ToolCall struct {
ID string `json:"id"` // Function call ID from LLM
Name string `json:"name"` // Tool name
Args map[string]interface{} `json:"args"` // Tool arguments
Result *ToolResult `json:"result"` // Execution result
Reflection string `json:"reflection,omitempty"` // Agent's reflection on this tool call result
Duration int64 `json:"duration"` // Execution time in milliseconds
}
ToolCall represents a single tool invocation within an agent step
type ToolResult ¶
type ToolResult struct {
Success bool `json:"success"` // Whether the tool executed successfully
Output string `json:"output"` // Human-readable output
Data map[string]interface{} `json:"data,omitempty"` // Structured data for programmatic use
Error string `json:"error,omitempty"` // Error message if execution failed
Images []string `json:"images,omitempty"` // Base64 data URIs from tool (e.g. MCP image content)
}
ToolResult represents the result of a tool execution
type UpdateAPIPrincipalConfigRequest ¶
type UpdateAPIPrincipalConfigRequest struct {
Mode APIPrincipalMode `json:"mode"`
DirectHeaderName string `json:"direct_header_name,omitempty"`
SignedTokenHeaderName string `json:"signed_token_header_name,omitempty"`
RequireDirectHeader bool `json:"require_direct_header,omitempty"`
HMACSecret string `json:"hmac_secret,omitempty"`
}
UpdateAPIPrincipalConfigRequest updates tenant API-key principal mapping.
type UpdateAgentRequest ¶
type UpdateAgentRequest struct {
Name string `json:"name"`
Description string `json:"description"`
// Avatar is omitted when nil to preserve the stored value. A pointer to
// an empty string explicitly clears the avatar.
Avatar *string `json:"avatar,omitempty"`
Config *AgentConfig `json:"config"`
}
UpdateAgentRequest represents the request to update an agent. JSON field names mirror internal/handler.UpdateAgentRequest.
type UpdateChunkRequest ¶
type UpdateChunkRequest struct {
Content string `json:"content"` // Chunk content
Embedding []float32 `json:"embedding"` // Vector embedding
ChunkIndex int `json:"chunk_index"` // Chunk index
IsEnabled bool `json:"is_enabled"` // Whether enabled
StartAt int `json:"start_at"` // Start position
EndAt int `json:"end_at"` // End position
ImageInfo string `json:"image_info"` // Image information
}
UpdateChunkRequest represents the request structure for updating a chunk Used for requesting chunk information updates
type UpdateImageInfoRequest ¶
type UpdateImageInfoRequest struct {
ImageInfo string `json:"image_info"` // Image information in JSON format
}
UpdateImageInfoRequest represents the request structure for updating a chunk Used for requesting chunk information updates
type UpdateKnowledgeBaseRequest ¶
type UpdateKnowledgeBaseRequest struct {
Name string `json:"name"`
Description string `json:"description"`
Config *KnowledgeBaseConfig `json:"config"`
}
UpdateKnowledgeBaseRequest update knowledge base request
type UpdateManualKnowledgeRequest ¶
type UpdateManualKnowledgeRequest struct {
Title string `json:"title,omitempty"`
Content string `json:"content,omitempty"`
}
UpdateManualKnowledgeRequest contains the parameters for updating a manual Markdown knowledge entry.
type UpdateModelRequest ¶
type UpdateModelRequest struct {
Name string `json:"name"`
DisplayName string `json:"display_name"`
Description string `json:"description"`
Parameters ModelParameters `json:"parameters"`
IsDefault bool `json:"is_default"`
}
UpdateModelRequest model update request
type UpdateOrganizationRequest ¶
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"`
}
UpdateOrganizationRequest represents a request to update an organization
type UpdateTagPayload ¶
type UpdateTagPayload struct {
Name *string `json:"name,omitempty"`
Color *string `json:"color,omitempty"`
SortOrder *int `json:"sort_order,omitempty"`
}
UpdateTagPayload is used to update an existing tag.
type UpdateTenantAPIKeyRequest ¶
type UpdateTenantAPIKeyRequest struct {
Name string `json:"name"`
FullAccess bool `json:"full_access"`
KnowledgeBaseIDs []string `json:"knowledge_base_ids"`
Capabilities []string `json:"capabilities"`
ExpiresAtUnix *int64 `json:"expires_at_unix"`
}
UpdateTenantAPIKeyRequest replaces an existing tenant API key's configurable attributes.
type UserInfo ¶
type UserInfo struct {
ID string `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
Avatar string `json:"avatar"`
TenantID uint64 `json:"tenant_id"`
IsActive bool `json:"is_active"`
CanAccessAllTenants bool `json:"can_access_all_tenants"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
UserInfo represents user information for API responses
Source Files
¶
- agent.go
- agent_manage.go
- auth.go
- chunk.go
- client.go
- env_var.go
- evaluation.go
- example.go
- faq.go
- initialization.go
- knowledge.go
- knowledgebase.go
- log.go
- mcp_endpoint.go
- mcp_service.go
- memory.go
- message.go
- message_suggestion.go
- model.go
- organization.go
- resource_urls.go
- retrieval.go
- session.go
- skill.go
- sse.go
- stream_errors.go
- system.go
- tag.go
- tenant.go
- web_search.go