Help us shape the future of Go! Take the 2026 Go Developer Survey

pluggedinkit

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 29, 2025 License: MIT Imports: 11 Imported by: 0

README

Plugged.in Go SDK

Official Go SDK for the Plugged.in Library API. Full support for document management, RAG queries, and file uploads.

Installation

go get github.com/veriteknik/pluggedinkit-go

Quick Start

package main

import (
    "context"
    "fmt"
    "log"

    pluggedin "github.com/veriteknik/pluggedinkit-go"
)

func main() {
    // Initialize client
    client := pluggedin.NewClient("your-api-key")
    // For local development:
    // client := pluggedin.NewClientWithOptions("your-api-key", "http://localhost:12005", nil)

    ctx := context.Background()

    // List documents
    docs, err := client.Documents.List(ctx, &pluggedin.DocumentFilters{
        Source: pluggedin.SourceAll,
        Limit:  10,
    })
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Found %d documents\n", docs.Total)

    // Search documents
    results, err := client.Documents.Search(ctx, "machine learning", nil, 10, 0)
    if err != nil {
        log.Fatal(err)
    }
    for _, result := range results.Results {
        fmt.Printf("%s - Relevance: %.2f\n", result.Title, result.RelevanceScore)
    }

    // Query RAG
    answer, err := client.RAG.AskQuestion(ctx, "What are the main features?")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(answer)
}

Features

  • 📄 Document Management - Full CRUD operations for documents
  • 🔍 Semantic Search - AI-powered document search
  • 🤖 RAG Integration - Natural language queries to your knowledge base
  • 📋 Clipboard/Memory - Persistent key-value storage for MCP tools and AI agents
  • 📤 File Uploads - Upload files with progress tracking
  • 🔄 Version Control - Document versioning and history
  • ⚡ Type Safety - Full Go type definitions
  • 🔐 Authentication - Secure API key authentication
  • 🔁 Context Support - Context-aware operations for cancellation
  • 📊 Rate Limiting - Built-in rate limit handling

Authentication

Get your API key from your Plugged.in profile settings:

import (
    "os"
    pluggedin "github.com/veriteknik/pluggedinkit-go"
)

client := pluggedin.NewClient(os.Getenv("PLUGGEDIN_API_KEY"))

Documentation

Document Operations
List Documents
filters := &pluggedin.DocumentFilters{
    Source:   pluggedin.SourceAIGenerated,
    Tags:     []string{"report", "analysis"},
    Sort:     pluggedin.SortDateDesc,
    Limit:    20,
    Offset:   0,
}

response, err := client.Documents.List(ctx, filters)
if err != nil {
    log.Fatal(err)
}

for _, doc := range response.Documents {
    fmt.Printf("%s (%d bytes)\n", doc.Title, doc.FileSize)
}
Get Document
// Get document metadata
doc, err := client.Documents.Get(ctx, "document-id", false, false)
if err != nil {
    log.Fatal(err)
}

// Get document with content
docWithContent, err := client.Documents.Get(ctx, "document-id", true, true)
if err != nil {
    log.Fatal(err)
}

fmt.Println(docWithContent.Content)
Search Documents
filters := map[string]interface{}{
    "modelProvider": "anthropic",
    "dateFrom":      "2024-01-01T00:00:00Z",
    "tags":          "finance,q4",
}

results, err := client.Documents.Search(ctx, "quarterly report", filters, 10, 0)
if err != nil {
    log.Fatal(err)
}

for _, result := range results.Results {
    fmt.Printf("%s\n", result.Title)
    fmt.Printf("  Relevance: %.2f\n", result.RelevanceScore)
    fmt.Printf("  Snippet: %s\n", result.Snippet)
}
Update Document
request := &pluggedin.UpdateDocumentRequest{
    Operation: pluggedin.OpAppend,
    Content:   "\n\n## New Section\n\nAdditional content here.",
    Metadata: map[string]interface{}{
        "changeSummary": "Added implementation details",
        "model": map[string]string{
            "name":     "claude-3-opus",
            "provider": "anthropic",
            "version":  "20240229",
        },
    },
}

