nodecode

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2026 License: MIT Imports: 13 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

nodecode-go

Go Reference

Zero-dependency Go client for the Nodecode API, built for Cyber v1 (nodecode-cyber-v1), Decide v1 (nodecode-decide-v1), and Image v1 (nodecode-image-v1).

Operated by Foresight Labs (EU entity) with zero data retention.

Install

go get github.com/nodecode-ai/nodecode-go

Requires Go 1.22+. Uses the Go standard library only.

Quickstart

Create an API key (sk-nc-...) at nodecode.ai/account/keys and set NODECODE_API_KEY:

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/nodecode-ai/nodecode-go"
)

func main() {
	client := nodecode.NewClient() // reads NODECODE_API_KEY

	resp, err := client.ChatCompletion(context.Background(), nodecode.ChatCompletionRequest{
		Model: nodecode.ModelCyberV1,
		Messages: []nodecode.Message{
			{Role: nodecode.RoleUser, Content: "22/tcp and 8080/tcp are open. What next, in order?"},
		},
		MaxTokens: 600,
	})
	if err != nil {
		log.Fatal(err)
	}

	msg := resp.Choices[0].Message
	fmt.Println("Reasoning:", msg.ReasoningText())
	fmt.Println("Answer:", msg.Content)
}

Streaming (SSE)

stream, err := client.ChatCompletionStream(ctx, nodecode.ChatCompletionRequest{
	Model: nodecode.ModelCyberV1,
	Messages: []nodecode.Message{
		{Role: nodecode.RoleUser, Content: "Audit this Dockerfile for privilege escalation."},
	},
	MaxTokens: 1024,
})
if err != nil {
	log.Fatal(err)
}
defer stream.Close()

for stream.Next() {
	chunk := stream.Chunk()
	if len(chunk.Choices) > 0 {
		fmt.Print(chunk.Choices[0].Delta.Content)
	}
}
if err := stream.Err(); err != nil {
	log.Fatal(err)
}

Reasoning token budget

Cyber v1 thinks first, and max_tokens covers both thinking and final output. Passing a very small max_tokens (such as 100) can exhaust the budget during reasoning and return empty Content with finish_reason: "length". Give calls at least a few hundred tokens.

Models, usage, and images

  • client.ListModels(ctx) / client.GetModel(ctx, nodecode.ModelCyberV1) - live model list and pricing (works without an API key, costs nothing).
  • client.Usage(ctx) - remaining balance, plan allowance, and running concurrency slots (GET /v1/usage, costs nothing).
  • client.GenerateImage(ctx, req) - Image v1 (nodecode-image-v1) via POST /v1/images/generations with DecodeBytes() for b64_json.
  • nodecode.IsInsufficientBalance(err) / nodecode.IsRateLimited(err) / nodecode.IsUnauthorized(err) - typed *nodecode.APIError helpers including Refill metadata on HTTP 402.

Documentation

License

MIT. Copyright (c) 2026 Foresight Labs.

Documentation

Overview

Package nodecode provides a zero-dependency Go client for the Nodecode API, including Cyber v1 (nodecode-cyber-v1), Decide v1 (nodecode-decide-v1), and Image v1 (nodecode-image-v1).

Nodecode's hosted inference API is operated by Foresight Labs (an EU entity) with zero data retention and exposes OpenAI-compatible chat completions, streaming server-sent events, model catalog pricing, account usage meters, and image generation from https://api.nodecode.ai/v1.

Quickstart

Create an API key (sk-nc-...) at API keys and export it as NODECODE_API_KEY (or pass WithAPIKey):

client := nodecode.NewClient()
resp, err := client.ChatCompletion(ctx, nodecode.ChatCompletionRequest{
	Model: nodecode.ModelCyberV1,
	Messages: []nodecode.Message{
		{Role: nodecode.RoleUser, Content: "22/tcp and 8080/tcp are open. What next, in order?"},
	},
	MaxTokens: 600,
})

Reasoning models

Cyber v1 thinks before writing its answer, and max_tokens covers both reasoning and final output. Give calls at least a few hundred tokens so the model finishes reasoning and emits content. Access the thinking trace via Message.ReasoningText or ChunkDelta.ReasoningText.

