pithsdk

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 5, 2026 License: MIT Imports: 15 Imported by: 0

README

pith-sdk

A minimal, OpenAI Agents-style SDK for Go app developers — built on pith.

Define an agent, run it, get text back. No gateway wiring, no ModelDescriptor, no EventBus parsing.

Who this is for

App developers who want ClientAgentSession.Run in ~15 lines, with optional custom providers (Anthropic, Groq, Ollama, etc.).

Who this is not for

Library authors and provider implementers who need direct control over the gateway, loop, or protocol layers. Use pith directly.

Quick start

package main

import (
    "context"
    "fmt"
    "os"

    pithsdk "github.com/chinudotdev/pith-sdk"
)

func main() {
    client, _ := pithsdk.NewClient(pithsdk.ClientConfig{
        APIKey: os.Getenv("OPENAI_API_KEY"),
    })

    agent, _ := pithsdk.NewAgent(pithsdk.AgentConfig{
        Name:         "Assistant",
        Instructions: "You are helpful. Be concise.",
        Model:        "gpt-4o-mini",
    })

    session, _ := client.NewSession(agent)
    result, _ := session.Run(context.Background(), "What is Go?")
    fmt.Println(result.Text)
}
With tools
weather := pithsdk.NewTool("get_weather", "Return weather for a city.",
    func(ctx pithsdk.ToolContext, args struct {
        City string `json:"city"`
    }) (string, error) {
        return fmt.Sprintf("Sunny in %s", args.City), nil
    },
)

agent, _ := pithsdk.NewAgent(pithsdk.AgentConfig{
    Name:         "Weather bot",
    Instructions: "You are a helpful weather bot.",
    Model:        "gpt-4o-mini",
    Tools:        []pithsdk.Tool{weather},
})

Pass run-scoped dependencies to tools with WithContext:

session.Run(ctx, "What's the weather?", pithsdk.WithContext(myDeps))
Multi-turn sessions

Reuse a Session to keep conversation history across runs:

session, _ := client.NewSession(agent)
session.Run(ctx, "My name is Alex.")
result, _ := session.Run(ctx, "What is my name?")
fmt.Println(result.Text)
fmt.Println(len(session.Messages())) // full transcript
session.Reset()                      // start fresh

Stream assistant text as it arrives:

session.Run(ctx, "Tell me a joke.", pithsdk.WithStream(func(c pithsdk.TextChunk) {
    fmt.Print(c.Delta)
}))

For one-shot scripts without managing a session:

result, _ := client.RunOnce(ctx, agent, "What is Go?")
Custom providers

Register any gateway.ProviderPort (e.g. Anthropic) once on the client:

client, _ := pithsdk.NewClient(pithsdk.ClientConfig{})

client.RegisterProvider(pithsdk.ProviderRegistration{
    Provider:  myAnthropicProvider,
    APIKeyEnv: "ANTHROPIC_API_KEY",
    Models: []pithsdk.ModelPreset{
        {ID: "claude-sonnet-4-20250514", ContextWindow: 200_000, MaxTokens: 8192},
    },
})

agent, _ := pithsdk.NewAgent(pithsdk.AgentConfig{
    Model: "anthropic/claude-sonnet-4-20250514",
    // ... same Agent API as OpenAI
})

Use provider/model strings when not using the default OpenAI provider. See examples/04-anthropic-provider for a full custom provider implementation.

Limit tool-calling loop iterations per run (default 10):

session.Run(ctx, input, pithsdk.WithMaxTurns(5))

API overview

Type Role
Client Gateway, credentials, defaults; creates sessions
Agent Specialist definition: instructions, model, tools
Session Runs the agent; holds multi-turn transcript
RunOnce One-shot run without managing a session
NewTool Typed tool with struct-based JSON Schema
RegisterProvider Custom ProviderPort + model catalog

Installation

go get github.com/chinudotdev/pith-sdk@v0.1.0

Requires Go 1.24+.

Examples

Example Description
01-hello Minimal agent run
02-tools Agent with custom tools
03-multi-turn Multi-turn conversation with streaming
04-anthropic-provider Custom Anthropic provider via RegisterProvider

Run from the repo root:

OPENAI_API_KEY="sk-..." go run ./examples/01-hello/main.go
OPENAI_API_KEY="sk-..." go run ./examples/02-tools/main.go
OPENAI_API_KEY="sk-..." go run ./examples/03-multi-turn/main.go
ANTHROPIC_API_KEY="sk-ant-..." go run ./examples/04-anthropic-provider/