response, err := client.Documents.Update(ctx, "document-id", request)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Updated to version %d\n", response.Version)
Create AI Document
request := &pluggedin.CreateDocumentRequest{
    Title:   "API Integration Guide",
    Content: "# API Integration Guide\n\n## Introduction\n\n...",
    Metadata: map[string]interface{}{
        "format":   "md",
        "category": "documentation",
        "tags":     []string{"api", "guide"},
        "model": map[string]string{
            "name":     "gpt-4",
            "provider": "openai",
            "version":  "0613",
        },
        "prompt":     "Create an API integration guide",
        "visibility": "workspace",
    },
}

doc, err := client.Documents.Create(ctx, request)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Created document: %s\n", doc.ID)
RAG Operations
Query Knowledge Base
// Simple query
answer, err := client.RAG.AskQuestion(ctx, "What are the deployment procedures?")
if err != nil {
    log.Fatal(err)
}
fmt.Println(answer)

// Query with sources
result, err := client.RAG.QueryWithSources(
    ctx,
    "Explain the authentication flow",
    "project-uuid", // Optional
)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Answer: %s\n", result.Answer)
fmt.Println("Sources:")
for _, source := range result.Sources {
    fmt.Printf("- %s (relevance: %.0f%%)\n", source.Name, source.Relevance)
}
Find Relevant Documents
documents, err := client.RAG.FindRelevantDocuments(
    ctx,
    "user authentication",
    "project-uuid",
    5, // Top 5 documents
)
if err != nil {
    log.Fatal(err)
}

for _, doc := range documents {
    fmt.Printf("- %s\n", doc.Name)
    if doc.Model != nil {
        fmt.Printf("  By: %s/%s\n", doc.Model.Provider, doc.Model.Name)
    }
}
File Upload Operations
Upload Single File
metadata := &pluggedin.UploadMetadata{
    Name:        "Q4 Report.pdf",
    Description: "Quarterly financial report",
    Tags:        []string{"finance", "q4", "2024"},
    Purpose:     "Financial documentation",
    RelatedTo:   "PROJECT-123",
}

// Progress callback
onProgress := func(percent int) {
    fmt.Printf("Upload progress: %d%%\n", percent)
}

response, err := client.Uploads.UploadFile(
    ctx,
    "./report.pdf",
    metadata,
    onProgress,
)
if err != nil {
    log.Fatal(err)
}

if response.Success {
    fmt.Printf("Uploaded: %s\n", response.DocumentID)

    // Track processing
    if response.UploadID != "" {
        onUpdate := func(status *pluggedin.UploadStatus) {
            fmt.Printf("Status: %s - %s\n", status.Status, status.Message)
        }

        client.Uploads.TrackUpload(ctx, response.UploadID, onUpdate)
    }
}
Upload from Reader
file, err := os.Open("document.txt")
if err != nil {
    log.Fatal(err)
}
defer file.Close()

fileInfo, _ := file.Stat()

response, err := client.Uploads.UploadReader(
    ctx,
    file,
    fileInfo.Size(),
    metadata,
    nil,
)
Batch Upload
files := []pluggedin.FileUpload{
    {
        Path:     "doc1.pdf",
        Metadata: &pluggedin.UploadMetadata{Name: "doc1.pdf", Tags: []string{"batch"}},
    },
    {
        Path:     "doc2.txt",
        Metadata: &pluggedin.UploadMetadata{Name: "doc2.txt", Tags: []string{"batch"}},
    },
}

onProgress := func(current, total int) {
    fmt.Printf("Uploaded %d/%d files\n", current, total)
}

results, err := client.Uploads.UploadBatch(ctx, files, onProgress)
if err != nil {
    log.Fatal(err)
}

for i, result := range results {
    if result.Success {
        fmt.Printf("✓ %s uploaded\n", files[i].Metadata.Name)
    } else {
        fmt.Printf("✗ %s failed: %s\n", files[i].Metadata.Name, result.Error)
    }
}
Clipboard Operations

The clipboard provides persistent key-value storage for MCP tools and AI agents.

Set Named Entry
entry, err := client.Clipboard.Set(ctx, &pluggedin.ClipboardSetRequest{
    Name:        "user_preferences",
    Value:       `{"theme": "dark", "lang": "en"}`,
    ContentType: "application/json",
    Encoding:    "utf-8",
    Visibility:  "private",
    TTLSeconds:  86400, // 24 hours
})
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Created entry: %s\n", entry.UUID)
fmt.Printf("Source: %s\n", *entry.Source) // "sdk" - automatically set
Get Entry
// By name
entry, err := client.Clipboard.GetByName(ctx, "user_preferences")
if err != nil {
    log.Fatal(err)
}
fmt.Println(entry.Value)