Index

Examples

Constants

View Source
const (
	RoleSystem    = "system"
	RoleUser      = "user"
	RoleAssistant = "assistant"
	RoleTool      = "tool"
)

Standard chat message roles.

View Source
const (
	// DefaultBaseURL is the production base URL for the Nodecode inference API.
	// See https://nodecode.ai/docs/cyber for endpoint details and wire formats.
	DefaultBaseURL = "https://api.nodecode.ai/v1"

	// DefaultEnvAPIKey is the environment variable read by NewClient when no
	// explicit key is passed via WithAPIKey.
	DefaultEnvAPIKey = "NODECODE_API_KEY"

	// ModelCyberV1 is Nodecode's abliterated security reasoning model with a
	// 1,048,576-token context window. See https://nodecode.ai/cyber.
	ModelCyberV1 = "nodecode-cyber-v1"

	// ModelDecideV1 is Nodecode's classifier model for structured probability
	// questions over a state (32K context). See https://nodecode.ai/docs/models.
	ModelDecideV1 = "nodecode-decide-v1"

	// ModelImageV1 is Nodecode's image generation model served at
	// POST /v1/images/generations. See https://nodecode.ai/docs/models.
	ModelImageV1 = "nodecode-image-v1"
)

Variables

This section is empty.

Functions

func IsInsufficientBalance

func IsInsufficientBalance(err error) bool

IsInsufficientBalance reports whether err is a 402 insufficient_balance or topup_required response from the Nodecode API.

func IsRateLimited

func IsRateLimited(err error) bool

IsRateLimited reports whether err is an HTTP 429 response (concurrency or allowance limit).

func IsUnauthorized

func IsUnauthorized(err error) bool

IsUnauthorized reports whether err is an HTTP 401 authentication failure.

Types

type APIError

type APIError struct {
	StatusCode int
	Type       string
	Code       string
	Message    string
	Param      string
	RequestID  string
	Refill     *RefillInfo
	RawBody    string
}

APIError is returned whenever the Nodecode API responds with an HTTP 4xx or 5xx status. Use errors.As to inspect StatusCode, Code, RequestID, or Refill. See https://nodecode.ai/docs/pricing for 402 and 429 behavior.

func (*APIError) Error

func (e *APIError) Error() string

type AccountUsage

type AccountUsage struct {
	Object  string      `json:"object"`
	Plan    *PlanUsage  `json:"plan"`
	Balance []Balance   `json:"balance"`
	Pays    string      `json:"pays"`
	House   *HouseUsage `json:"house,omitempty"`
}

AccountUsage is the response from GET /v1/usage, reporting what the account behind an API key has left in plan requests, prepaid balance, and running concurrency slots. Calling /v1/usage costs nothing. See https://nodecode.ai/docs/pricing and https://nodecode.ai/docs/models.

type Balance

type Balance struct {
	Currency string `json:"currency"`
	Micros   int64  `json:"micros"`
}

Balance represents a prepaid credit balance in one currency, stored in micro-units (1,000,000 micros = 1.00 unit of Currency).

func (Balance) Amount

func (b Balance) Amount() float64

Amount returns the balance in major currency units (e.g. dollars or euros).

type ChatCompletionChunk

type ChatCompletionChunk struct {
	ID                string        `json:"id"`
	Object            string        `json:"object"`
	Created           int64         `json:"created"`
	Model             string        `json:"model"`
	SystemFingerprint string        `json:"system_fingerprint,omitempty"`
	Choices           []ChunkChoice `json:"choices"`
	Usage             *TokenUsage   `json:"usage,omitempty"`
}

ChatCompletionChunk is one server-sent event payload from a streaming completion.

type ChatCompletionRequest

