llm

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 22 Imported by: 1 module, 1 package

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

🤖 llm — Starlark module for AI and LLM services

godoc license codecov binary footprint

A Starlark module for interacting with OpenAI and OpenAI-compatible API services. Generate text with chat completions and create images with DALL-E / GPT Image 1, directly from your Starlark scripts.

Overview

Within the Star* ecosystem — "starpkg = support for necessary LOCAL operations + simple abstractions over common ONLINE services, for ease of use" — llm is an online-service abstraction. It wraps a remote SaaS API behind three small script-facing builtins, so a script reaches a chat or image model without juggling HTTP, auth headers, retries, or response shapes.

  • Chat completions — chat for OpenAI GPT and reasoning models, with multi-turn conversations and multimodal inputs (text + images).
  • Image generation — draw for DALL-E 2/3 and GPT Image 1.
  • Message builder — message assembles a conversation message (text and/or image) for chat.
  • Many providers — the OpenAI API, Azure OpenAI Service, the Anthropic Claude API, and any OpenAI-compatible endpoint, selected by openai_provider.
  • Streaming — real-time responses with an optional per-chunk callback.
  • Robust calls — customizable retry behavior, graceful error handling (retry, allow_error), and custom/provider-specific parameters via kwargs.

It is an L3 domain module: it depends downward on starpkg/base (the module/config system), 1set/starlet (the Machine + dataconv), and transitively 1set/starlight + go.starlark.net. StarCLI registers this module; it does not depend upward on StarCLI.

For the complete per-builtin reference — signatures, parameters, returns, errors, examples — and the configuration accessors, see docs/API.md.

Installation

go get github.com/starpkg/llm

Quick Start

Wire the module into a Starlet interpreter, then load("llm", …) from a script. The Go layer provides the historical NewModule() (empty config) and NewModuleWithConfig(serviceProvider, endpointURL, apiKey, gptModel, dalleModel, apiVersion) (preset config) constructors. For a host that runs untrusted scripts, use NewModuleWithHostPolicy to bind credentials and the endpoint while keeping model selection in Starlark:

mod := llm.NewModuleWithHostPolicy(llm.HostPolicy{
    Provider:    "openai",
    EndpointURL: "https://api.openai.com/v1",
    APIKey:      os.Getenv("OPENAI_API_KEY"),
    FileRoot:    "/srv/llm-images", // empty disables image_file
})
package main

import (
    "fmt"
    "os"

    "github.com/1set/starlet"
    "github.com/starpkg/llm"
)

func main() {
    apiKey := os.Getenv("OPENAI_API_KEY")
    mod := llm.NewModuleWithConfig("openai", "", apiKey, "gpt-4o", "dall-e-3", "")

    interpreter := starlet.New(
        starlet.WithModuleLoader("llm", mod.LoadModule()),
    )

    script := `
load("llm", "chat", "draw")

# Generate text using GPT
response = chat(text="Explain quantum computing in simple terms.", max_tokens=100)
print("GPT response:", response)

# Generate an image using DALL-E
image_url = draw(prompt="A cute robot explaining quantum computing", size="1024x1024")
print("Image URL:", image_url)
`

    if err := interpreter.ExecScript("example.star", script); err != nil {
        fmt.Println("Error:", err)
    }
}

Hold a multi-turn conversation, building messages with message:

load("llm", "message", "chat")

messages = [
    message(role="user", text="Hello, who are you?"),
    message(role="assistant", text="I'm an AI assistant. How can I help you today?"),
    message(role="user", text="Can you explain what an LLM is?"),
]
print(chat(messages=messages, max_tokens=200))

Starlark API at a glance

Top-level builtins (load("llm", …)):

  • message(role?, text?, image?, image_file?, image_url?) — build a conversation message object for chat.
  • chat(text?, image?, image_file?, image_url?, messages?, model?, n?, max_tokens?, max_completion_tokens?, temperature?, top_p?, frequency_penalty?, presence_penalty?, stop?, response_format?, reasoning_effort?, retry?, full_response?, allow_error?, stream?, stream_callback?, kwargs?) — send a chat completion request (blocking or streaming).
  • draw(prompt, model?, n?, quality?, size?, style?, response_format?, background?, moderation?, output_format?, output_compression?, retry?, full_response?, allow_error?) — generate an image with DALL-E or GPT Image 1.

See docs/API.md for the full signatures, return values, errors, and examples of every builtin above.

Configuration

The module's options (openai_provider, openai_endpoint_url, openai_api_key, openai_gpt_model, openai_dalle_model, api_version, legacy_mode, request_timeout) are configured via environment variables (LLM_*) or per-option get_<key> / set_<key> accessor builtins, and serve as defaults for chat / draw. openai_api_key is secret — it exposes only set_openai_api_key, never a getter. request_timeout (default 120s) bounds each request (a total deadline for blocking chat/draw; a connect + first-response bound for streaming, so long streams aren't truncated). See the Configuration section of docs/API.md for the full option table, defaults, accessors, and the legacy_mode behavior.

