chatvllm

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 20 Imported by: 0

README

chat-vllm

The vLLM provider for go/chat.

Built to spec 0035, vLLM adapter, and checked against a GPU vLLM server before each release (see Running the live test).

It registers the vllm provider and talks to a vLLM server on its own HTTP client, with no OpenAI SDK underneath. Beyond chat it returns token log-probabilities and unexecuted tool calls through the core's interfaces, and adds what only vLLM serves: log-probabilities for named token IDs, the likelihood of a given answer, and listing, loading and unloading LoRA adapters.

Use

import (
	"gitlab.com/phpboyscout/go/chat"
	_ "gitlab.com/phpboyscout/go/chat-vllm"
)

client, err := chat.New(ctx, chat.Settings{Config: chat.Config{
	Provider: chat.ProviderVLLM,
	BaseURL:  "https://vllm.internal:8000/v1",
	Model:    "Qwen/Qwen3-8B",
}})
  • BaseURL and Model are required. BaseURL names the server's /v1 root; one that doesn't end in /v1 is refused with chatvllm.ErrBaseURLPath. Model is the name the server was started with, or a LoRA adapter it serves.
  • The key is optional. It comes from Config.Credential when one is set, and a broken source fails New. Otherwise it is Config.Token, then VLLM_API_KEY. With neither, no Authorization header is sent, which suits a server started without --api-key. No OPENAI_* variable is ever read.
  • Plain http:// needs Config.AllowInsecureBaseURL, which can only be set in code. Use it only for a server on a network you control.
  • vLLM's own sampling knobs go through chatvllm.New: WithTopK, WithMinP, WithRepetitionPenalty, WithSeed and WithChatTemplateKwargs (for enable_thinking and the like).

How it behaves

It implements chat, streaming, stateless use, sampling, Ask with a response schema, AddCached, Save and Restore, and history policies, and it passes the family's conformance suite. Where it differs from other providers:

  • Every model-dependent capability is Unknown. A server serves whatever its operator loaded, and nothing it exposes says what that model can do. Declare what you know with Config.Capabilities.
  • A reply cut off at the token limit is a *chat.TruncatedError carrying the partial text, and the question is taken back.
  • No refusals are reported: vLLM has no refusal field.
  • No effort setting: vLLM passes reasoning_effort to the chat template, which most ignore.
  • Images only, as image_url parts; no documents.
  • AddCached pins turns so a history policy keeps the prefix vLLM's automatic prefix caching reuses. No cache key is sent.
  • chat.CompactOldest summarises without this module's options. A client from chatvllm.New is summarised on its own Config, without WithSeed, WithTopK or the other sampling and template options, because they shape output.
  • A tool's schema is sent whole, and this adapter doesn't make the model keep to it. Both Chat and ProposeToolCalls leave tool choice at auto and strict unset, so whether arguments are held to the schema is up to the server's --tool-strict-level and its tool parser: see vLLM's tool calling docs. Unless you know the server enforces it, validate arguments in the handler. How a model's chat template renders keywords such as $defs and $ref is unproved: spec 0043's live run didn't include vLLM, so this path has only unit tests.
  • Retries follow openai-go's rules: connection errors, 408, 409, 429 and 5xx, honouring Retry-After up to two minutes, two retries unless Config.MaxRetries says otherwise.

Log-probabilities

Two calls on *chatvllm.Client return them, following spec 0032, token log-probabilities:

vllm := client.(*chatvllm.Client)

scored, err := vllm.ChatWithLogprobs(ctx, "Is the sky green? Answer yes or no.", 5)
// scored.Tokens[i].Logprob, and scored.Tokens[i].Top: up to five alternatives, most likely first