type ChatCompletionRequest struct {
	Model               string          `json:"model"`
	Messages            []Message       `json:"messages"`
	MaxTokens           int             `json:"max_tokens,omitempty"`
	MaxCompletionTokens int             `json:"max_completion_tokens,omitempty"`
	Temperature         *float64        `json:"temperature,omitempty"`
	TopP                *float64        `json:"top_p,omitempty"`
	Stop                []string        `json:"stop,omitempty"`
	Tools               []Tool          `json:"tools,omitempty"`
	ToolChoice          any             `json:"tool_choice,omitempty"`
	ParallelToolCalls   *bool           `json:"parallel_tool_calls,omitempty"`
	ResponseFormat      *ResponseFormat `json:"response_format,omitempty"`
	ReasoningEffort     string          `json:"reasoning_effort,omitempty"`
	Seed                *int            `json:"seed,omitempty"`
	User                string          `json:"user,omitempty"`
	Stream              bool            `json:"stream,omitempty"`
	StreamOptions       *StreamOptions  `json:"stream_options,omitempty"`
}

ChatCompletionRequest is the request payload for POST /v1/chat/completions.

If Model is empty, Client.ChatCompletion and Client.ChatCompletionStream default to ModelCyberV1. Because Cyber v1 thinks before answering and MaxTokens includes reasoning tokens, leave enough headroom (at least a few hundred tokens) to avoid empty content with finish_reason "length". See https://nodecode.ai/docs/cyber for wire details.

type ChatCompletionResponse

type ChatCompletionResponse struct {
	ID                string      `json:"id"`
	Object            string      `json:"object"`
	Created           int64       `json:"created"`
	Model             string      `json:"model"`
	SystemFingerprint string      `json:"system_fingerprint,omitempty"`
	Choices           []Choice    `json:"choices"`
	Usage             *TokenUsage `json:"usage,omitempty"`
}

ChatCompletionResponse is the non-streaming response from POST /v1/chat/completions.

type ChatStream

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

ChatStream reads server-sent events from a streaming chat completion. Callers must always call Close when finished to release the HTTP connection.

func (*ChatStream) Chunk

func (s *ChatStream) Chunk() ChatCompletionChunk

Chunk returns the most recent ChatCompletionChunk read by ChatStream.Next.

func (*ChatStream) Close

func (s *ChatStream) Close() error

Close closes the underlying HTTP response body.

func (*ChatStream) Err

func (s *ChatStream) Err() error

Err returns the first non-EOF error encountered while reading the stream.

func (*ChatStream) Next

func (s *ChatStream) Next() bool

Next advances the stream to the next ChatCompletionChunk. It returns false when the stream finishes cleanly ([DONE] or EOF) or encounters an error. Inspect ChatStream.Err after Next returns false.

type Choice

type Choice struct {
	Index        int     `json:"index"`
	Message      Message `json:"message"`
	FinishReason string  `json:"finish_reason"`
}

Choice is one candidate completion returned by the model.

type ChunkChoice

type ChunkChoice struct {
	Index        int        `json:"index"`
	Delta        ChunkDelta `json:"delta"`
	FinishReason string     `json:"finish_reason,omitempty"`
}

ChunkChoice is one incremental choice delta inside a ChatCompletionChunk.

type ChunkDelta

type ChunkDelta struct {
	Role             string     `json:"role,omitempty"`
	Content          string     `json:"content,omitempty"`
	Reasoning        string     `json:"reasoning,omitempty"`
	ReasoningContent string     `json:"reasoning_content,omitempty"`
	ToolCalls        []ToolCall `json:"tool_calls,omitempty"`
}

ChunkDelta holds incremental content, reasoning, or tool-call fragments.

func (ChunkDelta) ReasoningText

func (d ChunkDelta) ReasoningText() string

ReasoningText returns the incremental reasoning fragment, checking Reasoning first and falling back to ReasoningContent.

type Client

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

Client calls the Nodecode inference API (https://api.nodecode.ai/v1). A Client is safe for concurrent use by multiple goroutines once constructed. Create API keys at https://nodecode.ai/account/keys.

func NewClient

func NewClient(opts ...Option) *Client

NewClient returns a new Client configured for DefaultBaseURL. Without WithAPIKey, it reads NODECODE_API_KEY from the environment. Public endpoints such as Client.ListModels and Client.GetModel work even without a key.

func (*Client) ChatCompletion

func (c *Client) ChatCompletion(ctx context.Context, req ChatCompletionRequest) (*ChatCompletionResponse, error)

ChatCompletion sends a non-streaming POST /v1/chat/completions request.

If req.Model is empty, it defaults to ModelCyberV1. Stream is forced false; use Client.ChatCompletionStream for server-sent events.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/nodecode-ai/nodecode-go"
)