Trust model — NewModule() and NewModuleWithConfig retain the historical self-configuring behavior: a script can choose its provider/endpoint/key, and image_file can read any host-readable file (bounded to 64 MiB). For untrusted scripts, NewModuleWithHostPolicy makes the provider, endpoint, and key host-only, rejects cross-origin redirects, and confines image_file to FileRoot (an empty root disables it). See Safety / trust model.

License

This package is licensed under the MIT License — see the LICENSE file for details.

Documentation

Overview

Package llm provides a Starlark module that calls OpenAI models.

Configuration options:

  • openai_provider: Provider type (openai, azure, anthropic)
  • openai_endpoint_url: API endpoint URL
  • openai_api_key: API key for authentication
  • openai_gpt_model: Default GPT model name
  • openai_dalle_model: Default DALL-E model name
  • api_version: API version (used by Azure and Anthropic)
  • legacy_mode: Use legacy mode for data conversion (default: true)
  • request_timeout: Per-request timeout in seconds (default: 120). Total deadline for blocking chat/draw; connect+first-response bound for streaming

The historical constructors let a script set the provider, endpoint, and key. Hosts running untrusted scripts can opt into NewModuleWithHostPolicy to bind those values, reject cross-origin redirects, and optionally jail image_file reads. See docs/API.md "Safety / trust model".

The chat function supports both blocking and streaming modes:

  • In blocking mode (default), the function waits for the complete response
  • In streaming mode (stream=True), responses are received incrementally and can be processed via a callback
  • Streaming mode can improve responsiveness for large responses or when displaying partial results is desired
  • To use streaming mode, set stream=True and optionally provide stream_callback=function
  • The stream_callback receives each chunk of the response as it arrives
  • In both streaming and blocking modes, the function returns the same format: either the complete content or full response
  • For streaming, the content is automatically aggregated from all chunks

Custom parameters support:

  • The kwargs parameter allows passing custom or non-standard parameters to the API
  • Useful for provider-specific features, experimental parameters, or custom deployments
  • Any dictionary passed as kwargs will be included in the ChatTemplateKwargs field of the API request

Token parameters for different models:

  • max_tokens: Maximum number of tokens to generate; 0 (the default) leaves it unset so the API applies its own default - works with most models
  • max_completion_tokens: Upper bound for generated completion tokens - for o1 series models
  • For o1, o3, o4 series models, use max_completion_tokens instead of max_tokens

When legacy_mode is true (default), response objects are converted using direct struct access (ConvertJSONStruct). When false, JSON conversion is used (GoToStarlarkViaJSON).

Index

Constants

View Source
const (
	// ProviderOpenAI represents the default OpenAI API provider
	ProviderOpenAI = "openai"
	// ProviderAzure represents the Azure OpenAI Service provider
	ProviderAzure = "azure"
	// ProviderAnthropic represents the Anthropic Claude API provider
	ProviderAnthropic = "anthropic"
)

Provider type constants

View Source
const ModuleName = "llm"

ModuleName defines the expected name for this module when used in Starlark's load() function, e.g., load('llm', 'chat')

Variables

This section is empty.

Functions

This section is empty.

Types

type HostPolicy added in v0.1.1

type HostPolicy struct {
	Provider    string
	EndpointURL string
	APIKey      string
	FileRoot    string
}

HostPolicy binds host-provided credentials and file access to a fixed endpoint. It is opt-in through NewModuleWithHostPolicy; NewModule and NewModuleWithConfig retain their historical self-configuring behavior.

Provider, EndpointURL, and APIKey are host-only in the policy constructor, so a script cannot redirect a host credential. Redirects must stay on the same scheme, host, and port as EndpointURL. FileRoot is resolved once when the module is constructed; image_file paths are anchored to it and symlinks that leave it are rejected. An empty FileRoot denies image_file inputs.

type Module

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

Module wraps the ConfigurableModule with specific functionality for calling OpenAI models.

func NewModule

func NewModule() *Module

NewModule creates a new instance of Module with default empty configurations.

func NewModuleWithConfig

func NewModuleWithConfig(serviceProvider, endpointURL, apiKey, gptModel, dalleModel, apiVersion string) *Module

NewModuleWithConfig creates a new instance of Module with the given configuration values.

func NewModuleWithHostPolicy added in v0.1.1

func NewModuleWithHostPolicy(policy HostPolicy) *Module

NewModuleWithHostPolicy creates a module for a host-controlled endpoint and credential. The provider, endpoint, and API key cannot be changed by Starlark. Models and ordinary request options remain script-settable, which preserves the module's small self-configuring surface without exposing the host credential to a script-selected endpoint.

FileRoot enables image_file only beneath the supplied directory. Relative paths are resolved from that root. Leave it empty to deny host file reads. Invalid policy values are reported when the module loader or a request is used, matching the existing deferred configuration-validation contract.

func (*Module) LoadModule

func (m *Module) LoadModule() starlet.ModuleLoader

LoadModule returns the Starlark module loader exposing the llm builtins (message, chat, draw) plus the generated config setters/getters.

func (*Module) SetClient

func (m *Module) SetClient(cli *oai.Client)

SetClient sets the OpenAI client for this module.

Jump to

Keyboard shortcuts

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