Go SDK

Official Go client library for the Archivus API.

Archivus is built with Go, making this SDK the most natural integration for Go applications.


Installation

go get github.com/ubiship/archivus-go

Quick Start

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/ubiship/archivus-go"
)

func main() {
    // Initialize client with API key
    client := archivus.NewClient(
        archivus.WithAPIKey("ak_live_YOUR_API_KEY"),
    )

    // List documents
    ctx := context.Background()
    docs, err := client.Documents.List(ctx, &archivus.ListDocumentsParams{
        PageSize: 20,
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, doc := range docs.Data {
        fmt.Printf("Document: %s (%s)\n", doc.Filename, doc.ID)
    }
}

Authentication

client := archivus.NewClient(
    archivus.WithAPIKey("ak_live_YOUR_API_KEY"),
)

JWT Token

client := archivus.NewClient(
    archivus.WithToken("YOUR_JWT_TOKEN"),
    archivus.WithTenant("your-tenant"),
)

Custom Base URL

client := archivus.NewClient(
    archivus.WithAPIKey("ak_live_YOUR_API_KEY"),
    archivus.WithBaseURL("https://api.archivus.app"),
)

Documents

Upload a Document

file, err := os.Open("document.pdf")
if err != nil {
    log.Fatal(err)
}
defer file.Close()

doc, err := client.Documents.Upload(ctx, &archivus.UploadParams{
    File:     file,
    Filename: "document.pdf",
    FolderID: "folder_123", // optional
})
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Uploaded: %s\n", doc.ID)

List Documents

docs, err := client.Documents.List(ctx, &archivus.ListDocumentsParams{
    Page:     1,
    PageSize: 20,
    FolderID: "folder_123", // optional
    Status:   "completed",  // optional
})

Get Document

doc, err := client.Documents.Get(ctx, "doc_abc123")

Update Document

doc, err := client.Documents.Update(ctx, "doc_abc123", &archivus.UpdateDocumentParams{
    Filename:    "renamed.pdf",
    Description: "Updated description",
})

Delete Document

err := client.Documents.Delete(ctx, "doc_abc123")

Download Document

reader, err := client.Documents.Download(ctx, "doc_abc123")
if err != nil {
    log.Fatal(err)
}
defer reader.Close()

// Write to file
out, _ := os.Create("downloaded.pdf")
defer out.Close()
io.Copy(out, reader)

Chat & AI

Create Chat Session

session, err := client.Chat.CreateSession(ctx, &archivus.CreateSessionParams{
    DocumentIDs: []string{"doc_abc123"},
    Name:        "Research Session",
})

Ask a Question

response, err := client.Chat.Ask(ctx, session.ID, &archivus.AskParams{
    Question: "What are the key findings in this document?",
})

fmt.Println(response.Answer)

Ask with RAG (Pro+)

response, err := client.Chat.AskRAG(ctx, session.ID, &archivus.AskRAGParams{
    Question:    "Find information about revenue projections",
    MaxSources:  5,
    MinRelevance: 0.7,
})

fmt.Println(response.Answer)
for _, source := range response.Sources {
    fmt.Printf("- %s (relevance: %.2f)\n", source.DocumentName, source.Relevance)
}

results, err := client.Search.Semantic(ctx, &archivus.SemanticSearchParams{
    Query:    "quarterly financial performance",
    Limit:    10,
    FolderID: "folder_123", // optional
})

for _, result := range results.Documents {
    fmt.Printf("%s (score: %.2f)\n", result.Filename, result.Score)
}
results, err := client.Search.Hybrid(ctx, &archivus.HybridSearchParams{
    Query:         "contract renewal terms",
    SemanticWeight: 0.7,
    KeywordWeight:  0.3,
})

Folders

Create Folder

folder, err := client.Folders.Create(ctx, &archivus.CreateFolderParams{
    Name:     "Contracts",
    ParentID: "folder_parent", // optional
})

List Folders

folders, err := client.Folders.List(ctx, &archivus.ListFoldersParams{
    ParentID: "", // root level
})

Get Folder Tree

tree, err := client.Folders.GetTree(ctx, "folder_123")

Tags

Generate Tags (AI)

tags, err := client.Documents.GenerateTags(ctx, "doc_abc123")

for _, tag := range tags {
    fmt.Printf("Tag: %s (confidence: %.2f)\n", tag.Name, tag.Confidence)
}

Add Tag

err := client.Documents.AddTag(ctx, "doc_abc123", "tag_xyz")

List Tags

tags, err := client.Tags.List(ctx, &archivus.ListTagsParams{
    Popular: true,
})

Error Handling

doc, err := client.Documents.Get(ctx, "doc_nonexistent")
if err != nil {
    var apiErr *archivus.APIError
    if errors.As(err, &apiErr) {
        switch apiErr.Code {
        case "NOT_FOUND":
            fmt.Println("Document not found")
        case "FORBIDDEN":
            fmt.Println("Access denied")
        case "RATE_LIMITED":
            fmt.Printf("Rate limited. Retry after %d seconds\n", apiErr.RetryAfter)
        default:
            fmt.Printf("API error: %s\n", apiErr.Message)
        }
    } else {
        fmt.Printf("Network error: %v\n", err)
    }
}

Configuration Options

client := archivus.NewClient(
    archivus.WithAPIKey("ak_live_YOUR_API_KEY"),
    archivus.WithBaseURL("https://api.archivus.app"),
    archivus.WithTimeout(30 * time.Second),
    archivus.WithRetries(3),
    archivus.WithHTTPClient(customHTTPClient),
    archivus.WithDebug(true), // Enable request logging
)

Context and Cancellation

All methods accept a context.Context for cancellation and timeouts:

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

docs, err := client.Documents.List(ctx, nil)
if err != nil {
    if errors.Is(err, context.DeadlineExceeded) {
        fmt.Println("Request timed out")
    }
}

Pagination

var allDocs []archivus.Document

params := &archivus.ListDocumentsParams{
    Page:     1,
    PageSize: 100,
}

for {
    result, err := client.Documents.List(ctx, params)
    if err != nil {
        log.Fatal(err)
    }

    allDocs = append(allDocs, result.Data...)

    if params.Page >= result.TotalPages {
        break
    }
    params.Page++
}

Webhooks

Verify Webhook Signature

func webhookHandler(w http.ResponseWriter, r *http.Request) {
    body, _ := io.ReadAll(r.Body)
    signature := r.Header.Get("X-Archivus-Signature")

    valid := archivus.VerifyWebhookSignature(body, signature, webhookSecret)
    if !valid {
        http.Error(w, "Invalid signature", http.StatusUnauthorized)
        return
    }

    var event archivus.WebhookEvent
    json.Unmarshal(body, &event)

    switch event.Type {
    case "document.processed":
        fmt.Printf("Document processed: %s\n", event.Data.DocumentID)
    case "document.deleted":
        fmt.Printf("Document deleted: %s\n", event.Data.DocumentID)
    }

    w.WriteHeader(http.StatusOK)
}

Complete Example

package main

import (
    "context"
    "fmt"
    "log"
    "os"

    "github.com/ubiship/archivus-go"
)

func main() {
    client := archivus.NewClient(
        archivus.WithAPIKey(os.Getenv("ARCHIVUS_API_KEY")),
    )

    ctx := context.Background()

    // Create a folder
    folder, err := client.Folders.Create(ctx, &archivus.CreateFolderParams{
        Name: "Q4 Reports",
    })
    if err != nil {
        log.Fatal(err)
    }

    // Upload a document
    file, _ := os.Open("report.pdf")
    defer file.Close()

    doc, err := client.Documents.Upload(ctx, &archivus.UploadParams{
        File:     file,
        Filename: "Q4-2024-Report.pdf",
        FolderID: folder.ID,
    })
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Uploaded document: %s\n", doc.ID)

    // Generate AI tags
    tags, err := client.Documents.GenerateTags(ctx, doc.ID)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("Generated tags:")
    for _, tag := range tags {
        fmt.Printf("  - %s\n", tag.Name)
    }

    // Start a chat session
    session, err := client.Chat.CreateSession(ctx, &archivus.CreateSessionParams{
        DocumentIDs: []string{doc.ID},
    })
    if err != nil {
        log.Fatal(err)
    }

    // Ask a question
    response, err := client.Chat.Ask(ctx, session.ID, &archivus.AskParams{
        Question: "What are the main highlights from this report?",
    })
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("\nAI Response:")
    fmt.Println(response.Answer)
}

Resources


Questions? Contact support@ubiship.com