func main() {
	client := nodecode.NewClient() // reads NODECODE_API_KEY

	resp, err := client.ChatCompletion(context.Background(), nodecode.ChatCompletionRequest{
		Model: nodecode.ModelCyberV1,
		Messages: []nodecode.Message{
			{Role: nodecode.RoleUser, Content: "22/tcp and 8080/tcp are open. What next, in order?"},
		},
		MaxTokens: 600,
	})
	if err != nil {
		log.Fatal(err)
	}

	msg := resp.Choices[0].Message
	fmt.Println(msg.Content)
}

func (*Client) ChatCompletionStream

func (c *Client) ChatCompletionStream(ctx context.Context, req ChatCompletionRequest) (*ChatStream, error)

ChatCompletionStream opens a streaming POST /v1/chat/completions request and returns a ChatStream over the incoming server-sent event chunks.

If req.Model is empty, it defaults to ModelCyberV1. If req.StreamOptions is nil, IncludeUsage is enabled so the final chunk carries token usage.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/nodecode-ai/nodecode-go"
)

func main() {
	client := nodecode.NewClient()

	stream, err := client.ChatCompletionStream(context.Background(), nodecode.ChatCompletionRequest{
		Model: nodecode.ModelCyberV1,
		Messages: []nodecode.Message{
			{Role: nodecode.RoleUser, Content: "Review this nginx config for header smuggling."},
		},
		MaxTokens: 800,
	})
	if err != nil {
		log.Fatal(err)
	}
	defer stream.Close()

	for stream.Next() {
		chunk := stream.Chunk()
		if len(chunk.Choices) > 0 {
			fmt.Print(chunk.Choices[0].Delta.Content)
		}
	}
	if err := stream.Err(); err != nil {
		log.Fatal(err)
	}
}

func (*Client) GenerateImage

GenerateImage sends POST /v1/images/generations using ModelImageV1 by default.

func (*Client) GetModel

func (c *Client) GetModel(ctx context.Context, modelID string) (*Model, error)

GetModel fetches GET /v1/models/{id} for a single model (for example, ModelCyberV1). Works with or without an API key and costs nothing.

func (*Client) ListModels

func (c *Client) ListModels(ctx context.Context) (*ModelList, error)

ListModels fetches GET /v1/models with live pricing. Works with or without an API key and costs nothing.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/nodecode-ai/nodecode-go"
)

func main() {
	// ListModels works without an API key and costs nothing.
	client := nodecode.NewClient()
	models, err := client.ListModels(context.Background())
	if err != nil {
		log.Fatal(err)
	}
	for _, m := range models.Data {
		fmt.Println(m.ID, m.Name)
	}
}

func (*Client) Usage

func (c *Client) Usage(ctx context.Context) (*AccountUsage, error)

Usage fetches GET /v1/usage for the configured API key. Costs nothing.

type CompletionTokensDetails

type CompletionTokensDetails struct {
	ReasoningTokens int `json:"reasoning_tokens"`
}

CompletionTokensDetails breaks down completion tokens, including reasoning tokens.

type GeneratedImage

type GeneratedImage struct {
	B64JSON       string `json:"b64_json,omitempty"`
	URL           string `json:"url,omitempty"`
	RevisedPrompt string `json:"revised_prompt,omitempty"`
}

GeneratedImage is one image item returned by Client.GenerateImage.

func (GeneratedImage) DecodeBytes

func (g GeneratedImage) DecodeBytes() ([]byte, error)

DecodeBytes base64-decodes B64JSON into raw image bytes.

type HouseUsage

type HouseUsage struct {
	Threads uint32 `json:"threads"`
	Running uint32 `json:"running"`
}

