serve

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 27 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.

Documentation

Overview

Package serve provides OpenAI-compatible HTTP inference serving and SGLang gRPC worker endpoints.

The PufferLib policy network and Breakout environment are in github.com/tmc/pufferlib-go/nvidia.

This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.

Example
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"net/http/httptest"
	"strings"

	nnserve "github.com/tmc/lib/nvidia/x/nn/serve"
)

// echoEngine generates the prompt back, one token at a time.
type echoEngine struct{}

func (echoEngine) Generate(ctx context.Context, req *nnserve.Request, emit func([]int32) error) (nnserve.Finish, error) {
	for i, t := range req.Input {
		if i == int(req.Sampling.MaxNewTokens) {
			break
		}
		if err := emit([]int32{t}); err != nil {
			return nnserve.Finish{}, err
		}
	}
	return nnserve.Finish{Reason: nnserve.FinishLength}, nil
}

func (echoEngine) Flush(context.Context) error { return nil }

func main() {
	srv, err := nnserve.NewSGLangServer(echoEngine{}, nnserve.SGLangConfig{
		ModelPath:     "models/echo",
		ContextLength: 4096,
	})
	if err != nil {
		log.Fatal(err)
	}
	ts := httptest.NewServer(srv.HTTP())
	defer ts.Close()

	body := `{"input_ids": [11, 12, 13], "sampling_params": {"max_new_tokens": 2}}`
	resp, err := http.Post(ts.URL+"/generate", "application/json", strings.NewReader(body))
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	var out struct {
		OutputIDs []int32 `json:"output_ids"`
		MetaInfo  struct {
			FinishReason     json.RawMessage `json:"finish_reason"`
			CompletionTokens int             `json:"completion_tokens"`
		} `json:"meta_info"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
		log.Fatal(err)
	}
	fmt.Println(out.OutputIDs, out.MetaInfo.CompletionTokens, string(out.MetaInfo.FinishReason))
}
Output:
[11 12] 2 {"type":"length","length":2}

Index

Examples

Constants

View Source
const (
	FinishStop   = "stop"   // an EOS or stop token was generated
	FinishLength = "length" // MaxNewTokens or the context length was reached
	FinishAbort  = "abort"  // the engine gave up on the request
)

Finish reasons, as SGLang names them in meta_info.finish_reason.type.

Variables

This section is empty.

Functions

func GPUVisTelemetrySource

func GPUVisTelemetrySource(
	group interface{ SetObserver(func(ncclx.Submission)) },
	calibration GPUVisNCCL,
	maxSubmissions int,
	snapshot func(context.Context) (*GPUVisSnapshot, error),
) (func(context.Context) (*GPUVisSnapshot, error), error)

GPUVisTelemetrySource attaches a bounded host submission collector to a group and combines it with the owner's retained, calibrated IKET capture. It observes host Group.Launch API intervals, including failures before enqueue. The observer has no device completion or collective-level signal.

The owner installs the observer before starting group launches and keeps it installed for the capture. The group must have no concurrent launches while installing or replacing an observer. The calibration and retained snapshot must describe the same capture and the same clock axis. The snapshot callback supplies the ring and any profiler evidence, with NCCL left nil. The collector counts loss across the capture, even for an earlier retained window.

Types

type AdapterOption

type AdapterOption func(*BatchEngineAdapter)

AdapterOption configures BatchEngineAdapter.

func WithContinuationTracker

func WithContinuationTracker(ct *cudabatch.ContinuationTracker) AdapterOption

WithContinuationTracker sets session transcript bookkeeping. Requests must include their full conversation; snapshots do not retain reusable KV blocks.

func WithShapeBucket

func WithShapeBucket(b cudabatch.ShapeBucket) AdapterOption

WithShapeBucket sets the shape bucket used for binding.

func WithStepTicker

func WithStepTicker(d time.Duration) AdapterOption

WithStepTicker sets the background iteration polling interval.

type BatchEngineAdapter

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

BatchEngineAdapter wraps cudabatch.BatchScheduler and an ExecutionEngine into cudaserver.Engine, enabling live continuous batching for HTTP requests.

func NewBatchEngineAdapter

func NewBatchEngineAdapter(
	scheduler *cudabatch.BatchScheduler,
	execEngine cudabatch.ExecutionEngine,
	tokenizer Tokenizer,
	opts ...AdapterOption,
) *BatchEngineAdapter

NewBatchEngineAdapter creates an adapter bridging cudabatch and cudaserver.

func (*BatchEngineAdapter) Close

func (a *BatchEngineAdapter) Close()

Close cancels the adapter's batch context, stopping a forward step that is waiting on the device for every row in its batch. It is the batch owner's abort, for engine shutdown; to stop one request, cancel the context passed to Generate, which removes only that request's rows.

func (*BatchEngineAdapter) ContinuationTracker

func (a *BatchEngineAdapter) ContinuationTracker() *cudabatch.ContinuationTracker

ContinuationTracker returns the active multi-turn continuation tracker.

func (*BatchEngineAdapter) Drain

func (a *BatchEngineAdapter) Drain(ctx context.Context) error

Drain waits for a retained execution using ctx. It releases scheduler resources only after the execution reports Done. A failed wait can be retried; no background goroutine assumes ownership of native buffers.

Example
package main

import (
	"context"
	"fmt"

	nnserve "github.com/tmc/lib/nvidia/x/nn/serve"
)

func main() {
	adapter := nnserve.NewBatchEngineAdapter(nil, nil, nil)
	fmt.Println(adapter.Drain(context.Background()))
}
Output:
<nil>

func (*BatchEngineAdapter) Generate

func (a *BatchEngineAdapter) Generate(ctx context.Context, req ChatCompletionRequest, tokenChan chan<- string) error

Generate implements the cudaserver.Engine interface.

func (*BatchEngineAdapter) GenerateWithUsage

func (a *BatchEngineAdapter) GenerateWithUsage(ctx context.Context, req ChatCompletionRequest, tokenChan chan<- string) (UsageStats, error)

GenerateWithUsage counts the rendered prompt's tokenizer IDs and the scheduler's generated token IDs. Stream chunk lengths do not affect usage.

func (*BatchEngineAdapter) StepIteration

func (a *BatchEngineAdapter) StepIteration(ctx context.Context) error

StepIteration advances the continuous batch scheduler by one forward iteration. Can be run in a loop or driven deterministically by tests.

ctx bounds draining a retained execution. The forward step itself waits with the adapter's batch context, which only Close cancels, so that no request's context can stop a step its batch shares.

type ChatChoice

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

ChatChoice represents a single completion choice.

type ChatCompletionChunk

type ChatCompletionChunk struct {
	ID      string         `json:"id"`
	Object  string         `json:"object"`
	Created int64          `json:"created"`
	Model   string         `json:"model"`
	Choices []StreamChoice `json:"choices"`
}

ChatCompletionChunk represents an SSE streaming data chunk.

type ChatCompletionRequest

type ChatCompletionRequest struct {
	Model            string        `json:"model"`
	Messages         []ChatMessage `json:"messages"`
	Stream           bool          `json:"stream"`
	Temperature      float32       `json:"temperature,omitempty"`
	TopP             float32       `json:"top_p,omitempty"`
	MaxTokens        int           `json:"max_tokens,omitempty"`
	SessionID        string        `json:"session_id,omitempty"`
	ResponsesVisible bool          `json:"responses_visible,omitempty"`
	ThinkingVisible  bool          `json:"thinking_visible,omitempty"`
}

ChatCompletionRequest represents an OpenAI-compatible /v1/chat/completions payload.

type ChatCompletionResponse

type ChatCompletionResponse struct {
	ID      string       `json:"id"`
	Object  string       `json:"object"`
	Created int64        `json:"created"`
	Model   string       `json:"model"`
	Choices []ChatChoice `json:"choices"`
	// Usage is nil when the engine does not report tokenizer counts.
	Usage *UsageStats `json:"usage,omitempty"`
}

ChatCompletionResponse represents the full non-streaming response.

type ChatMessage

type ChatMessage struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

ChatMessage represents a single turn in a chat conversation.

type DebugHandlers

type DebugHandlers struct {
	// GPUVis reads a fresh snapshot from the serving backend for each GET.
	GPUVis func(context.Context) (*DebugSnapshot, error)

	// HotSwap serves the admission-gated httpapi handler. The server
	// forwards POST /debug/hotswap to /v1/push.
	HotSwap *httpapi.Handler
}

DebugHandlers selects the optional serving debug routes. Applications that expose these routes outside a trusted listener should authenticate them with their HTTP middleware.

type DebugRoutes

type DebugRoutes struct {
	Authorize func(*http.Request) bool
	GPUVis    func(context.Context) (*iket.FlightRingSnapshot, error)
	Telemetry func(context.Context) (*GPUVisSnapshot, error)
	Snapshot  func(context.Context) (*DebugSnapshot, error)
	Hotswap   http.Handler
	Admission *httpapi.Handler
}

DebugRoutes configures optional serving diagnostics and hot-swap routes. Authorize must authenticate and authorize each debug request. GPUVis supplies a decoded flight ring snapshot that is safe to read for the request's lifetime. Telemetry supplies a GPUVis snapshot with optional NCCL and profiler data. Snapshot supplies an active generation and its associated diagnostics. Configure at most one of GPUVis, Telemetry and Snapshot. Hotswap supplies the application's handler. Configure its receipt policy before mounting it. Admission handles the receipt-gated kernel push at POST /debug/hotswap. When both handlers are configured, Hotswap must be a qualified-stage HTTP API handler. The application owns their resources.

Example
package main

import (
	"context"
	"fmt"
	"github.com/tmc/lib/nvidia/x/nn/serve"
	"net/http"
	"net/http/httptest"

	"github.com/tmc/lib/nvidia/x/obs/iket"
)

func main() {
	s := serve.New(nil, "example")
	h, err := s.HandlerWithDebug(serve.DebugRoutes{
		Authorize: func(*http.Request) bool { return true },
		Snapshot: func(context.Context) (*serve.DebugSnapshot, error) {
			return &serve.DebugSnapshot{Timeline: &iket.GPUVisTimeline{}}, nil
		},
	})
	if err != nil {
		panic(err)
	}
	w := httptest.NewRecorder()
	h.ServeHTTP(w, httptest.NewRequest("GET", "/debug/gpuvis", nil))
	fmt.Println(w.Code)
}
Output:
200

type DebugSnapshot

type DebugSnapshot struct {
	Active   *hotswap.State       `json:"active,omitempty"`
	Timeline *iket.GPUVisTimeline `json:"timeline,omitempty"`
	Limiter  *limiter.Verdict     `json:"limiter,omitempty"`
	Stallmap *stallmap.Map        `json:"stallmap,omitempty"`
}

A DebugSnapshot describes the serving backend's active generation and observations. The provider is responsible for matching samples and verdicts to the kernel generation they describe.

type Engine

type Engine interface {
	Generate(ctx context.Context, req ChatCompletionRequest, tokenChan chan<- string) error
}

Engine is the backend inference engine driving model generation. Generate must stop when ctx is canceled and must not close tokenChan.

type Finish

type Finish struct {
	Reason       string // FinishStop, FinishLength or FinishAbort
	Matched      int32  // for FinishStop, the EOS or stop token generated
	Message      string // for FinishAbort, why
	CachedTokens int    // prompt tokens served from a prefix cache
}

A Finish says how a generation ended.

type GPUVisKernel

type GPUVisKernel struct {
	CaptureID, Device, CubinSHA256 string
	StallMap                       *stallmap.Map
	Limiter                        *limiter.Verdict
	// LaunchEvidence is optional provenance supplied and validated by the producer.
	LaunchEvidence json.RawMessage
}

GPUVisKernel associates capture-level profiler evidence with the exact executable artifact. The provider binds the limiter input to this capture and cubin. StallMap supplies its own cubin digest for a cross-check.

type GPUVisNCCL

type GPUVisNCCL struct {
	CaptureID, Device               string
	DeviceOrdinal                   int
	HostAnchor                      time.Time
	TimelineAnchorNs, UncertaintyNs int64
	Submissions                     []ncclx.Submission
	// Dropped counts observed submissions discarded at the retention limit.
	Dropped uint64
}

GPUVisNCCL describes host submission intervals for the observed transport, including peer kernels and libNCCL, using an anchor measured by the provider on both the host and the IKET timeline. HostAnchor and the submissions must share the same process clock. Uncertainty is an upper bound supplied by the provider, in nanoseconds.

type GPUVisSnapshot

type GPUVisSnapshot struct {
	Ring              *iket.FlightRingSnapshot
	CaptureID, Device string
	// StartNs and EndNs delimit the capture on the same axis as Ring.
	StartNs, EndNs int64
	NCCL           *GPUVisNCCL
	Kernels        []GPUVisKernel
}

GPUVisSnapshot combines an IKET snapshot with optional serving telemetry. CaptureID and Device identify the recording and device at the producer. The provider must retain the inputs unchanged for the duration of export.

func (*GPUVisSnapshot) Timeline

func (s *GPUVisSnapshot) Timeline() (*iket.GPUVisTimeline, error)

Timeline returns an IKET GPUVis timeline with matching host submissions and capture-level profiler evidence. Profiler evidence is exported as metadata because it does not describe an individual launch timestamp.

type Metrics

type Metrics struct {
	RequestsTotal       uint64
	OutputChunksTotal   uint64
	AvgTimeToFirstToken float64
	AvgInterTokenTime   float64
}

Metrics represents runtime performance metrics.

type Profiler

type Profiler interface {
	Start(dir string) error
	Stop() (summary string, err error)
}

A Profiler records a profile of the engine into a directory. github.com/tmc/lib/nvidia/x/cudaprof.Recorder is one.

type Request

type Request struct {
	ID           string // SGLang rid; assigned by the server when the client sends none
	Input        []int32
	Sampling     Sampling
	Stream       bool
	TraceHeaders map[string]string // W3C trace context and other propagation headers
}

A Request is one generation request.

type RequestValidator

type RequestValidator interface {
	Validate(*Request) error
}

A RequestValidator is an Engine that checks requests before generation. An error is reported to the client as an invalid argument.

type SGLangConfig

type SGLangConfig struct {
	// ModelPath is reported as model_path. It is required.
	ModelPath string
	// TokenizerPath is reported as tokenizer_path. The default is ModelPath.
	TokenizerPath string
	// ServedModelName is the model ID in /v1/models and ListModels and the
	// model_name metric label. The default is ModelPath.
	ServedModelName string
	// ContextLength bounds prompt plus output tokens. It is required.
	ContextLength int
	// MaxTotalTokens is the engine's KV capacity in tokens, reported as
	// max_total_num_tokens when positive.
	MaxTotalTokens int
	// Version is reported as version in the server info.
	Version string

	// Profiler serves StartProfile and StopProfile. Without one, they fail.
	Profiler Profiler
	// ProfileDir is where a profile goes when StartProfile names no directory.
	ProfileDir string

	// Debug enables optional diagnostic and hot-swap HTTP routes.
	Debug       DebugHandlers
	DebugRoutes DebugRoutes

	// Tracer records a span per generation request. It may be nil.
	Tracer *otlp.Tracer
}

Config describes the model a Server serves.

type SGLangEngine

type SGLangEngine interface {
	Generate(ctx context.Context, req *Request, emit func(tokens []int32) error) (Finish, error)
	Flush(ctx context.Context) error
}

An Engine generates token IDs.

Generate runs one request. It calls emit with each batch of new output tokens, in order, and returns how generation finished. If emit returns an error, Generate stops and returns that error. Generate must return promptly once ctx is done; the server cancels ctx when the request is aborted or its client goes away. Generate is called concurrently.

Flush drops any cached prefix state.

type SGLangServer

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

A Server serves an Engine through SGLang's worker interfaces. Use New to make one.

func NewSGLangServer

func NewSGLangServer(eng SGLangEngine, cfg SGLangConfig) (*SGLangServer, error)

New returns a server for eng.

func (*SGLangServer) GRPC

func (s *SGLangServer) GRPC() http.Handler

GRPC returns a handler for the gRPC service sglang.runtime.v1.SglangService. gRPC needs HTTP/2. Serve the handler over TLS, or set http.Server.Protocols to allow unencrypted HTTP/2, as gRPC clients without TLS expect. Methods the server does not implement fail with status UNIMPLEMENTED.

Example

ExampleSGLangServer_GRPC serves the gRPC service and the HTTP API on one unencrypted port, as an SGLang worker started with a gRPC port does on two.

package main

import (
	"context"
	"log"
	"net/http"
	"strings"

	nnserve "github.com/tmc/lib/nvidia/x/nn/serve"
)

// echoEngine generates the prompt back, one token at a time.
type echoEngine struct{}

func (echoEngine) Generate(ctx context.Context, req *nnserve.Request, emit func([]int32) error) (nnserve.Finish, error) {
	for i, t := range req.Input {
		if i == int(req.Sampling.MaxNewTokens) {
			break
		}
		if err := emit([]int32{t}); err != nil {
			return nnserve.Finish{}, err
		}
	}
	return nnserve.Finish{Reason: nnserve.FinishLength}, nil
}

func (echoEngine) Flush(context.Context) error { return nil }

func main() {
	srv, err := nnserve.NewSGLangServer(echoEngine{}, nnserve.SGLangConfig{
		ModelPath:     "models/echo",
		ContextLength: 4096,
	})
	if err != nil {
		log.Fatal(err)
	}
	api, grpc := srv.HTTP(), srv.GRPC()
	h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if strings.HasPrefix(r.Header.Get("Content-Type"), "application/grpc") {
			grpc.ServeHTTP(w, r)
			return
		}
		api.ServeHTTP(w, r)
	})
	hs := &http.Server{Addr: "localhost:30001", Handler: h, Protocols: new(http.Protocols)}
	hs.Protocols.SetHTTP1(true)
	hs.Protocols.SetUnencryptedHTTP2(true)
	_ = hs // call hs.ListenAndServe() to serve
}

func (*SGLangServer) HTTP

func (s *SGLangServer) HTTP() http.Handler

HTTP returns a handler for SGLang's HTTP API:

POST /generate          generate from input_ids, streaming as server-sent events if asked
GET  /health            200 while the server accepts requests, else 503
GET  /health_generate   generate one token from input_ids [0]
GET  /model_info        model_path, tokenizer_path, is_generation
GET  /server_info       the configuration a router reads
GET  /v1/models         the served model, in OpenAI's format
POST /flush_cache       drop the engine's cache; refused while requests run
GET  /metrics           Prometheus metrics with SGLang's names
POST /start_profile     start the Profiler, in the body's output_dir if any
POST /stop_profile      stop the Profiler and return its summary

A streamed /generate sends the output tokens so far in each event, as SGLang does by default, and ends with "data: [DONE]". Errors are JSON objects {"error": {"message": ...}}. As in SGLang, /flush_cache, /start_profile and /stop_profile also accept GET.

func (*SGLangServer) Healthy

func (s *SGLangServer) Healthy() bool

Healthy reports whether s accepts new requests.

func (*SGLangServer) Shutdown

func (s *SGLangServer) Shutdown(ctx context.Context) error

Shutdown stops accepting requests and waits for running ones to finish. If ctx is done first, Shutdown aborts them and returns ctx's error.

type Sampling

type Sampling struct {
	Temperature       float32
	TopP              float32
	TopK              int32 // -1 means all tokens
	MinP              float32
	FrequencyPenalty  float32
	PresencePenalty   float32
	RepetitionPenalty float32
	MaxNewTokens      int32
	MinNewTokens      int32
	StopTokenIDs      []int32
	IgnoreEOS         bool
	Seed              int64
	HasSeed           bool
	// contains filtered or unexported fields
}

Sampling is the subset of SGLang's SamplingParams a token-ID engine can honor. DefaultSampling returns SGLang's defaults. Before generation the server lowers MaxNewTokens, and MinNewTokens with it, to fit the context, as SGLang's scheduler does.

func DefaultSampling

func DefaultSampling() Sampling

DefaultSampling returns the values SGLang uses for parameters a request omits.

func (Sampling) Greedy

func (s Sampling) Greedy() bool

Greedy reports whether s always picks the most likely token.

func (Sampling) Validate

func (s Sampling) Validate() error

Validate reports whether s is within the ranges SGLang accepts.

type Server

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

Server provides an HTTP handler for OpenAI-compatible LLM inference.

func New

func New(engine Engine, modelName string) *Server

New creates a new inference server wrapping engine.

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler returns the http.Handler serving API routes. Chat completion requests must contain one JSON value in at most 1 MiB.

func (*Server) HandlerWithDebug

func (s *Server) HandlerWithDebug(routes DebugRoutes) (http.Handler, error)

HandlerWithDebug serves the usual inference routes and the configured debug routes. Authorize wraps /debug/gpuvis and /debug/hotswap. The existing /debug/trace.pftrace route keeps its original behavior, so deployments that expose it must retain their existing authorization boundary. The hot-swap handler receives requests with /debug/hotswap stripped.

func (*Server) SetDebugHandlers

func (s *Server) SetDebugHandlers(h DebugHandlers)

SetDebugHandlers configures debug routes before Handler builds the mux.

Example
package main

import (
	"context"
	"fmt"
	"net/http/httptest"

	"github.com/tmc/lib/nvidia/x/nn/serve"
	"github.com/tmc/lib/nvidia/x/obs/iket"
)

func main() {
	s := serve.New(nil, "example")
	s.SetDebugHandlers(serve.DebugHandlers{
		GPUVis: func(context.Context) (*serve.DebugSnapshot, error) {
			return &serve.DebugSnapshot{Timeline: &iket.GPUVisTimeline{}}, nil
		},
	})
	w := httptest.NewRecorder()
	s.Handler().ServeHTTP(w, httptest.NewRequest("GET", "/debug/gpuvis", nil))
	fmt.Println(w.Code)
}
Output:
200

func (*Server) SetFlightRecorder

func (s *Server) SetFlightRecorder(fr *cudaprof.FlightRecorder)

SetFlightRecorder configures an in-memory GPU flight recorder for live trace export.

type StreamChoice

type StreamChoice struct {
	Index        int         `json:"index"`
	Delta        StreamDelta `json:"delta"`
	FinishReason *string     `json:"finish_reason"`
}

StreamChoice represents a choice in an SSE chunk.

type StreamDelta

type StreamDelta struct {
	Role    string `json:"role,omitempty"`
	Content string `json:"content,omitempty"`
}

StreamDelta represents the incremental content in an SSE chunk.

type Tokenizer

type Tokenizer interface {
	Encode(text string) ([]int32, error)
	Decode(tokens []int32) (string, error)
}

Tokenizer encodes text strings into token IDs and decodes token IDs into text.

type UsageEngine

type UsageEngine interface {
	Engine
	GenerateWithUsage(context.Context, ChatCompletionRequest, chan<- string) (UsageStats, error)
}

UsageEngine reports the engine's actual tokenizer counts for the rendered prompt and completed output. The server validates arithmetic, not the engine tokenizer implementation. Without it, responses omit usage; token stream chunks are not tokenizer tokens. GenerateWithUsage must obey Engine's rules.

Example
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"

	nnserve "github.com/tmc/lib/nvidia/x/nn/serve"
)

type usageEngine struct{ usage nnserve.UsageStats }

func (e usageEngine) Generate(context.Context, nnserve.ChatCompletionRequest, chan<- string) error {
	panic("usage engine must use GenerateWithUsage")
}
func (e usageEngine) GenerateWithUsage(_ context.Context, _ nnserve.ChatCompletionRequest, ch chan<- string) (nnserve.UsageStats, error) {
	ch <- "many words in one chunk"
	ch <- ""
	return e.usage, nil
}

func main() {
	server := nnserve.New(usageEngine{nnserve.UsageStats{PromptTokens: 14, CompletionTokens: 7, TotalTokens: 21}}, "test")
	response := httptest.NewRecorder()
	server.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(`{}`)))
	var completion nnserve.ChatCompletionResponse
	_ = json.Unmarshal(response.Body.Bytes(), &completion)
	fmt.Println(completion.Usage.TotalTokens)
}
Output:
21

type UsageStats

type UsageStats struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
	TotalTokens      int `json:"total_tokens"`
}

UsageStats records actual engine tokenizer counts for a completion. TotalTokens must equal PromptTokens plus CompletionTokens.

Directories

Path Synopsis
Package cert records what has been checked about a serving image and checks the record against what is loaded.
Package cert records what has been checked about a serving image and checks the record against what is loaded.
Package disagg implements single-host disaggregated prefill and decode serving over loopback framed KV transfers.
Package disagg implements single-host disaggregated prefill and decode serving over loopback framed KV transfers.

Jump to

Keyboard shortcuts

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