scores, err := vllm.ChatWithTokenLogprobs(ctx, prompt, []int{9454, 2753})
// scores.Positions[i].Named: the log-probability of each ID at that position, in the order given
  • Each is one request, outside the conversation. It sends the system prompt and the prompt alone, offers no tools, reads and records no history, and doesn't wait for a conversational call in flight. Usage is counted in Usage(), but History().LastInputTokens keeps the last conversational request's figure, so a long one-off prompt can't trigger compaction.
  • top is 0 to 20, or -1 for the whole vocabulary on a server started with --max-logprobs -1. A request over the server's --max-logprobs, or a token ID outside its vocabulary, is chat.ErrModelRejectedParameter.
  • ids holds 1 to 128 distinct token IDs, vLLM's limit. They're the model's tokenizer IDs.
  • A reply with no log-probabilities is chat.ErrLogprobsUnavailable, never an empty result, and one cut off at the token limit is a *chat.TruncatedError.
  • ChatWithLogprobs is the core's chat.LogprobsCapable. chatvllm.Scored and chatvllm.TokenLogprob are aliases of the core's types, so a fallback chain of clients that all implement it offers it too. ChatWithTokenLogprobs is vLLM's alone.

The likelihood of a given answer

Likelihood scores an answer you supply as the assistant's reply to a prompt, without generating one:

l, err := vllm.Likelihood(ctx, "What is the capital of France?", "Paris")
// l.Sum, l.Tokens[i].Logprob, and l.Scored: the answer as the template rendered it
  • The server's chat template does the rendering, so you never render one. Templates may trim the answer's edges (a leading space or newline), which is why Scored is returned.
  • Two requests: /tokenize on the conversation with an empty answer finds where the answer starts, then one chat request with prompt_logprobs scores it. Only the second is counted in usage. If the empty-answer tokens aren't a prefix of what was scored, it's an error rather than a score of the wrong tokens.
  • Like the other calls here, it sends the system prompt and the prompt alone, neither reads nor records history, and runs outside the conversation. WithChatTemplateKwargs applies to both requests.

Tool calls without running them

ProposeToolCalls offers tools and returns the calls the model makes, without running them, following spec 0034, tool calls without execution:

proposal, err := vllm.ProposeToolCalls(ctx, "What's the weather in Leeds?", []chat.Tool{weather})
// proposal.Calls[i].Name, .Input (the arguments exactly as the model wrote them) and .ID
  • The tools carry no Handler. One that does is refused, so a handler can't be passed and silently not run. Parameters is required, as for SetTools.
  • One request, outside the conversation, as for log-probabilities: the system prompt and the prompt alone, tool_choice auto, history neither read nor recorded, and the tools from SetTools left alone.
  • Every call, in order, or none: the model may answer in text instead, and that is in proposal.Text.
  • The server must be started with tool calling (--enable-auto-tool-choice and --tool-call-parser); without it the request is a 400 naming those flags.
  • It is the core's chat.ToolCallProposer, and chatvllm.Proposal and chatvllm.ToolCall are aliases of the core's types, so the calls go straight to chat.ExecuteToolsParallel.

Models and adapters

Models lists what a server serves, and LoadAdapter and UnloadAdapter change which LoRA adapters it has loaded. They are package functions, since they address the server rather than one model, and take the same chat.Config: BaseURL, the key and HTTPClient apply, and Model is ignored.

models, err := chatvllm.Models(ctx, cfg)
// models[i].ID, .Parent (empty for a base model) and .MaxModelLen (zero for an adapter)

err = chatvllm.LoadAdapter(ctx, cfg, "tldr", "/adapters/tldr")
err = chatvllm.UnloadAdapter(ctx, cfg, "tldr")

To compare several models or adapters, list them and build one client per entry, sharing one Config.HTTPClient, as spec 0033, choosing the model per request describes.

  • Loading twice is not an error. LoadAdapter lists the server's models first, and leaves an adapter already loaded under that name from the same path as it is. The same name from another path, or a base model's name, is refused before anything is loaded.
  • The adapter routes exist only on a server started with VLLM_ALLOW_RUNTIME_LORA_UPDATING=True, which vLLM warns is for local development only. Without it, both functions return chatvllm.ErrRuntimeAdaptersDisabled.
  • Unloading a name with nothing loaded returns chatvllm.ErrAdapterNotLoaded.
  • The path is read by the server, so it names a directory on the server or a Hugging Face repository it can fetch.