HouseUsage reports concurrency limits on internal/house keys.

type ImageGenerationRequest

type ImageGenerationRequest struct {
	Model          string `json:"model"`
	Prompt         string `json:"prompt"`
	Size           string `json:"size,omitempty"`
	N              int    `json:"n,omitempty"`
	ResponseFormat string `json:"response_format,omitempty"`
	Seed           *int   `json:"seed,omitempty"`
}

ImageGenerationRequest is the request payload for POST /v1/images/generations. If Model is empty, Client.GenerateImage defaults to ModelImageV1. ResponseFormat defaults to "b64_json", which is how Image v1 returns images. See https://nodecode.ai/docs/models for Image v1 details.

type ImageGenerationResponse

type ImageGenerationResponse struct {
	Created int64            `json:"created"`
	Data    []GeneratedImage `json:"data"`
}

ImageGenerationResponse is the response from POST /v1/images/generations.

type LongContextPricing

type LongContextPricing struct {
	OverTokens       int     `json:"over_tokens"`
	CachedInputTimes float64 `json:"cached_input_times"`
}

LongContextPricing describes the cached-input multiplier above OverTokens.

type Message

type Message struct {
	Role             string     `json:"role"`
	Content          string     `json:"content,omitempty"`
	Reasoning        string     `json:"reasoning,omitempty"`
	ReasoningContent string     `json:"reasoning_content,omitempty"`
	Name             string     `json:"name,omitempty"`
	ToolCallID       string     `json:"tool_call_id,omitempty"`
	ToolCalls        []ToolCall `json:"tool_calls,omitempty"`
}

Message is a single turn in a chat completion conversation.

Cyber v1 is a reasoning model: assistant replies carry thinking in Reasoning (or ReasoningContent on compatible gateways) and the final answer in Content. See the Cyber v1 API quickstart for reasoning token budgeting guidance.

func (Message) ReasoningText

func (m Message) ReasoningText() string

ReasoningText returns the message's reasoning trace, checking Reasoning first and falling back to ReasoningContent.

type Model

type Model struct {
	ID              string        `json:"id"`
	Object          string        `json:"object"`
	Created         int64         `json:"created"`
	OwnedBy         string        `json:"owned_by"`
	Name            string        `json:"name,omitempty"`
	Kind            string        `json:"kind,omitempty"`
	ContextLength   *int          `json:"context_length,omitempty"`
	MaxOutputTokens *int          `json:"max_output_tokens,omitempty"`
	Pricing         *ModelPricing `json:"pricing,omitempty"`
}

Model describes one hosted model on the Nodecode API.

type ModelList

type ModelList struct {
	Object     string           `json:"object"`
	Data       []Model          `json:"data"`
	Onboarding *OnboardingLinks `json:"onboarding,omitempty"`
}

ModelList is the response from GET /v1/models. Public requests (without an API key) list all public models along with live pricing and agent onboarding links. See https://nodecode.ai/docs/pricing.

type ModelPricing

type ModelPricing struct {
	InputPerMillion       *float64            `json:"input_per_million,omitempty"`
	CachedInputPerMillion *float64            `json:"cached_input_per_million,omitempty"`
	OutputPerMillion      *float64            `json:"output_per_million,omitempty"`
	PerImage              *float64            `json:"per_image,omitempty"`
	Currency              string              `json:"currency,omitempty"`
	LongContext           *LongContextPricing `json:"long_context,omitempty"`
}

ModelPricing reports live per-million-token or per-image pricing. See https://nodecode.ai/docs/pricing for weekday and weekend schedules.

type OnboardingLinks struct {
	CoinsURL     string `json:"coins_url,omitempty"`
	ChallengeURL string `json:"challenge_url,omitempty"`
	OrdersURL    string `json:"orders_url,omitempty"`
	OpenAPIURL   string `json:"openapi_url,omitempty"`
	SkillURL     string `json:"skill_url,omitempty"`
	X402KeyURL   string `json:"x402_key_url,omitempty"`
}

OnboardingLinks lists discovery and self-serve onboarding URLs published on unauthenticated GET /v1/models responses.

type Option