// By index (stack access)
latest, err := client.Clipboard.GetByIndex(ctx, 0)
Push to Stack
entry, err := client.Clipboard.Push(ctx, &pluggedin.ClipboardPushRequest{
    Value:       "Processing step 1 result",
    ContentType: "text/plain",
})
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Pushed to index: %d\n", *entry.Idx)
Pop from Stack
entry, err := client.Clipboard.Pop(ctx)
if err != nil {
    log.Fatal(err)
}
if entry != nil {
    fmt.Printf("Popped value: %s\n", entry.Value)
}
List and Delete
// List entries with pagination (limit: 100, offset: 0)
response, err := client.Clipboard.List(ctx, 100, 0)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Total: %d, Returned: %d\n", response.Total, len(response.Entries))

for _, entry := range response.Entries {
    var label string
    if entry.Name != nil {
        label = *entry.Name
    } else if entry.Idx != nil {
        label = fmt.Sprintf("idx:%d", *entry.Idx)
    }
    source := pluggedin.DefaultClipboardSource
    if entry.Source != nil {
        source = *entry.Source
    }
    fmt.Printf("%s - source: %s\n", label, source)
}

// Delete by name
name := "old_entry"
deleted, err := client.Clipboard.Delete(ctx, &pluggedin.ClipboardDeleteRequest{
    Name: &name,
})
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Deleted: %v\n", deleted)

// Clear all entries (bulk delete)
result, err := client.Clipboard.ClearAll(ctx)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Cleared %d entries\n", result.Deleted)
Clipboard Entry Structure
type ClipboardEntry struct {
    UUID           string            `json:"uuid"`
    Name           *string           `json:"name"`           // Semantic key
    Idx            *int              `json:"idx"`            // Stack index
    Value          string            `json:"value"`
    ContentType    string            `json:"contentType"`
    Encoding       string            `json:"encoding"`       // utf-8, base64, hex
    SizeBytes      int               `json:"sizeBytes"`
    Visibility     string            `json:"visibility"`     // private, workspace, public
    CreatedByTool  *string           `json:"createdByTool"`
    CreatedByModel *string           `json:"createdByModel"`
    Source         *ClipboardSource  `json:"source,omitempty"` // Auto-set: ui, sdk, mcp
    CreatedAt      time.Time         `json:"createdAt"`
    UpdatedAt      time.Time         `json:"updatedAt"`
    ExpiresAt      *time.Time        `json:"expiresAt"`
}

Note: The Source field is automatically set to ClipboardSourceSDK when using this SDK. It indicates how the entry was created (UI, SDK, or MCP proxy).

Error Handling
doc, err := client.Documents.Get(ctx, "invalid-id", false, false)
if err != nil {
    switch e := err.(type) {
    case *pluggedin.AuthenticationError:
        fmt.Println("Invalid API key")
    case *pluggedin.RateLimitError:
        fmt.Printf("Rate limited. Retry after %d seconds\n", e.RetryAfter)
    case *pluggedin.NotFoundError:
        fmt.Printf("Document not found: %s\n", e.ID)
    case *pluggedin.ValidationError:
        fmt.Printf("Validation error: %s\n", e.Message)
    case *pluggedin.APIError:
        fmt.Printf("API error (%d): %s\n", e.StatusCode, e.Message)
    default:
        fmt.Printf("Error: %v\n", err)
    }
}
Advanced Configuration
import (
    "net/http"
    "time"
)

// Custom HTTP client
httpClient := &http.Client{
    Timeout: 120 * time.Second,
    // Add custom transport, etc.
}

client := pluggedin.NewClientWithOptions(
    "your-api-key",
    "https://plugged.in",
    httpClient,
)

// Update API key at runtime
client.SetAPIKey("new-api-key")

// Change base URL
client.SetBaseURL("http://localhost:12005")

Environment Variables

Store your API key securely:

export PLUGGEDIN_API_KEY=your-api-key
export PLUGGEDIN_BASE_URL=https://plugged.in
import (
    "os"
    pluggedin "github.com/veriteknik/pluggedinkit-go"
)

client := pluggedin.NewClientWithOptions(
    os.Getenv("PLUGGEDIN_API_KEY"),
    os.Getenv("PLUGGEDIN_BASE_URL"),
    nil,
)

