Go

Go Examples

Use QuietStack with Go - just HTTP requests using the standard library

No External Dependencies Required!

These examples use only Go's standard library for HTTP requests. For the web server example, we use popular packages: go get github.com/gorilla/mux github.com/rs/cors

Basic HTTP Request

Simple example using Go's standard http package

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "log"
)

type Message struct {
    Role    string `json:"role"`
    Content string `json:"content"`
}

type Request struct {
    Provider string    `json:"provider"`
    Model    string    `json:"model"`
    Messages []Message `json:"messages"`
}

type Usage struct {
    PromptTokens     int     `json:"prompt_tokens"`
    CompletionTokens int     `json:"completion_tokens"`
    TotalTokens      int     `json:"total_tokens"`
    Cost             float64 `json:"cost"`
}

type Verification struct {
    Hash         string `json:"hash"`
    BlockchainTx string `json:"blockchain_tx"`
    Timestamp    string `json:"timestamp"`
    Network      string `json:"network"`
}

type Response struct {
    Response     string       `json:"response"`
    Usage        Usage        `json:"usage"`
    Verification Verification `json:"verification"`
}

func callQuietStack(prompt string) (*Response, error) {
    url := "https://api.quietstack.ai/v1/proxy"
    
    reqBody := Request{
        Provider: "openai",
        Model:    "gpt-3.5-turbo",
        Messages: []Message{
            {
                Role:    "user",
                Content: prompt,
            },
        },
    }
    
    jsonData, err := json.Marshal(reqBody)
    if err != nil {
        return nil, fmt.Errorf("error marshaling request: %v", err)
    }
    
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
    if err != nil {
        return nil, fmt.Errorf("error creating request: %v", err)
    }
    
    req.Header.Set("Authorization", "Bearer qs_live_YOUR_API_KEY")
    req.Header.Set("Content-Type", "application/json")
    
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        return nil, fmt.Errorf("error making request: %v", err)
    }
    defer resp.Body.Close()
    
    body, err := io.ReadAll(resp.Body)
    if err != nil {
        return nil, fmt.Errorf("error reading response: %v", err)
    }
    
    var response Response
    err = json.Unmarshal(body, &response)
    if err != nil {
        return nil, fmt.Errorf("error unmarshaling response: %v", err)
    }
    
    return &response, nil
}

func main() {
    response, err := callQuietStack("What is the capital of France?")
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Printf("AI Response: %s\n", response.Response)
    fmt.Printf("Cost: $%.6f\n", response.Usage.Cost)
    fmt.Printf("Blockchain Hash: %s\n", response.Verification.Hash)
}

Structured Client

Reusable client with proper error handling and type safety

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
    "time"
)

// QuietStackClient provides methods for interacting with QuietStack API
type QuietStackClient struct {
    APIKey  string
    BaseURL string
    Client  *http.Client
}

// NewClient creates a new QuietStack client
func NewClient(apiKey string) *QuietStackClient {
    return &QuietStackClient{
        APIKey:  apiKey,
        BaseURL: "https://api.quietstack.ai/v1",
        Client: &http.Client{
            Timeout: 30 * time.Second,
        },
    }
}

// ChatRequest represents a chat completion request
type ChatRequest struct {
    Provider string    `json:"provider"`
    Model    string    `json:"model"`
    Messages []Message `json:"messages"`
}

// ChatResponse represents a chat completion response
type ChatResponse struct {
    Response     string       `json:"response"`
    Usage        Usage        `json:"usage"`
    Verification Verification `json:"verification"`
    Metadata     Metadata     `json:"metadata"`
}

type Metadata struct {
    Provider  string `json:"provider"`
    Model     string `json:"model"`
    RequestID string `json:"request_id"`
}

// Chat sends a chat completion request
func (c *QuietStackClient) Chat(request ChatRequest) (*ChatResponse, error) {
    jsonData, err := json.Marshal(request)
    if err != nil {
        return nil, fmt.Errorf("failed to marshal request: %w", err)
    }
    
    req, err := http.NewRequest("POST", c.BaseURL+"/proxy", bytes.NewBuffer(jsonData))
    if err != nil {
        return nil, fmt.Errorf("failed to create request: %w", err)
    }
    
    req.Header.Set("Authorization", "Bearer "+c.APIKey)
    req.Header.Set("Content-Type", "application/json")
    
    resp, err := c.Client.Do(req)
    if err != nil {
        return nil, fmt.Errorf("failed to make request: %w", err)
    }
    defer resp.Body.Close()
    
    if resp.StatusCode != http.StatusOK {
        body, _ := io.ReadAll(resp.Body)
        return nil, fmt.Errorf("API error %d: %s", resp.StatusCode, string(body))
    }
    
    var response ChatResponse
    if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
        return nil, fmt.Errorf("failed to decode response: %w", err)
    }
    
    return &response, nil
}