type Option func(*Client)

Option configures a Client created by NewClient.

func WithAPIKey

func WithAPIKey(key string) Option

WithAPIKey sets the bearer API key (sk-nc-...) sent in the Authorization header. If omitted, NewClient falls back to the NODECODE_API_KEY environment variable.

func WithBaseURL

func WithBaseURL(rawURL string) Option

WithBaseURL overrides DefaultBaseURL (for proxies, local gateways, or tests). Trailing slashes are stripped automatically.

func WithHTTPClient

func WithHTTPClient(hc *http.Client) Option

WithHTTPClient supplies a custom *http.Client for transport, proxy, or timeout control.

func WithUserAgent

func WithUserAgent(ua string) Option

WithUserAgent overrides the default User-Agent header sent on requests.

type PlanUsage

type PlanUsage struct {
	Name     string  `json:"name"`
	Label    string  `json:"label"`
	Requests int64   `json:"requests"`
	Carried  int64   `json:"carried"`
	Used     float64 `json:"used"`
	Left     float64 `json:"left"`
	ResetsAt string  `json:"resets_at"`
	EndsAt   *string `json:"ends_at"`
	Threads  uint32  `json:"threads"`
	Running  uint32  `json:"running"`
}

PlanUsage reports active plan request allowance and concurrency utilization.

type PromptTokensDetails

type PromptTokensDetails struct {
	CachedTokens int `json:"cached_tokens"`
}

PromptTokensDetails breaks down prompt tokens, including prefix cache hits.

type RefillInfo

type RefillInfo struct {
	URL          string  `json:"url"`
	Method       string  `json:"method"`
	Auth         string  `json:"auth"`
	BalanceURL   string  `json:"balance_url,omitempty"`
	CoinsURL     string  `json:"coins_url,omitempty"`
	OpenAPIURL   string  `json:"openapi_url,omitempty"`
	X402TopupURL string  `json:"x402_topup_url,omitempty"`
	MinUSD       float64 `json:"min_usd,omitempty"`
}

RefillInfo describes programmatic refill endpoints returned alongside a 402 insufficient_balance error. Manual top-ups are also available at https://nodecode.ai/account/top-up.

type ResponseFormat

type ResponseFormat struct {
	Type       string `json:"type"`
	JSONSchema any    `json:"json_schema,omitempty"`
}

ResponseFormat controls structured output formatting on chat completions.

type StreamOptions

type StreamOptions struct {
	IncludeUsage bool `json:"include_usage,omitempty"`
}

StreamOptions configures additional metadata returned during SSE streaming.

type TokenUsage

type TokenUsage struct {
	PromptTokens            int                      `json:"prompt_tokens"`
	CompletionTokens        int                      `json:"completion_tokens"`
	TotalTokens             int                      `json:"total_tokens"`
	PromptTokensDetails     *PromptTokensDetails     `json:"prompt_tokens_details,omitempty"`
	CompletionTokensDetails *CompletionTokensDetails `json:"completion_tokens_details,omitempty"`
}

TokenUsage reports prompt, cached, reasoning, and completion token counts. See Nodecode pricing for cached input and long-context rates.

type Tool

type Tool struct {
	Type     string       `json:"type"`
	Function ToolFunction `json:"function"`
}

Tool describes a callable function offered to the model.

type ToolCall

type ToolCall struct {
	Index    *int             `json:"index,omitempty"`
	ID       string           `json:"id,omitempty"`
	Type     string           `json:"type,omitempty"`
	Function ToolCallFunction `json:"function"`
}

ToolCall represents a tool invocation requested by the assistant.

type ToolCallFunction

type ToolCallFunction struct {
	Name      string `json:"name,omitempty"`
	Arguments string `json:"arguments,omitempty"`
}

ToolCallFunction carries the function name and JSON-encoded arguments.

type ToolFunction

type ToolFunction struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Parameters  any    `json:"parameters,omitempty"`
	Strict      *bool  `json:"strict,omitempty"`
}

ToolFunction defines a function tool's name, description, and JSON Schema parameters.

Jump to

Keyboard shortcuts

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