Errors from the server are *chatvllm.APIError, carrying the status, vLLM's error type and its message.

The family's documentation lives at https://chat.go.phpboyscout.uk.

Running the live test

The unit tests run against a stub. Before each release, the live test runs by hand against a real server with a GPU; CI runners can't hold a model through a log-probability request. Start the server with tool calling and runtime adapters, and leave --max-logprobs at its default of 20:

VLLM_ALLOW_RUNTIME_LORA_UPDATING=True vllm serve Qwen/Qwen3-0.6B \
  --enable-auto-tool-choice --tool-call-parser hermes \
  --enable-lora --max-lora-rank 64

Then point the tests at it:

INT_TEST_VLLM=1 VLLM_BASE_URL=http://gpu-host:8000/v1 go test -run Live -v ./...
  • VLLM_MODEL picks the model; unset, it's the first base model the server lists.
  • VLLM_LORA_PATH is an adapter for that model, to load, chat through and unload. Unset, that part is skipped.
  • VLLM_API_KEY, with the server started with the same --api-key, adds the check that a wrong key is a 401.
  • With -v the test logs what spec 0035 left to observe but chat-vllm doesn't depend on: entry order in log-probability replies, and completions echo with max_tokens: 0.

Licence

MIT. See LICENSE.

Documentation

Overview

Package chatvllm is the vLLM provider for gitlab.com/phpboyscout/go/chat. It speaks vLLM's OpenAI-compatible routes on its own HTTP client, and adds what only vLLM serves: log-probabilities, answer scoring, model and LoRA adapter discovery, and loading adapters at runtime.

Index

Constants

View Source
const EnvVLLMKey = "VLLM_API_KEY"

EnvVLLMKey is the environment variable read for the server's API key when neither Config.Credential nor Config.Token is set. Unset, no key is sent, since vLLM authenticates only when started with --api-key (spec 0035 D4).

Variables

View Source
var ErrAdapterNotLoaded = errors.NewSentinel("chatvllm.adapter_not_loaded",
	"no adapter is loaded under that name")

ErrAdapterNotLoaded is returned when unloading a name the server has no adapter loaded under.

View Source
var ErrBaseURLPath = errors.NewSentinel("chatvllm.base_url_path",
	"vLLM base URL must name the server's /v1 root, such as https://host:8000/v1")

ErrBaseURLPath is returned when Config.BaseURL does not end in /v1.

View Source
var ErrLogprobsUnavailable = chat.ErrLogprobsUnavailable

ErrLogprobsUnavailable is chat.ErrLogprobsUnavailable, so errors.Is matches either.

View Source
var ErrRuntimeAdaptersDisabled = errors.NewSentinel("chatvllm.runtime_adapters_disabled",
	"runtime adapter loading is not enabled on this server")

ErrRuntimeAdaptersDisabled is returned when the server has no adapter routes, because it was started without VLLM_ALLOW_RUNTIME_LORA_UPDATING.

Functions

func LoadAdapter

func LoadAdapter(ctx context.Context, cfg chat.Config, name, path string) error

LoadAdapter loads the LoRA adapter at path, a directory or Hugging Face repository the server can read, under name. An adapter already loaded under name from the same path is left as it is, so loading twice is not an error.

func New

func New(ctx context.Context, settings chat.Settings, opts ...Option) (chat.ChatClient, error)

New builds a Client with options the registry path cannot carry. Otherwise chat.New with chat.ProviderVLLM does the same job. It goes through chat.NewWithFactory so every guard chat.New applies runs here too.

func UnloadAdapter

func UnloadAdapter(ctx context.Context, cfg chat.Config, name string) error