Releases

v0.1.0 is the first public release. See CHANGELOG.md for details.

Future work is tracked in plan.md.

License

MIT — see LICENSE.

Documentation

Overview

Package pithsdk is a minimal, OpenAI Agents-style SDK for Go app developers. It wraps github.com/chinudotdev/pith primitives so you can define an agent, run it, and get text back without wiring gateways, ModelDescriptors, or EventBus.

Quick start:

client, _ := pithsdk.NewClient(pithsdk.ClientConfig{APIKey: os.Getenv("OPENAI_API_KEY")})
agent, _ := pithsdk.NewAgent(pithsdk.AgentConfig{
    Instructions: "You are helpful.",
    Model:        "gpt-4o-mini",
})
session, _ := client.NewSession(agent)
result, _ := session.Run(ctx, "Hello!")

Import with the recommended alias:

import pithsdk "github.com/chinudotdev/pith-sdk"

See the examples/ directory and https://github.com/chinudotdev/pith-sdk for more.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Agent

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

Agent is a specialist definition: name, instructions, model, tools, and settings. Agents are immutable configuration; create a Session to run them.

func NewAgent

func NewAgent(cfg AgentConfig) (*Agent, error)

NewAgent creates an agent definition.

type AgentConfig

type AgentConfig struct {
	// Name is an optional display name for the agent.
	Name string
	// Instructions is the system prompt sent to the model.
	Instructions string
	// Model is a bare ID (e.g. "gpt-4o-mini") or provider/model (e.g. "anthropic/claude-...").
	Model string
	// Tools are custom tools available during runs.
	Tools []Tool
	// Settings overrides client-level generation defaults for this agent.
	Settings *ModelSettings
}

AgentConfig configures a new Agent.

type Client

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

Client holds gateway configuration, credentials, and defaults for running agents.

func NewClient

func NewClient(cfg ClientConfig) (*Client, error)

NewClient creates a client with a built-in OpenAI-compatible provider. An OpenAI API key is optional at construction time; it is required when using the default OpenAI provider at run time.

func NewClientFromGateway

func NewClientFromGateway(gw *gateway.LLMGateway) *Client

NewClientFromGateway wraps a pre-wired gateway (e.g. for testing or custom setups).

func (*Client) NewSession

func (c *Client) NewSession(agent *Agent) (*Session, error)

NewSession creates a session for the given agent definition.

func (*Client) RegisterProvider

func (c *Client) RegisterProvider(reg ProviderRegistration) error

RegisterProvider registers a custom provider, its models, and credentials.

func (*Client) RunOnce

func (c *Client) RunOnce(ctx context.Context, agent *Agent, input string, opts ...RunOption) (*RunResult, error)

RunOnce runs a single prompt without requiring the caller to manage a Session.

type ClientConfig

type ClientConfig struct {
	// APIKey is the OpenAI-compatible API key. When empty, OPENAI_API_KEY is used at run time.
	APIKey string
	// DefaultProvider is the provider ID for bare model strings (default "openai").
	DefaultProvider string
	// DefaultModel is used when an Agent has no Model set (default "gpt-4o-mini").
	DefaultModel string
	// DefaultSettings applies generation defaults to all agents unless overridden.
	DefaultSettings *ModelSettings
}

ClientConfig configures a new Client.

type MessageSummary

type MessageSummary struct {
	// Role is the message role (e.g. "user", "assistant", "toolResult").
	Role string
	// Text is the message text content.
	Text string
}

MessageSummary is a simplified view of a transcript message.

type ModelPreset

type ModelPreset struct {
	// ID is the model identifier used in provider/model strings.
	ID string
	// Name is an optional display name; defaults to ID.
	Name string
	// BaseURL is an optional API base URL; the provider may use its own default.
	BaseURL string
	// ContextWindow is the model context size; zero uses the SDK default.
	ContextWindow int
	// MaxTokens is the default max output tokens; zero uses the SDK default.
	MaxTokens int
}

ModelPreset describes a model to register in the gateway catalog.

type ModelSettings

type ModelSettings struct {
	// Temperature controls randomness. Nil leaves the provider default.
	Temperature *float64
	// MaxTokens caps output tokens. Nil leaves the provider default.
	MaxTokens *int
}

ModelSettings configures generation parameters for an agent run.

type ProviderRegistration

