llm

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 18, 2026 License: MIT Imports: 18 Imported by: 1

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 completionschat for OpenAI GPT and reasoning models, with multi-turn conversations and multimodal inputs (text + images).
  • Image generationdraw for DALL-E 2/3 and GPT Image 1.
  • Message buildermessage 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 L4 domain module: it depends downward on starpkg/base (the module/config system), 1set/starlet (the Machine + dataconv), and transitively 1set/starlight + go.starlark.net. Nothing in the ecosystem depends on it.

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 two constructors: NewModule() (empty config) and NewModuleWithConfig(serviceProvider, endpointURL, apiKey, gptModel, dalleModel, apiVersion) (preset config).

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) 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. See the Configuration section of docs/API.md for the full option table, defaults, accessors, and the legacy_mode behavior.

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)

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 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 (*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