Rate Limiting

The SDK handles rate limiting automatically:

  • API Endpoints: 60 requests per minute
  • Document Search: 10 requests per hour for AI document creation
  • RAG Queries: Subject to plan limits

Examples

See the examples directory for complete working examples:

Contributing

Contributions are welcome! Please see our Contributing Guide for details.

License

MIT - see LICENSE for details.

Support

Changelog

See CHANGELOG.md for release history.

Documentation

Index

Constants

View Source
const (
	DefaultBaseURL = "https://plugged.in"
	DefaultTimeout = 60 * time.Second
	Version        = "1.0.1"
)
View Source
const DefaultClipboardSource = ClipboardSourceUI

DefaultClipboardSource is the default source for backward compatibility

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	StatusCode int
	Message    string
	Details    interface{}
}

APIError represents an API error

func (*APIError) Error

func (e *APIError) Error() string

type AuthenticationError

type AuthenticationError struct {
	Message string
}

AuthenticationError represents an authentication error

func (*AuthenticationError) Error

func (e *AuthenticationError) Error() string

type ClearAllResult

type ClearAllResult struct {
	Deleted int  `json:"deleted"` // Number of entries deleted
	Success bool `json:"success"` // Whether the operation was successful
}

ClearAllResult provides structured feedback from clearing all clipboard entries

type Client

type Client struct {

	// Services
	Clipboard *ClipboardService
	Documents *DocumentsService
	RAG       *RAGService
	Uploads   *UploadsService
	// contains filtered or unexported fields
}

Client is the main Plugged.in API client

func NewClient

func NewClient(apiKey string) *Client

NewClient creates a new Plugged.in API client

func NewClientWithOptions

func NewClientWithOptions(apiKey, baseURL string, httpClient *http.Client) *Client

NewClientWithOptions creates a new client with custom options

func (*Client) SetAPIKey

func (c *Client) SetAPIKey(apiKey string)

SetAPIKey updates the API key

func (*Client) SetBaseURL

func (c *Client) SetBaseURL(baseURL string)

SetBaseURL updates the base URL

type ClipboardDeleteRequest

type ClipboardDeleteRequest struct {
	Name *string `json:"name,omitempty"`
	Idx  *int    `json:"idx,omitempty"`
}

ClipboardDeleteRequest represents a request to delete a clipboard entry

type ClipboardDeleteResponse

type ClipboardDeleteResponse struct {
	Success bool   `json:"success"`
	Deleted bool   `json:"deleted,omitempty"`
	Error   string `json:"error,omitempty"`
}

ClipboardDeleteResponse represents the response from clipboard delete operations

type ClipboardEncoding

type ClipboardEncoding string

ClipboardEncoding represents clipboard content encoding

const (
	EncodingUTF8   ClipboardEncoding = "utf-8"
	EncodingBase64 ClipboardEncoding = "base64"
	EncodingHex    ClipboardEncoding = "hex"
)

type ClipboardEntry

type ClipboardEntry struct {
	UUID           string              `json:"uuid"`
	Name           *string             `json:"name,omitempty"`
	Idx            *int                `json:"idx,omitempty"`
	Value          string              `json:"value"`
	ContentType    string              `json:"contentType"`
	Encoding       ClipboardEncoding   `json:"encoding"`
	SizeBytes      int                 `json:"sizeBytes"`
	Visibility     ClipboardVisibility `json:"visibility"`
	CreatedByTool  *string             `json:"createdByTool,omitempty"`
	CreatedByModel *string             `json:"createdByModel,omitempty"`
	// Source is optional for backward compatibility with older API responses
	Source    *ClipboardSource `json:"source,omitempty"`
	CreatedAt time.Time        `json:"createdAt"`
	UpdatedAt time.Time        `json:"updatedAt"`
	ExpiresAt *time.Time       `json:"expiresAt,omitempty"`
}

ClipboardEntry represents a clipboard entry

type ClipboardGetFilters

type ClipboardGetFilters struct {
	Name *string `json:"name,omitempty"`
	Idx  *int    `json:"idx,omitempty"`
}

ClipboardGetFilters represents filters for getting a clipboard entry

type ClipboardListResponse