// SimpleChat is a convenience method for simple chat requests
func (c *QuietStackClient) SimpleChat(prompt, provider, model string) (*ChatResponse, error) {
    if provider == "" {
        provider = "openai"
    }
    if model == "" {
        model = "gpt-3.5-turbo"
    }
    
    request := ChatRequest{
        Provider: provider,
        Model:    model,
        Messages: []Message{
            {
                Role:    "user",
                Content: prompt,
            },
        },
    }
    
    return c.Chat(request)
}

func main() {
    // Get API key from environment variable
    apiKey := os.Getenv("QUIETSTACK_API_KEY")
    if apiKey == "" {
        fmt.Println("Please set QUIETSTACK_API_KEY environment variable")
        os.Exit(1)
    }
    
    client := NewClient(apiKey)
    
    // Simple chat example
    response, err := client.SimpleChat("Explain blockchain verification", "openai", "gpt-4")
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
    
    fmt.Printf("Response: %s\n\n", response.Response)
    fmt.Printf("Usage: %d tokens ($%.6f)\n", response.Usage.TotalTokens, response.Usage.Cost)
    fmt.Printf("Verified: %s\n", response.Verification.Hash)
    fmt.Printf("Transaction: %s\n", response.Verification.BlockchainTx)
}

HTTP Web Server

Complete web server with QuietStack integration

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "os"
    
    "github.com/gorilla/mux"
    "github.com/rs/cors"
)

type Server struct {
    client *QuietStackClient
}

type ChatRequest struct {
    Message  string `json:"message"`
    Provider string `json:"provider,omitempty"`
    Model    string `json:"model,omitempty"`
}

type ChatResponse struct {
    Response        string  `json:"response"`
    Verified        bool    `json:"verified"`
    BlockchainHash  string  `json:"blockchain_hash"`
    Cost            float64 `json:"cost"`
}

func (s *Server) handleChat(w http.ResponseWriter, r *http.Request) {
    var req ChatRequest
    if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
        http.Error(w, "Invalid request body", http.StatusBadRequest)
        return
    }
    
    if req.Message == "" {
        http.Error(w, "Message is required", http.StatusBadRequest)
        return
    }
    
    // Default values
    if req.Provider == "" {
        req.Provider = "openai"
    }
    if req.Model == "" {
        req.Model = "gpt-3.5-turbo"
    }
    
    // Call QuietStack API
    response, err := s.client.SimpleChat(req.Message, req.Provider, req.Model)
    if err != nil {
        log.Printf("QuietStack API error: %v", err)
        http.Error(w, "Failed to process request", http.StatusInternalServerError)
        return
    }
    
    // Return response
    chatResp := ChatResponse{
        Response:       response.Response,
        Verified:       true,
        BlockchainHash: response.Verification.Hash,
        Cost:           response.Usage.Cost,
    }
    
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(chatResp)
}

func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    json.NewEncoder(w).Encode(map[string]string{"status": "healthy"})
}

func main() {
    apiKey := os.Getenv("QUIETSTACK_API_KEY")
    if apiKey == "" {
        log.Fatal("QUIETSTACK_API_KEY environment variable is required")
    }
    
    client := NewClient(apiKey)
    server := &Server{client: client}
    
    r := mux.NewRouter()
    
    // Routes
    r.HandleFunc("/chat", server.handleChat).Methods("POST")
    r.HandleFunc("/health", server.handleHealth).Methods("GET")
    
    // CORS
    c := cors.New(cors.Options{
        AllowedOrigins: []string{"*"},
        AllowedMethods: []string{"GET", "POST", "OPTIONS"},
        AllowedHeaders: []string{"*"},
    })
    
    handler := c.Handler(r)
    
    port := os.Getenv("PORT")
    if port == "" {
        port = "8080"
    }
    
    fmt.Printf("Server starting on port %s\n", port)
    log.Fatal(http.ListenAndServe(":"+port, handler))
}

/*
Test with:
curl -X POST http://localhost:8080/chat \
  -H "Content-Type: application/json" \
  -d '{"message": "Hello, world!"}'
*/

Project Setup

go.mod file for the web server example with dependencies

1. Initialize Go module:

go mod init quietstack-example

2. go.mod file:

module quietstack-example

go 1.19

require (
    github.com/gorilla/mux v1.8.0
    github.com/rs/cors v1.8.3
)

3. Install dependencies:

go get github.com/gorilla/mux github.com/rs/cors

Environment Setup

Secure your API key using environment variables

1. Set environment variable:

export QUIETSTACK_API_KEY=qs_live_your_actual_api_key_here

2. Use in Go code:

import "os"

apiKey := os.Getenv("QUIETSTACK_API_KEY")
if apiKey == "" {
    log.Fatal("QUIETSTACK_API_KEY environment variable is required")
}

Ready to try it out?

Get your API key and start building blockchain-verified AI applications with Go