type ProviderRegistration struct {
	// Provider implements gateway.ProviderPort for the custom API.
	Provider gateway.ProviderPort

	// Credentials — set exactly one of the following:
	// APIKey is a static API key string.
	APIKey string
	// APIKeyEnv names an environment variable holding the API key (e.g. "ANTHROPIC_API_KEY").
	APIKeyEnv string
	// Credential is a custom resolver returning the API key for the provider ID.
	Credential func(providerID string) (string, error)

	// Models lists model presets to register in the gateway catalog.
	Models []ModelPreset
}

ProviderRegistration registers a custom LLM provider and its models on the client.

type RunOption

type RunOption func(*RunOptions)

RunOption configures a Session.Run call.

func WithContext

func WithContext(local any) RunOption

WithContext sets run-scoped local dependencies available as ToolContext.Local.

func WithInstructions

func WithInstructions(instructions string) RunOption

WithInstructions overrides the agent's system prompt for this run only.

func WithMaxTurns

func WithMaxTurns(n int) RunOption

WithMaxTurns limits how many agent loop turns a single Run may take. Zero uses the SDK default of 10.

func WithStream

func WithStream(fn func(TextChunk)) RunOption

WithStream registers a callback for streaming assistant text deltas during the run. When nil (default), Run blocks until the full response is ready.

type RunOptions

type RunOptions struct {
	// Context holds run-scoped local dependencies exposed as ToolContext.Local.
	Context any
	// Instructions overrides the agent system prompt for this run only.
	Instructions string
	// Stream receives assistant text deltas during the run; nil blocks until complete.
	Stream func(chunk TextChunk)
	// MaxTurns limits tool-calling loop iterations for this run. Zero uses defaultMaxTurns (10).
	MaxTurns int
}

RunOptions configures a single run. Apply via RunOption functions.

type RunResult

type RunResult struct {
	// Text is the final assistant response text.
	Text string
	// Messages is the session transcript after this run, as simplified summaries.
	Messages []MessageSummary
	// Usage reports token usage from the last assistant response, if available.
	Usage *UsageSummary
}

RunResult is the outcome of a single Session.Run call.

type Session

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

Session runs an agent and holds its transcript across multiple Run calls.

func (*Session) Messages

func (s *Session) Messages() []MessageSummary

Messages returns the current session transcript.

func (*Session) Reset

func (s *Session) Reset()

Reset clears the session transcript and queued messages.

func (*Session) Run

func (s *Session) Run(ctx context.Context, input string, opts ...RunOption) (*RunResult, error)

Run sends input to the agent and returns the final text result.

type TextChunk

type TextChunk struct {
	// Delta is the incremental text from the latest EventTextDelta.
	Delta string
	// Text is the accumulated assistant text so far.
	Text string
}

TextChunk is a streaming text delta from the assistant response.

type Tool

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

Tool is an opaque tool definition. Create with NewTool or RawTool.

func NewTool

func NewTool[T any](name, description string, fn func(ToolContext, T) (string, error)) Tool

NewTool creates a typed tool from a struct argument type T and handler function. T must be a struct; JSON Schema is generated from json and optional desc struct tags.

func RawTool

func RawTool(t loop.AgentTool) Tool

RawTool wraps a pre-built loop.AgentTool without ToolContext injection.

type ToolContext

type ToolContext struct {
	// Run is the context for the current Session.Run call.
	Run context.Context
	// Local holds run-scoped dependencies from WithContext; not sent to the model.
	Local any
	// CallID is the provider-assigned tool call identifier.
	CallID string
}

ToolContext is passed to tool handlers during execution.

type UsageSummary

type UsageSummary struct {
	// Input is the number of input/prompt tokens.
	Input int
	// Output is the number of output/completion tokens.
	Output int
	// Total is the combined token count when reported by the provider.
	Total int
}

UsageSummary reports token usage from the last assistant response.

Directories

Path Synopsis
examples
01-hello command
Example 01: Hello — minimal agent run with the pith-sdk.
Example 01: Hello — minimal agent run with the pith-sdk.
02-tools command
Example 02: Tools — agent with a custom tool the model can call.
Example 02: Tools — agent with a custom tool the model can call.
03-multi-turn command
Example 03: Multi-turn — conversation across multiple Session.Run calls.
Example 03: Multi-turn — conversation across multiple Session.Run calls.
04-anthropic-provider command
Example 04: Custom Anthropic provider via pith-sdk RegisterProvider.
Example 04: Custom Anthropic provider via pith-sdk RegisterProvider.
internal

Jump to

Keyboard shortcuts

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