type ClipboardListResponse struct {
	Success bool             `json:"success"`
	Entries []ClipboardEntry `json:"entries"`
	Total   int              `json:"total,omitempty"`
	Limit   int              `json:"limit,omitempty"`
	Offset  int              `json:"offset,omitempty"`
}

ClipboardListResponse represents the response from listing clipboard entries

type ClipboardPushRequest

type ClipboardPushRequest struct {
	Value          string              `json:"value"`
	ContentType    string              `json:"contentType,omitempty"`
	Encoding       ClipboardEncoding   `json:"encoding,omitempty"`
	Visibility     ClipboardVisibility `json:"visibility,omitempty"`
	CreatedByTool  string              `json:"createdByTool,omitempty"`
	CreatedByModel string              `json:"createdByModel,omitempty"`
	TTLSeconds     int                 `json:"ttlSeconds,omitempty"`
}

ClipboardPushRequest represents a request to push to indexed clipboard

type ClipboardResponse

type ClipboardResponse struct {
	Success bool            `json:"success"`
	Entry   *ClipboardEntry `json:"entry,omitempty"`
	Error   string          `json:"error,omitempty"`
}

ClipboardResponse represents the response from clipboard operations

type ClipboardService

type ClipboardService struct {
	// contains filtered or unexported fields
}

ClipboardService handles clipboard-related operations

func (*ClipboardService) ClearAll

func (s *ClipboardService) ClearAll(ctx context.Context) (*ClearAllResult, error)

ClearAll clears all clipboard entries using bulk delete API. Returns a ClearAllResult with the count of deleted entries and success status.

func (*ClipboardService) Delete

Delete deletes a clipboard entry by name or index

func (*ClipboardService) DeleteByIndex

func (s *ClipboardService) DeleteByIndex(ctx context.Context, idx int) (bool, error)

DeleteByIndex deletes a clipboard entry by index (convenience method)

func (*ClipboardService) DeleteByName

func (s *ClipboardService) DeleteByName(ctx context.Context, name string) (bool, error)

DeleteByName deletes a clipboard entry by name (convenience method)

func (*ClipboardService) Get

Get retrieves a clipboard entry by name or index. Returns (nil, nil) if the entry is not found. Returns (nil, error) if there was an actual error.

func (*ClipboardService) GetByIndex

func (s *ClipboardService) GetByIndex(ctx context.Context, idx int) (*ClipboardEntry, error)

GetByIndex retrieves a clipboard entry by index (convenience method)

func (*ClipboardService) GetByName

func (s *ClipboardService) GetByName(ctx context.Context, name string) (*ClipboardEntry, error)

GetByName retrieves a clipboard entry by name (convenience method)

func (*ClipboardService) List

func (s *ClipboardService) List(ctx context.Context, limit, offset int) (*ClipboardListResponse, error)

List retrieves clipboard entries with optional pagination. limit: maximum number of entries to return (1-100, default: 50) offset: number of entries to skip (default: 0)

func (*ClipboardService) Pop

Pop pops the last indexed entry from clipboard. Returns (nil, nil) if the clipboard is empty. Returns (nil, error) if there was an actual error.

func (*ClipboardService) Push

Push pushes a value to the indexed clipboard (auto-increment index)

func (*ClipboardService) Set

Set sets a named clipboard entry (upsert)

type ClipboardSetRequest

type ClipboardSetRequest struct {
	Name           string              `json:"name"`
	Value          string              `json:"value"`
	ContentType    string              `json:"contentType,omitempty"`
	Encoding       ClipboardEncoding   `json:"encoding,omitempty"`
	Visibility     ClipboardVisibility `json:"visibility,omitempty"`
	CreatedByTool  string              `json:"createdByTool,omitempty"`
	CreatedByModel string              `json:"createdByModel,omitempty"`
	TTLSeconds     int                 `json:"ttlSeconds,omitempty"`
}

ClipboardSetRequest represents a request to set a named clipboard entry

type ClipboardSource

type ClipboardSource string

ClipboardSource represents the source of clipboard data

const (
	ClipboardSourceUI  ClipboardSource = "ui"
	ClipboardSourceSDK ClipboardSource = "sdk"
	ClipboardSourceMCP ClipboardSource = "mcp"
)

type ClipboardVisibility

type ClipboardVisibility string

ClipboardVisibility represents clipboard visibility

