tinfoil

package module
v0.12.1 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2026 License: AGPL-3.0 Imports: 15 Imported by: 0

README

Tinfoil Go Client

Build Status Documentation

For complete documentation, see the Go SDK documentation.

Installation

Add the Tinfoil SDK to your project:

go get github.com/tinfoilsh/tinfoil-go

Quick Start

The Tinfoil Go client is a wrapper around the OpenAI Go client v3 and provides secure communication with Tinfoil enclaves. It has the same API as the OpenAI client, with additional security features:

  • Automatic attestation validation to ensure enclave integrity verification
  • Supports Encrypted HTTP Body Protocol to provide direct-to-enclave encrypted communication with attested public keys
  • Supports a fallback mode with TLS certificate pinning using attested certificates to provide direct-to-enclave encrypted communication over TLS
package main

import (
	"context"
	"fmt"
	"log"

    "github.com/openai/openai-go/v3"
    "github.com/openai/openai-go/v3/option"
	"github.com/tinfoilsh/tinfoil-go"
)

func main() {
	// Create a client
	client, err := tinfoil.NewClient(
		option.WithAPIKey("<YOUR_API_KEY>"),
	)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	// Make requests using the OpenAI client API
	// Note: enclave verification and direct-to-enclave encryption happens automatically
	chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{
		Messages: []openai.ChatCompletionMessageParamUnion{
			openai.UserMessage("Say this is a test"),
		},
		Model: "llama3-3-70b", // see https://docs.tinfoil.sh/models/catalog for supported models
	})

	if err != nil {
		log.Fatalf("Chat completion error: %v", err)
	}

	fmt.Println(chatCompletion.Choices[0].Message.Content)
}

Usage

// 1. Create a client
client, err := tinfoil.NewClient(
	option.WithAPIKey(os.Getenv("TINFOIL_API_KEY")),
)
if err != nil {
	log.Printf("Failed to create client: %v", err)
	return
}

// 2. Use client as you would openai.Client
// see https://pkg.go.dev/github.com/openai/openai-go/v3 for API documentation

Advanced Functionality

// Create a secure client with explicit enclave and repo parameters
client, err := tinfoil.NewClientWithParams(enclave, repo)
if err != nil {
	return fmt.Errorf("Failed to create client: %v", err)
}

// For direct HTTP access, use the underlying HTTPClient
httpClient := client.HTTPClient()
endpoint := fmt.Sprintf("https://%s/health", enclave)
resp, err := httpClient.Get(endpoint)
if err != nil {
	return fmt.Errorf("Request failed: %v", err)
}

API Documentation

This library is a drop-in replacement for the official OpenAI Go client that can be used with Tinfoil. All methods and types are identical. See the OpenAI Go client documentation for complete API usage and documentation.

Go Reference

Reporting Vulnerabilities

Please report security vulnerabilities by either:

We aim to respond to (legitimate) security reports within 24 hours.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Annotation added in v0.11.2

type Annotation struct {
	Type        string      `json:"type"` // "url_citation"
	URLCitation URLCitation `json:"url_citation"`
}

Annotation represents a citation or reference in the response.

type BlockedSearch added in v0.11.2

type BlockedSearch struct {
	ID     string `json:"id"`
	Query  string `json:"query"`
	Reason string `json:"reason,omitempty"`
}

BlockedSearch represents a search that was blocked due to PII.

type Client

type Client struct {
	*openai.Client
	// contains filtered or unexported fields
}

Client wraps the OpenAI client to provide secure inference through Tinfoil

func NewClient

func NewClient(openaiOpts ...option.RequestOption) (*Client, error)

NewClient creates a new secure OpenAI client using default parameters

func NewClientWithParams

func NewClientWithParams(enclave, repo string, openaiOpts ...option.RequestOption) (*Client, error)

NewClientWithParams creates a new secure OpenAI client with explicit enclave and repo parameters

func (*Client) Enclave added in v0.1.2

func (c *Client) Enclave() string

func (*Client) HTTPClient added in v0.12.0

func (c *Client) HTTPClient() *http.Client

HTTPClient returns the underlying HTTP client that is configured with automatic certificate re-verification and is restricted to TLS connections to the verified enclave. This can be used for secure, direct HTTP requests to the enclave.

func (*Client) Repo added in v0.1.2

func (c *Client) Repo() string

func (*Client) Verify added in v0.11.1

func (c *Client) Verify() (*client.GroundTruth, error)

Verify re-verifies the enclave attestation and returns the ground truth

type ReasoningItem added in v0.11.2

type ReasoningItem struct {
	ID      string        `json:"id"`
	Type    string        `json:"type"` // "reasoning"
	Summary []SummaryPart `json:"summary,omitempty"`
}

ReasoningItem represents a reasoning step from the agent model.

type SummaryPart added in v0.11.2

type SummaryPart struct {
	Type string `json:"type"` // "summary_text"
	Text string `json:"text"`
}

SummaryPart represents a part of the reasoning summary.

type URLCitation added in v0.11.2