UnloadAdapter unloads the LoRA adapter loaded under name.

Types

type APIError

type APIError struct {
	// StatusCode is the HTTP status.
	StatusCode int
	// Type is vLLM's error type, such as NotFoundError, when it sent one.
	Type string
	// Param names the request field at fault, when vLLM said.
	Param string
	// Message is the server's own account of the failure.
	Message string
}

APIError is a non-2xx answer from the vLLM server, decoded from either of its error bodies.

func (*APIError) Error

func (e *APIError) Error() string

type Client

type Client struct {
	chat.UsageTracker
	// contains filtered or unexported fields
}

Client is a chat.ChatClient for a vLLM server.

func (*Client) Add

func (c *Client) Add(ctx context.Context, prompt string, media ...chat.Media) error

Add appends a user turn without sending it.

func (*Client) AddCached

func (c *Client) AddCached(ctx context.Context, prompt string, media ...chat.Media) error

AddCached appends a user turn and pins it, so a history policy cannot drop the prefix vLLM's automatic prefix caching keeps hitting. No cache key is sent (spec 0035 D11).

func (*Client) ApplyPolicyNow

func (c *Client) ApplyPolicyNow(ctx context.Context, policy chat.HistoryPolicy) (int, error)

ApplyPolicyNow bounds the retained conversation now rather than before the next request. A nil policy means the configured one; with none, it does nothing.

func (*Client) Ask

func (c *Client) Ask(ctx context.Context, question string, target any, media ...chat.Media) error

Ask sends a question and decodes the answer into target, as JSON when Config.ResponseSchema is set and as text otherwise. It offers no tools.

func (*Client) Chat

func (c *Client) Chat(ctx context.Context, prompt string, media ...chat.Media) (string, error)

Chat sends a prompt and returns the reply, running any tools it calls.

func (*Client) ChatWithLogprobs

func (c *Client) ChatWithLogprobs(ctx context.Context, prompt string, top int, media ...chat.Media) (Scored, error)

ChatWithLogprobs sends prompt after the system prompt alone and returns the reply with each token's log-probability and up to top alternatives. top is 0 to 20, or -1 for the whole vocabulary on a server started with --max-logprobs -1. It offers no tools and neither reads nor records history.

func (*Client) ChatWithTokenLogprobs

func (c *Client) ChatWithTokenLogprobs(ctx context.Context, prompt string, ids []int, media ...chat.Media) (TokenScores, error)

ChatWithTokenLogprobs returns the log-probability of each named token ID at every generated position. ids holds 1 to 128 distinct, non-negative IDs; the server rejects one outside its vocabulary. It offers no tools and neither reads nor records history.

func (*Client) History

func (c *Client) History() chat.History

History reports the turns this client will re-send, the system turn and any buffered Add turns included. Known is true: this client owns its transcript.

func (*Client) Likelihood

func (c *Client) Likelihood(ctx context.Context, prompt, answer string) (Likelihood, error)

Likelihood returns the log-probability of each token of answer as the assistant's reply to prompt, under the server's chat template, without generating. It neither reads nor records history.

It makes two requests: /tokenize on the conversation with an empty answer gives where the answer starts, and one chat request with prompt_logprobs scores it. Only the second is counted in usage.

func (*Client) Model

func (c *Client) Model() string

Model implements chat.ModelIdentifier.

func (*Client) ProposeToolCalls

func (c *Client) ProposeToolCalls(ctx context.Context, prompt string, tools []chat.Tool, media ...chat.Media) (Proposal, error)

ProposeToolCalls offers tools to the model and returns the calls it makes, in order, without running them. The tools must carry no Handler. It sends prompt after the system prompt alone, with tool_choice auto, and neither reads nor records history.

func (*Client) Provider

func (c *Client) Provider() chat.Provider

Provider implements chat.ModelIdentifier.

func (*Client) Restore

func (c *Client) Restore(snapshot *chat.Snapshot) error