const (
	ClipboardVisibilityPrivate   ClipboardVisibility = "private"
	ClipboardVisibilityWorkspace ClipboardVisibility = "workspace"
	ClipboardVisibilityPublic    ClipboardVisibility = "public"
)

type CreateDocumentRequest

type CreateDocumentRequest struct {
	Title    string                 `json:"title"`
	Content  string                 `json:"content"`
	Format   string                 `json:"format,omitempty"`
	Category string                 `json:"category,omitempty"`
	Tags     []string               `json:"tags,omitempty"`
	Metadata map[string]interface{} `json:"metadata,omitempty"`
}

CreateDocumentRequest represents a request to create a document

type Document

type Document struct {
	ID                string             `json:"id"`
	Title             string             `json:"title"`
	Description       string             `json:"description,omitempty"`
	FileName          string             `json:"fileName"`
	FileSize          int64              `json:"fileSize"`
	MimeType          string             `json:"mimeType"`
	Tags              []string           `json:"tags,omitempty"`
	Source            DocumentSource     `json:"source"`
	Visibility        DocumentVisibility `json:"visibility"`
	Version           int                `json:"version"`
	CreatedAt         time.Time          `json:"createdAt"`
	UpdatedAt         time.Time          `json:"updatedAt"`
	AIMetadata        map[string]any     `json:"aiMetadata,omitempty"`
	ModelAttributions []ModelAttribution `json:"modelAttributions,omitempty"`
	Content           string             `json:"content,omitempty"`
	ContentEncoding   string             `json:"contentEncoding,omitempty"`
	ContentHash       string             `json:"contentHash,omitempty"`
	ParentDocumentID  string             `json:"parentDocumentId,omitempty"`
}

Document represents a document in the library

type DocumentCategory

type DocumentCategory string

DocumentCategory represents document category

const (
	CategoryReport        DocumentCategory = "report"
	CategoryAnalysis      DocumentCategory = "analysis"
	CategoryDocumentation DocumentCategory = "documentation"
	CategoryGuide         DocumentCategory = "guide"
	CategoryResearch      DocumentCategory = "research"
	CategoryCode          DocumentCategory = "code"
	CategoryOther         DocumentCategory = "other"
)

type DocumentFilters

type DocumentFilters struct {
	Source        DocumentSource   `json:"source,omitempty"`
	Tags          []string         `json:"tags,omitempty"`
	Category      DocumentCategory `json:"category,omitempty"`
	DateFrom      *time.Time       `json:"dateFrom,omitempty"`
	DateTo        *time.Time       `json:"dateTo,omitempty"`
	ModelProvider string           `json:"modelProvider,omitempty"`
	ModelName     string           `json:"modelName,omitempty"`
	SearchQuery   string           `json:"searchQuery,omitempty"`
	Sort          SortOrder        `json:"sort,omitempty"`
	Limit         int              `json:"limit,omitempty"`
	Offset        int              `json:"offset,omitempty"`
}

DocumentFilters represents filters for listing documents

type DocumentFormat

type DocumentFormat string

DocumentFormat represents document format

const (
	FormatMarkdown DocumentFormat = "md"
	FormatText     DocumentFormat = "txt"
	FormatJSON     DocumentFormat = "json"
	FormatHTML     DocumentFormat = "html"
)

type DocumentSource

type DocumentSource string

DocumentSource represents the source of a document

const (
	SourceAll         DocumentSource = "all"
	SourceUpload      DocumentSource = "upload"
	SourceAIGenerated DocumentSource = "ai_generated"
	SourceAPI         DocumentSource = "api"
)

type DocumentVisibility

type DocumentVisibility string

DocumentVisibility represents document visibility

const (
	VisibilityPrivate   DocumentVisibility = "private"
	VisibilityWorkspace DocumentVisibility = "workspace"
	VisibilityPublic    DocumentVisibility = "public"
)

type DocumentsService

type DocumentsService struct {
	// contains filtered or unexported fields
}

DocumentsService handles document-related operations

func (*DocumentsService) Create

Create creates a new AI-generated document

func (*DocumentsService) Delete

func (s *DocumentsService) Delete(ctx context.Context, documentID string) error

Delete deletes a document

func (*DocumentsService) Download

func (s *DocumentsService) Download(ctx context.Context, documentID string, projectUUID string) ([]byte, error)

Download downloads a document file

func (*DocumentsService) Get