type URLCitation struct {
	Title         string `json:"title"`
	URL           string `json:"url"`
	Content       string `json:"content,omitempty"`
	PublishedDate string `json:"published_date,omitempty"`
}

URLCitation contains details about a cited source.

type WebSearchAction added in v0.11.2

type WebSearchAction struct {
	Type  string `json:"type"`  // Always "search"
	Query string `json:"query"` // The search query
}

WebSearchAction contains the search query details.

type WebSearchCall added in v0.11.2

type WebSearchCall struct {
	Type   string           `json:"type"`             // Always "web_search_call"
	ID     string           `json:"id"`               // Unique identifier (e.g., "ws_abc123")
	Status string           `json:"status"`           // "in_progress", "completed", "failed", or "blocked"
	Reason string           `json:"reason,omitempty"` // Present when status is "failed" or "blocked"
	Action *WebSearchAction `json:"action,omitempty"`
}

WebSearchCall represents a web search event emitted during streaming. These events are emitted before chat completion chunks and track search progress.

type WebSearchChoice added in v0.11.2

type WebSearchChoice struct {
	Index        int             `json:"index"`
	Delta        *WebSearchDelta `json:"delta,omitempty"`
	FinishReason string          `json:"finish_reason,omitempty"`
}

WebSearchChoice represents a choice in the chat completion chunk with web search metadata.

type WebSearchDelta added in v0.11.2

type WebSearchDelta struct {
	Content         string          `json:"content,omitempty"`
	Annotations     []Annotation    `json:"annotations,omitempty"`
	SearchReasoning string          `json:"search_reasoning,omitempty"`
	ReasoningItems  []ReasoningItem `json:"reasoning_items,omitempty"`
}

WebSearchDelta extends the standard delta with web search metadata. These fields appear in the metadata chunk before content chunks.

type WebSearchMessage added in v0.11.2

type WebSearchMessage struct {
	Content         string          `json:"content"`
	Annotations     []Annotation    `json:"annotations,omitempty"`
	SearchReasoning string          `json:"search_reasoning,omitempty"`
	ReasoningItems  []ReasoningItem `json:"reasoning_items,omitempty"`
	BlockedSearches []BlockedSearch `json:"blocked_searches,omitempty"`
}

WebSearchMessage extends the standard message with web search metadata. Used in non-streaming responses.

func ParseWebSearchMessage added in v0.11.2

func ParseWebSearchMessage(body []byte) (*WebSearchMessage, error)

ParseWebSearchMessage parses a non-streaming response body into a WebSearchMessage.

func ParseWebSearchResponse added in v0.11.2

func ParseWebSearchResponse(body io.Reader) (*WebSearchMessage, error)

ParseWebSearchResponse is a convenience function that reads and parses a response body.

type WebSearchStream added in v0.11.2

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

WebSearchStream wraps a streaming response and parses web search events.

func NewWebSearchStream added in v0.11.2

func NewWebSearchStream(body io.ReadCloser) *WebSearchStream

NewWebSearchStream creates a new WebSearchStream from a streaming HTTP response body.

func SimulateWebSearchStream added in v0.11.2

func SimulateWebSearchStream(data string) *WebSearchStream

SimulateWebSearchStream creates a WebSearchStream from raw SSE data (useful for testing).

func (*WebSearchStream) Close added in v0.11.2

func (s *WebSearchStream) Close() error

Close closes the underlying reader.

func (*WebSearchStream) Current added in v0.11.2

func (s *WebSearchStream) Current() *WebSearchStreamEvent

Current returns the current event in the stream. Must be called after Next() returns true.

func (*WebSearchStream) Err added in v0.11.2

func (s *WebSearchStream) Err() error

Err returns any error that occurred during streaming.

func (*WebSearchStream) Next added in v0.11.2

func (s *WebSearchStream) Next() bool

Next advances to the next event in the stream. Returns true if there is a next event, false if the stream is exhausted or an error occurred.

type WebSearchStreamEvent added in v0.11.2

type WebSearchStreamEvent struct {
	// WebSearchCall fields (present when Type == "web_search_call")
	Type   string           `json:"type,omitempty"`
	ID     string           `json:"id,omitempty"`
	Status string           `json:"status,omitempty"`
	Reason string           `json:"reason,omitempty"`
	Action *WebSearchAction `json:"action,omitempty"`

	// Chat completion chunk fields (present when Type is empty or not "web_search_call")
	Choices []WebSearchChoice `json:"choices,omitempty"`
}

WebSearchStreamEvent represents either a WebSearchCall or a chat completion chunk. Use IsWebSearchCall() to determine the event type.

func (*WebSearchStreamEvent) IsWebSearchCall added in v0.11.2

func (e *WebSearchStreamEvent) IsWebSearchCall() bool

IsWebSearchCall returns true if this event is a web search call event.

func (*WebSearchStreamEvent) ToWebSearchCall added in v0.11.2

func (e *WebSearchStreamEvent) ToWebSearchCall() *WebSearchCall

ToWebSearchCall converts this event to a WebSearchCall. Returns nil if this is not a web search call event.

Directories

Path Synopsis
examples
chat command
verifier module

Jump to

Keyboard shortcuts

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