Restore replaces the conversation with a snapshot Save wrote. It waits its turn, so a call in flight cannot commit over the restored conversation.

func (*Client) Save

func (c *Client) Save() (*chat.Snapshot, error)

Save captures the conversation. A stateless client keeps none, so its snapshot carries only the system turn.

func (*Client) SetTools

func (c *Client) SetTools(tools []chat.Tool) error

SetTools replaces the tools offered to the model.

func (*Client) StreamChat

func (c *Client) StreamChat(ctx context.Context, prompt string, callback chat.StreamCallback, media ...chat.Media) (string, error)

StreamChat is Chat with the reply delivered to callback as it arrives.

func (*Client) SummariserFactory added in v0.4.0

func (c *Client) SummariserFactory() chat.ProviderFactory

SummariserFactory implements chat.SummariserFactory with the registry factory: every option this module owns shapes output, so a summariser carries none of them. See https://gitlab.com/phpboyscout/go/chat/-/wikis/specs/0040-summariser-on-the-callers-credentials.

func (*Client) SupportsSampling

func (c *Client) SupportsSampling()

SupportsSampling marks Client as able to carry Config.Temperature and TopP.

func (*Client) SupportsStateless

func (c *Client) SupportsStateless()

SupportsStateless marks Client as honouring chat.Config.Stateless.

type IDLogprob

type IDLogprob struct {
	ID      int
	Logprob float64
}

IDLogprob is a token ID and its log-probability, which vLLM clamps at -9999.

type Likelihood

type Likelihood struct {
	Scored string
	Tokens []TokenLogprob
	Sum    float64
}

Likelihood is the log-probability of an answer, token by token. Scored is the answer as the chat template rendered it, which may trim its edges.

type Model

type Model struct {
	ID          string
	Parent      string // empty for a base model
	MaxModelLen int    // zero for an adapter
}

Model is one model a server serves: a base model or a LoRA adapter on one.

func Models

func Models(ctx context.Context, cfg chat.Config) ([]Model, error)

Models lists what the server at cfg.BaseURL serves: base models with their context length, and LoRA adapters with their parent. It ignores cfg.Model.

type Option

type Option func(*options)

Option configures a Client at construction with a knob only vLLM understands. Each becomes a field on every chat request.

func WithChatTemplateKwargs

func WithChatTemplateKwargs(kwargs map[string]any) Option

WithChatTemplateKwargs passes arguments to the model's chat template, such as enable_thinking. Later calls add to, and override, earlier ones.

func WithMinP

func WithMinP(p float64) Option

WithMinP drops tokens whose probability is below p times the most likely one's.

func WithRepetitionPenalty

func WithRepetitionPenalty(p float64) Option

WithRepetitionPenalty penalises tokens already in the prompt or reply; 1 is no penalty.

func WithSeed

func WithSeed(seed int64) Option

WithSeed pins the sampling seed.

func WithTopK

func WithTopK(k int) Option

WithTopK limits sampling to the k most likely tokens.

type PositionScores

type PositionScores struct {
	Chosen IDLogprob
	Named  []IDLogprob
}

PositionScores is one generated position: the token chosen there, and each named ID in the order requested.

type Proposal

type Proposal = chat.Proposal

Proposal and ToolCall are the core's, kept under these names so callers written before the core took them over still compile.

type Scored

type Scored = chat.Scored

Scored and TokenLogprob are the core's, kept under these names so callers written before the core took them over still compile.

type TokenLogprob

type TokenLogprob = chat.TokenLogprob

Scored and TokenLogprob are the core's, kept under these names so callers written before the core took them over still compile.

type TokenScores

type TokenScores struct {
	Text      string
	Positions []PositionScores
}

TokenScores is a reply with the log-probability of each named token ID at every generated position.

type ToolCall

type ToolCall = chat.ToolCall

Proposal and ToolCall are the core's, kept under these names so callers written before the core took them over still compile.

Jump to

Keyboard shortcuts

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