func (s *DocumentsService) Get(ctx context.Context, documentID string, includeContent, includeVersions bool) (*Document, error)

Get retrieves a specific document by ID

func (*DocumentsService) List

List retrieves a list of documents with optional filters

func (*DocumentsService) Search

func (s *DocumentsService) Search(ctx context.Context, query string, filters map[string]interface{}, limit, offset int) (*SearchResponse, error)

Search performs a semantic search on documents

func (*DocumentsService) Update

Update updates an existing document

type ErrorResponse

type ErrorResponse struct {
	Error   string      `json:"error"`
	Message string      `json:"message"`
	Details interface{} `json:"details,omitempty"`
}

ErrorResponse represents an error response from the API

type FileUpload

type FileUpload struct {
	Path     string
	Metadata *UploadMetadata
}

FileUpload represents a file to upload (retained for compatibility).

type ListDocumentsResponse

type ListDocumentsResponse struct {
	Documents []Document `json:"documents"`
	Total     int        `json:"total"`
	Limit     int        `json:"limit"`
	Offset    int        `json:"offset"`
}

ListDocumentsResponse represents the response from listing documents

type ModelAttribution

type ModelAttribution struct {
	ModelName        string         `json:"modelName"`
	ModelProvider    string         `json:"modelProvider"`
	ContributionType string         `json:"contributionType"`
	Timestamp        time.Time      `json:"timestamp"`
	Metadata         map[string]any `json:"metadata,omitempty"`
}

ModelAttribution represents model contribution metadata

type NotFoundError

type NotFoundError struct {
	Resource string
	ID       string
}

NotFoundError represents a not found error

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

type ProgressCallback

type ProgressCallback func(percent int)

ProgressCallback is retained for backwards compatibility.

type RAGDocumentReference

type RAGDocumentReference struct {
	DocumentID string `json:"documentId"`
	Source     string `json:"source,omitempty"`
}

RAGDocumentReference represents a matched document reference

type RAGResponse

type RAGResponse struct {
	Success     bool     `json:"success"`
	Answer      string   `json:"answer,omitempty"`
	Sources     []string `json:"sources,omitempty"`
	DocumentIDs []string `json:"documentIds,omitempty"`
	Error       string   `json:"error,omitempty"`
}

RAGResponse represents a RAG query response

type RAGService

type RAGService struct {
	// contains filtered or unexported fields
}

RAGService handles RAG-related operations

func (*RAGService) AskQuestion

func (s *RAGService) AskQuestion(ctx context.Context, query string) (string, error)

AskQuestion performs a simple RAG query and returns the answer text.

func (*RAGService) CheckAvailability

func (s *RAGService) CheckAvailability(ctx context.Context) (map[string]interface{}, error)

CheckAvailability checks if the RAG service is reachable.

func (*RAGService) FindRelevantDocuments

func (s *RAGService) FindRelevantDocuments(ctx context.Context, query, _ string, limit int) ([]RAGDocumentReference, error)

FindRelevantDocuments finds documents relevant to a query.

func (*RAGService) GetStorageStats

func (s *RAGService) GetStorageStats(ctx context.Context, userID string) (*RAGStorageStats, error)

GetStorageStats gets storage statistics for RAG.

func (*RAGService) Query

func (s *RAGService) Query(ctx context.Context, query string) (*RAGResponse, error)

Query performs a RAG query and returns the raw response.

func (*RAGService) QueryWithSources

func (s *RAGService) QueryWithSources(ctx context.Context, query, _ string) (*RAGResponse, error)

QueryWithSources performs a RAG query and returns the response with metadata.

type RAGStorageStats

type RAGStorageStats struct {
	DocumentsCount     int     `json:"documents_count"`
	TotalChunks        int     `json:"total_chunks"`
	EstimatedStorageMB float64 `json:"estimated_storage_mb"`
	VectorsCount       int     `json:"vectors_count,omitempty"`
	EmbeddingDimension int     `json:"embedding_dimension,omitempty"`
	IsEstimate         bool    `json:"is_estimate,omitempty"`
}

RAGStorageStats represents storage metrics returned by the API

type RateLimitError

type RateLimitError struct {
	Message    string
	RetryAfter int
}

RateLimitError represents a rate limit error

func (*RateLimitError) Error

func (e *RateLimitError) Error() string

type SearchResponse

