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 ¶
- Constants
- func IsInsufficientBalance(err error) bool
- func IsRateLimited(err error) bool
- func IsUnauthorized(err error) bool
- type APIError
- type AccountUsage
- type Balance
- type ChatCompletionChunk
- type ChatCompletionRequest
- type ChatCompletionResponse
- type ChatStream
- type Choice
- type ChunkChoice
- type ChunkDelta
- type Client
- func (c *Client) ChatCompletion(ctx context.Context, req ChatCompletionRequest) (*ChatCompletionResponse, error)
- func (c *Client) ChatCompletionStream(ctx context.Context, req ChatCompletionRequest) (*ChatStream, error)
- func (c *Client) GenerateImage(ctx context.Context, req ImageGenerationRequest) (*ImageGenerationResponse, error)
- func (c *Client) GetModel(ctx context.Context, modelID string) (*Model, error)
- func (c *Client) ListModels(ctx context.Context) (*ModelList, error)
- func (c *Client) Usage(ctx context.Context) (*AccountUsage, error)
- type CompletionTokensDetails
- type GeneratedImage
- type HouseUsage
- type ImageGenerationRequest
- type ImageGenerationResponse
- type LongContextPricing
- type Message
- type Model
- type ModelList
- type ModelPricing
- type OnboardingLinks
- type Option
- type PlanUsage
- type PromptTokensDetails
- type RefillInfo
- type ResponseFormat
- type StreamOptions
- type TokenUsage
- type Tool
- type ToolCall
- type ToolCallFunction
- type ToolFunction
Examples ¶
Constants ¶
const ( RoleSystem = "system" RoleUser = "user" RoleAssistant = "assistant" RoleTool = "tool" )
Standard chat message roles.
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 ¶
IsInsufficientBalance reports whether err is a 402 insufficient_balance or topup_required response from the Nodecode API.
func IsRateLimited ¶
IsRateLimited reports whether err is an HTTP 429 response (concurrency or allowance limit).
func IsUnauthorized ¶
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.
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 ¶
Balance represents a prepaid credit balance in one currency, stored in micro-units (1,000,000 micros = 1.00 unit of Currency).
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 ¶
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)
}
Output:
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)
}
}
Output:
func (*Client) GenerateImage ¶
func (c *Client) GenerateImage(ctx context.Context, req ImageGenerationRequest) (*ImageGenerationResponse, error)
GenerateImage sends POST /v1/images/generations using ModelImageV1 by default.
func (*Client) GetModel ¶
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 ¶
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)
}
}
Output:
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
WithBaseURL overrides DefaultBaseURL (for proxies, local gateways, or tests). Trailing slashes are stripped automatically.
func WithHTTPClient ¶
WithHTTPClient supplies a custom *http.Client for transport, proxy, or timeout control.
func WithUserAgent ¶
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.