type SearchResponse struct {
	Results []SearchResult `json:"results"`
	Total   int            `json:"total"`
	Limit   int            `json:"limit"`
	Offset  int            `json:"offset"`
	HasMore bool           `json:"hasMore"`
}

SearchResponse represents the response from searching documents

type SearchResult

type SearchResult struct {
	ID                string             `json:"id"`
	Title             string             `json:"title"`
	Description       string             `json:"description,omitempty"`
	Snippet           string             `json:"snippet"`
	RelevanceScore    float64            `json:"relevanceScore"`
	Source            string             `json:"source"`
	AIMetadata        map[string]any     `json:"aiMetadata,omitempty"`
	Tags              []string           `json:"tags,omitempty"`
	Visibility        string             `json:"visibility"`
	CreatedAt         time.Time          `json:"createdAt"`
	ModelAttributions []ModelAttribution `json:"modelAttributions,omitempty"`
}

SearchResult represents a search result

type SortOrder

type SortOrder string

SortOrder represents sort order for listing

const (
	SortDateDesc SortOrder = "date_desc"
	SortDateAsc  SortOrder = "date_asc"
	SortTitle    SortOrder = "title"
	SortSize     SortOrder = "size"
)

type UpdateDocumentRequest

type UpdateDocumentRequest struct {
	Operation UpdateOperation        `json:"operation"`
	Content   string                 `json:"content"`
	Metadata  map[string]interface{} `json:"metadata,omitempty"`
}

UpdateDocumentRequest represents a request to update a document

type UpdateDocumentResponse

type UpdateDocumentResponse struct {
	Success     bool   `json:"success"`
	DocumentID  string `json:"documentId"`
	Version     int    `json:"version"`
	FileWritten bool   `json:"fileWritten"`
	Message     string `json:"message,omitempty"`
}

UpdateDocumentResponse represents the response from updating a document

type UpdateOperation

type UpdateOperation string

UpdateOperation represents update operations

const (
	OpReplace UpdateOperation = "replace"
	OpAppend  UpdateOperation = "append"
	OpPrepend UpdateOperation = "prepend"
)

type UploadMetadata

type UploadMetadata struct {
	Name        string   `json:"name"`
	Description string   `json:"description,omitempty"`
	Tags        []string `json:"tags,omitempty"`
	Purpose     string   `json:"purpose,omitempty"`
	RelatedTo   string   `json:"relatedTo,omitempty"`
	ProjectID   string   `json:"projectId,omitempty"`
}

UploadMetadata represents metadata for file uploads

type UploadResponse

type UploadResponse struct {
	Success    bool   `json:"success"`
	DocumentID string `json:"documentId,omitempty"`
	UploadID   string `json:"uploadId,omitempty"`
	Error      string `json:"error,omitempty"`
	Message    string `json:"message,omitempty"`
}

UploadResponse represents the response from uploading a file

type UploadStatus

type UploadStatus struct {
	UploadID string `json:"uploadId"`
	Status   string `json:"status"`
	Message  string `json:"message"`
	Progress int    `json:"progress"`
}

UploadStatus represents the status of an upload

type UploadsService

type UploadsService struct {
	// contains filtered or unexported fields
}

UploadsService handles upload operations. The public API no longer exposes direct binary upload endpoints. The methods now return informative errors to help consumers migrate to the supported flows.

func (*UploadsService) TrackUpload

func (s *UploadsService) TrackUpload(ctx context.Context, uploadID string, onUpdate func(status *UploadStatus)) error

TrackUpload is no longer supported.

func (*UploadsService) UploadBatch

func (s *UploadsService) UploadBatch(ctx context.Context, files []FileUpload, onProgress func(current, total int)) ([]UploadResponse, error)

UploadBatch is no longer supported.

func (*UploadsService) UploadFile

func (s *UploadsService) UploadFile(ctx context.Context, filePath string, metadata *UploadMetadata, onProgress ProgressCallback) (*UploadResponse, error)

UploadFile is no longer supported.

func (*UploadsService) UploadReader

func (s *UploadsService) UploadReader(ctx context.Context, reader io.Reader, size int64, metadata *UploadMetadata, onProgress ProgressCallback) (*UploadResponse, error)

UploadReader is no longer supported.

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

ValidationError represents a validation error

func (*ValidationError) Error

func (e *ValidationError) Error() string

Directories

Path Synopsis
examples
basic command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL