chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,197 @@
|
||||
package vlm
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"academy/internal/logger"
|
||||
"academy/internal/models/utils"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const academyCloudVLMPath = "/api/v1/chat/completions"
|
||||
|
||||
// AcademyCloudVLM implements VLM via the AcademyCloud API.
|
||||
type AcademyCloudVLM struct {
|
||||
modelName string
|
||||
remoteModelName string
|
||||
modelID string
|
||||
appID string
|
||||
apiKey string
|
||||
baseURL string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
// NewAcademyCloudVLM creates a AcademyCloud-backed VLM instance.
|
||||
func NewAcademyCloudVLM(config *Config) (*AcademyCloudVLM, error) {
|
||||
if config.AppID == "" {
|
||||
return nil, fmt.Errorf("AcademyCloud VLM: AppID is required")
|
||||
}
|
||||
if config.AppSecret == "" {
|
||||
return nil, fmt.Errorf("AcademyCloud VLM: AppSecret is required")
|
||||
}
|
||||
baseURL := strings.TrimRight(config.BaseURL, "/")
|
||||
if err := validateVLMBaseURL(baseURL); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
remoteModelName := ""
|
||||
if config.Extra != nil {
|
||||
if v, ok := config.Extra["remote_model_name"]; ok {
|
||||
if vs, ok := v.(string); ok {
|
||||
remoteModelName = strings.TrimSpace(vs)
|
||||
}
|
||||
}
|
||||
}
|
||||
return &AcademyCloudVLM{
|
||||
modelName: config.ModelName,
|
||||
remoteModelName: remoteModelName,
|
||||
modelID: config.ModelID,
|
||||
appID: config.AppID,
|
||||
apiKey: config.AppSecret,
|
||||
baseURL: baseURL,
|
||||
client: newVLMHTTPClient(vlmHTTPTimeout()),
|
||||
}, nil
|
||||
}
|
||||
|
||||
type academyCloudVLMContentPart struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text,omitempty"`
|
||||
ImageURL *academyCloudVLMImageURL `json:"image_url,omitempty"`
|
||||
}
|
||||
|
||||
type academyCloudVLMImageURL struct {
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
type academyCloudVLMMessage struct {
|
||||
Role string `json:"role"`
|
||||
Content interface{} `json:"content"`
|
||||
}
|
||||
|
||||
type academyCloudVLMRequest struct {
|
||||
Model string `json:"model"`
|
||||
Messages []academyCloudVLMMessage `json:"messages"`
|
||||
MaxTokens int `json:"max_tokens,omitempty"`
|
||||
Temperature float64 `json:"temperature,omitempty"`
|
||||
Stream bool `json:"stream"`
|
||||
}
|
||||
|
||||
type academyCloudVLMResponse struct {
|
||||
Choices []struct {
|
||||
Message struct {
|
||||
Content string `json:"content"`
|
||||
} `json:"message"`
|
||||
} `json:"choices"`
|
||||
}
|
||||
|
||||
// Predict sends images with a text prompt to the AcademyCloud API.
|
||||
func (v *AcademyCloudVLM) Predict(ctx context.Context, imgBytesList [][]byte, prompt string) (string, error) {
|
||||
return v.PredictWithOptions(ctx, imgBytesList, prompt, nil)
|
||||
}
|
||||
|
||||
// PredictWithOptions satisfies the interface. The hosted endpoint exposes no
|
||||
// thinking switch, so the options are accepted and used for nothing — the same
|
||||
// call goes out as Predict sends.
|
||||
func (v *AcademyCloudVLM) PredictWithOptions(
|
||||
ctx context.Context, imgBytesList [][]byte, prompt string, _ *PredictOptions,
|
||||
) (string, error) {
|
||||
var parts []academyCloudVLMContentPart
|
||||
|
||||
parts = append(parts, academyCloudVLMContentPart{
|
||||
Type: "text",
|
||||
Text: prompt,
|
||||
})
|
||||
|
||||
for _, imgBytes := range imgBytesList {
|
||||
if len(imgBytes) > 0 {
|
||||
mimeType := detectImageMIME(imgBytes)
|
||||
b64 := base64.StdEncoding.EncodeToString(imgBytes)
|
||||
dataURI := fmt.Sprintf("data:%s;base64,%s", mimeType, b64)
|
||||
parts = append(parts, academyCloudVLMContentPart{
|
||||
Type: "image_url",
|
||||
ImageURL: &academyCloudVLMImageURL{
|
||||
URL: dataURI,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
reqBody := academyCloudVLMRequest{
|
||||
Model: v.effectiveModelName(),
|
||||
Messages: []academyCloudVLMMessage{
|
||||
{
|
||||
Role: "user",
|
||||
Content: parts,
|
||||
},
|
||||
},
|
||||
MaxTokens: defaultMaxToks,
|
||||
Temperature: float64(defaultTemp),
|
||||
Stream: false,
|
||||
}
|
||||
|
||||
bodyBytes, err := json.Marshal(reqBody)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("academycloud VLM: marshal: %w", err)
|
||||
}
|
||||
|
||||
requestID := uuid.New().String()
|
||||
headers := utils.Sign(v.appID, v.apiKey, requestID, string(bodyBytes))
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, v.baseURL+academyCloudVLMPath, bytes.NewReader(bodyBytes))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("academycloud VLM: create request: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
for k, hv := range headers {
|
||||
req.Header.Set(k, hv)
|
||||
}
|
||||
|
||||
totalImageSize := 0
|
||||
for _, img := range imgBytesList {
|
||||
totalImageSize += len(img)
|
||||
}
|
||||
logger.Infof(ctx, "[VLM] Calling AcademyCloud API, model=%s, baseURL=%s, numImages=%d, totalImageSize=%d",
|
||||
v.effectiveModelName(), v.baseURL, len(imgBytesList), totalImageSize)
|
||||
|
||||
resp, err := v.client.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("academycloud VLM: do request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBytes, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("academycloud VLM: read response: %w", err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("academycloud VLM: status %d: %s", resp.StatusCode, string(respBytes))
|
||||
}
|
||||
|
||||
var vlmResp academyCloudVLMResponse
|
||||
if err := json.Unmarshal(respBytes, &vlmResp); err != nil {
|
||||
return "", fmt.Errorf("academycloud VLM: unmarshal: %w", err)
|
||||
}
|
||||
if len(vlmResp.Choices) == 0 {
|
||||
return "", fmt.Errorf("academycloud VLM: no choices in response")
|
||||
}
|
||||
|
||||
content := vlmResp.Choices[0].Message.Content
|
||||
logger.Infof(ctx, "[VLM] AcademyCloud response received, len=%d", len(content))
|
||||
return content, nil
|
||||
}
|
||||
|
||||
func (v *AcademyCloudVLM) effectiveModelName() string {
|
||||
if v.remoteModelName != "" {
|
||||
return v.remoteModelName
|
||||
}
|
||||
return v.modelName
|
||||
}
|
||||
|
||||
func (v *AcademyCloudVLM) GetModelName() string { return v.modelName }
|
||||
func (v *AcademyCloudVLM) GetModelID() string { return v.modelID }
|
||||
@@ -0,0 +1,47 @@
|
||||
package vlm
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"academy/internal/models/limiter"
|
||||
)
|
||||
|
||||
// Multimodal enrichment (image OCR / caption) is a high-volume, slow background
|
||||
// stage that hits the same provider budget as chat. Like chat, it must be
|
||||
// governed at the client layer so an image-heavy ingestion storm can't burst
|
||||
// the whole worker pool against one VLM provider. Only background (asynq
|
||||
// worker) calls are throttled — see limiter.Gate / types.IsBackgroundTask.
|
||||
type concurrencyVLM struct {
|
||||
inner VLM
|
||||
// limit is this model's configured per-model background cap; 0 falls back
|
||||
// to the process-wide default (see limiter.GateN).
|
||||
limit int
|
||||
}
|
||||
|
||||
func (w *concurrencyVLM) GetModelName() string { return w.inner.GetModelName() }
|
||||
func (w *concurrencyVLM) GetModelID() string { return w.inner.GetModelID() }
|
||||
|
||||
func (w *concurrencyVLM) Predict(ctx context.Context, imgBytes [][]byte, prompt string) (string, error) {
|
||||
return w.PredictWithOptions(ctx, imgBytes, prompt, nil)
|
||||
}
|
||||
|
||||
// PredictWithOptions holds the same concurrency slot around the per-call
|
||||
// variant, so a tuned request (e.g. an explicit thinking switch) is governed
|
||||
// exactly like a plain one.
|
||||
func (w *concurrencyVLM) PredictWithOptions(
|
||||
ctx context.Context, imgBytes [][]byte, prompt string, opts *PredictOptions,
|
||||
) (string, error) {
|
||||
release := limiter.GateNamedN(ctx, w.inner.GetModelID(), w.inner.GetModelName(), w.limit)
|
||||
defer release()
|
||||
return w.inner.PredictWithOptions(ctx, imgBytes, prompt, opts)
|
||||
}
|
||||
|
||||
// wrapVLMConcurrency installs the background concurrency governor as the
|
||||
// outermost VLM decorator. Always applied; a cheap passthrough when no limiter
|
||||
// is installed or the call is interactive.
|
||||
func wrapVLMConcurrency(v VLM, limit int, err error) (VLM, error) {
|
||||
if err != nil || v == nil {
|
||||
return v, err
|
||||
}
|
||||
return &concurrencyVLM{inner: v, limit: limit}, nil
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package vlm
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
func TestConfigFromModel_RemoteDefaultsToOpenAI(t *testing.T) {
|
||||
m := &types.Model{
|
||||
ID: "v1",
|
||||
Name: "gpt-4o",
|
||||
Source: types.ModelSourceRemote,
|
||||
Parameters: types.ModelParameters{
|
||||
BaseURL: "https://api.example.com/v1",
|
||||
APIKey: "sk",
|
||||
Provider: "openai",
|
||||
ExtraConfig: map[string]string{"x": "y"},
|
||||
CustomHeaders: map[string]string{"H": "v"},
|
||||
},
|
||||
}
|
||||
cfg := ConfigFromModel(m, "app", "secret")
|
||||
if cfg.InterfaceType != "openai" {
|
||||
t.Errorf("expected openai default for remote, got %q", cfg.InterfaceType)
|
||||
}
|
||||
if cfg.CustomHeaders["H"] != "v" {
|
||||
t.Errorf("CustomHeaders not propagated: %+v", cfg.CustomHeaders)
|
||||
}
|
||||
if cfg.Extra["x"] != "y" {
|
||||
t.Errorf("ExtraConfig not propagated as Extra: %+v", cfg.Extra)
|
||||
}
|
||||
if cfg.AppID != "app" || cfg.AppSecret != "secret" {
|
||||
t.Errorf("cloud creds mismatch: %+v", cfg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigFromModel_LocalDefaultsToOllama(t *testing.T) {
|
||||
m := &types.Model{
|
||||
Name: "qwen2-vl",
|
||||
Source: types.ModelSourceLocal,
|
||||
}
|
||||
cfg := ConfigFromModel(m, "", "")
|
||||
if cfg.InterfaceType != "ollama" {
|
||||
t.Errorf("expected ollama default for local, got %q", cfg.InterfaceType)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigFromModel_RespectsExplicitInterface(t *testing.T) {
|
||||
m := &types.Model{
|
||||
Name: "qwen2-vl",
|
||||
Source: types.ModelSourceRemote,
|
||||
Parameters: types.ModelParameters{
|
||||
InterfaceType: "ollama",
|
||||
},
|
||||
}
|
||||
if got := ConfigFromModel(m, "", "").InterfaceType; got != "ollama" {
|
||||
t.Errorf("expected explicit interface to win, got %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package vlm
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"academy/internal/tracing/langfuse"
|
||||
)
|
||||
|
||||
// langfuseVLM wraps a VLM and reports each Predict call as a Langfuse
|
||||
// generation. The raw image bytes are NOT uploaded — Langfuse traces are
|
||||
// designed for text. We include image count and total byte size in the
|
||||
// metadata, plus the text prompt, which matches how Langfuse's own VLM
|
||||
// integrations report multimodal calls.
|
||||
type langfuseVLM struct {
|
||||
inner VLM
|
||||
}
|
||||
|
||||
func (l *langfuseVLM) GetModelName() string { return l.inner.GetModelName() }
|
||||
func (l *langfuseVLM) GetModelID() string { return l.inner.GetModelID() }
|
||||
|
||||
func (l *langfuseVLM) Predict(ctx context.Context, imgBytes [][]byte, prompt string) (string, error) {
|
||||
return l.PredictWithOptions(ctx, imgBytes, prompt, nil)
|
||||
}
|
||||
|
||||
func (l *langfuseVLM) PredictWithOptions(
|
||||
ctx context.Context, imgBytes [][]byte, prompt string, opts *PredictOptions,
|
||||
) (string, error) {
|
||||
mgr := langfuse.GetManager()
|
||||
if !mgr.Enabled() {
|
||||
return l.inner.PredictWithOptions(ctx, imgBytes, prompt, opts)
|
||||
}
|
||||
|
||||
totalImgSize := 0
|
||||
for _, b := range imgBytes {
|
||||
totalImgSize += len(b)
|
||||
}
|
||||
|
||||
genCtx, gen := mgr.StartGeneration(ctx, langfuse.GenerationOptions{
|
||||
Name: "vlm.predict",
|
||||
Model: l.inner.GetModelName(),
|
||||
Input: map[string]interface{}{
|
||||
"prompt": prompt,
|
||||
"image_count": len(imgBytes),
|
||||
},
|
||||
Metadata: map[string]interface{}{
|
||||
"model_id": l.inner.GetModelID(),
|
||||
"image_count": len(imgBytes),
|
||||
"image_bytes_total": totalImgSize,
|
||||
},
|
||||
})
|
||||
|
||||
result, err := l.inner.PredictWithOptions(genCtx, imgBytes, prompt, opts)
|
||||
|
||||
// VLMs don't return token usage; approximate prompt tokens for cost
|
||||
// tracking in Langfuse (users can configure per-model pricing in the UI).
|
||||
promptTokens := len([]rune(prompt))/4 + 1
|
||||
outputTokens := len([]rune(result)) / 4
|
||||
usage := &langfuse.TokenUsage{
|
||||
Input: promptTokens,
|
||||
Output: outputTokens,
|
||||
Total: promptTokens + outputTokens,
|
||||
Unit: "TOKENS",
|
||||
}
|
||||
|
||||
gen.Finish(result, usage, err)
|
||||
return result, err
|
||||
}
|
||||
|
||||
// wrapVLMLangfuse applies the Langfuse decorator when the manager is enabled.
|
||||
func wrapVLMLangfuse(v VLM, err error) (VLM, error) {
|
||||
if err != nil || v == nil {
|
||||
return v, err
|
||||
}
|
||||
if !langfuse.GetManager().Enabled() {
|
||||
return v, nil
|
||||
}
|
||||
return &langfuseVLM{inner: v}, nil
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package vlm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"academy/internal/tracing/langfuse"
|
||||
"github.com/stretchr/testify/require"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
"go.opentelemetry.io/otel/sdk/trace/tracetest"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
type tracingTestVLM struct {
|
||||
spanID trace.SpanID
|
||||
opts *PredictOptions
|
||||
err error
|
||||
}
|
||||
|
||||
func (m *tracingTestVLM) GetModelName() string { return "test-model" }
|
||||
func (m *tracingTestVLM) GetModelID() string { return "test-id" }
|
||||
func (m *tracingTestVLM) Predict(ctx context.Context, images [][]byte, prompt string) (string, error) {
|
||||
return m.PredictWithOptions(ctx, images, prompt, nil)
|
||||
}
|
||||
|
||||
func (m *tracingTestVLM) PredictWithOptions(
|
||||
ctx context.Context, _ [][]byte, _ string, opts *PredictOptions,
|
||||
) (string, error) {
|
||||
m.spanID = trace.SpanContextFromContext(ctx).SpanID()
|
||||
m.opts = opts
|
||||
return "caption text", m.err
|
||||
}
|
||||
|
||||
func TestVLMLangfuseRecordsBothPredictionMethods(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer server.Close()
|
||||
manager, err := langfuse.Init(langfuse.Config{
|
||||
Enabled: true, Host: server.URL, PublicKey: "test", SecretKey: "test",
|
||||
SampleRate: 1, FlushAt: 10, QueueSize: 100, FlushInterval: time.Hour, RequestTimeout: time.Second,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
defer func() {
|
||||
require.NoError(t, manager.Shutdown(context.Background()))
|
||||
_, err := langfuse.Init(langfuse.Config{})
|
||||
require.NoError(t, err)
|
||||
}()
|
||||
_, parent := manager.Tracer().Start(context.Background(), "fixture")
|
||||
provider := parent.TracerProvider().(*sdktrace.TracerProvider)
|
||||
recorder := tracetest.NewSpanRecorder()
|
||||
provider.RegisterSpanProcessor(recorder)
|
||||
parent.End()
|
||||
|
||||
on := true
|
||||
for _, opts := range []*PredictOptions{nil, {Thinking: &on}} {
|
||||
for _, failure := range []error{nil, errors.New("model unavailable")} {
|
||||
inner := &tracingTestVLM{err: failure}
|
||||
wrapped, err := wrapVLMLangfuse(inner, nil)
|
||||
require.NoError(t, err)
|
||||
wrapped, err = wrapVLMConcurrency(wrapped, 0, nil)
|
||||
require.NoError(t, err)
|
||||
var result string
|
||||
if opts == nil {
|
||||
result, err = wrapped.Predict(context.Background(), nil, "describe this image")
|
||||
} else {
|
||||
result, err = wrapped.PredictWithOptions(context.Background(), nil, "describe this image", opts)
|
||||
}
|
||||
require.Equal(t, failure, err)
|
||||
require.Equal(t, "caption text", result)
|
||||
require.Same(t, opts, inner.opts)
|
||||
require.True(t, inner.spanID.IsValid(), "the model call must receive the generation context")
|
||||
var generation sdktrace.ReadOnlySpan
|
||||
for _, span := range recorder.Ended() {
|
||||
if span.SpanContext().SpanID() == inner.spanID {
|
||||
generation = span
|
||||
}
|
||||
}
|
||||
require.NotNil(t, generation, "the generation must end on both success and error")
|
||||
require.Equal(t, "vlm.predict", generation.Name())
|
||||
attrs := map[string]string{}
|
||||
for _, attr := range generation.Attributes() {
|
||||
attrs[string(attr.Key)] = attr.Value.AsString()
|
||||
}
|
||||
require.Equal(t, "generation", attrs["langfuse.observation.type"])
|
||||
require.Contains(t, attrs["langfuse.observation.usage_details"], "input")
|
||||
if failure != nil {
|
||||
require.Equal(t, codes.Error, generation.Status().Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package vlm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"academy/internal/logger"
|
||||
)
|
||||
|
||||
// debugVLM wraps a VLM with LLM debug logging.
|
||||
type debugVLM struct {
|
||||
inner VLM
|
||||
}
|
||||
|
||||
func (d *debugVLM) Predict(ctx context.Context, imgBytes [][]byte, prompt string) (string, error) {
|
||||
return d.call(ctx, imgBytes, prompt, nil)
|
||||
}
|
||||
|
||||
func (d *debugVLM) PredictWithOptions(
|
||||
ctx context.Context, imgBytes [][]byte, prompt string, opts *PredictOptions,
|
||||
) (string, error) {
|
||||
return d.call(ctx, imgBytes, prompt, opts)
|
||||
}
|
||||
|
||||
func (d *debugVLM) call(
|
||||
ctx context.Context, imgBytes [][]byte, prompt string, opts *PredictOptions,
|
||||
) (string, error) {
|
||||
start := time.Now()
|
||||
result, err := d.inner.PredictWithOptions(ctx, imgBytes, prompt, opts)
|
||||
logVLMDebug(ctx, d.inner.GetModelName(), imgBytes, prompt, result, err, time.Since(start))
|
||||
return result, err
|
||||
}
|
||||
|
||||
func (d *debugVLM) GetModelName() string { return d.inner.GetModelName() }
|
||||
func (d *debugVLM) GetModelID() string { return d.inner.GetModelID() }
|
||||
|
||||
func logVLMDebug(ctx context.Context, model string, imgBytes [][]byte, prompt string, response string, callErr error, dur time.Duration) {
|
||||
if !logger.LLMDebugEnabled() {
|
||||
return
|
||||
}
|
||||
|
||||
record := &logger.LLMCallRecord{
|
||||
CallType: "VLM",
|
||||
Model: model,
|
||||
Duration: dur,
|
||||
}
|
||||
|
||||
// Input section
|
||||
var inputBuf strings.Builder
|
||||
inputBuf.WriteString(fmt.Sprintf("Images: count=%d", len(imgBytes)))
|
||||
totalSize := 0
|
||||
for _, img := range imgBytes {
|
||||
totalSize += len(img)
|
||||
}
|
||||
inputBuf.WriteString(fmt.Sprintf(", total_size=%d bytes\n\n", totalSize))
|
||||
inputBuf.WriteString("[prompt]\n")
|
||||
inputBuf.WriteString(prompt)
|
||||
inputBuf.WriteString("\n")
|
||||
record.Sections = append(record.Sections, logger.RecordSection{Title: "Input", Content: inputBuf.String()})
|
||||
|
||||
// Response section
|
||||
if response != "" {
|
||||
record.Sections = append(record.Sections, logger.RecordSection{
|
||||
Title: "Response",
|
||||
Content: response,
|
||||
})
|
||||
}
|
||||
|
||||
if callErr != nil {
|
||||
record.Error = callErr.Error()
|
||||
}
|
||||
logger.LLMDebugLog(ctx, record)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package vlm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"academy/internal/logger"
|
||||
"academy/internal/models/utils/ollama"
|
||||
ollamaapi "github.com/ollama/ollama/api"
|
||||
)
|
||||
|
||||
// OllamaVLM implements VLM via the local Ollama service.
|
||||
type OllamaVLM struct {
|
||||
modelName string
|
||||
modelID string
|
||||
ollamaService *ollama.OllamaService
|
||||
}
|
||||
|
||||
// NewOllamaVLM creates an Ollama-backed VLM instance.
|
||||
func NewOllamaVLM(config *Config, ollamaService *ollama.OllamaService) (*OllamaVLM, error) {
|
||||
if ollamaService == nil {
|
||||
return nil, fmt.Errorf("ollama service is required for local VLM model")
|
||||
}
|
||||
return &OllamaVLM{
|
||||
modelName: config.ModelName,
|
||||
modelID: config.ModelID,
|
||||
ollamaService: ollamaService,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Predict sends an image with a text prompt to the Ollama vision model.
|
||||
func (v *OllamaVLM) Predict(ctx context.Context, imgBytesList [][]byte, prompt string) (string, error) {
|
||||
return v.PredictWithOptions(ctx, imgBytesList, prompt, nil)
|
||||
}
|
||||
|
||||
// PredictWithOptions carries the thinking preference in Ollama's top-level
|
||||
// Think field; sampling parameters remain in Options.
|
||||
func (v *OllamaVLM) PredictWithOptions(
|
||||
ctx context.Context, imgBytesList [][]byte, prompt string, opts *PredictOptions,
|
||||
) (string, error) {
|
||||
streamFlag := false
|
||||
var images []ollamaapi.ImageData
|
||||
for _, imgBytes := range imgBytesList {
|
||||
if len(imgBytes) > 0 {
|
||||
images = append(images, imgBytes)
|
||||
}
|
||||
}
|
||||
|
||||
chatReq := &ollamaapi.ChatRequest{
|
||||
Model: v.modelName,
|
||||
Messages: []ollamaapi.Message{
|
||||
{
|
||||
Role: "user",
|
||||
Content: prompt,
|
||||
Images: images,
|
||||
},
|
||||
},
|
||||
Stream: &streamFlag,
|
||||
Options: map[string]interface{}{"temperature": 0.1},
|
||||
}
|
||||
if opts != nil && opts.Thinking != nil {
|
||||
chatReq.Think = &ollamaapi.ThinkValue{Value: *opts.Thinking}
|
||||
}
|
||||
|
||||
totalImageSize := 0
|
||||
for _, img := range imgBytesList {
|
||||
totalImageSize += len(img)
|
||||
}
|
||||
logger.Infof(ctx, "[VLM] Calling Ollama API, model=%s, numImages=%d, totalImageSize=%d", v.modelName, len(images), totalImageSize)
|
||||
|
||||
var result string
|
||||
err := v.ollamaService.Chat(ctx, chatReq, func(resp ollamaapi.ChatResponse) error {
|
||||
result = resp.Message.Content
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("Ollama VLM request: %w", err)
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[VLM] Ollama response received, len=%d", len(result))
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (v *OllamaVLM) GetModelName() string { return v.modelName }
|
||||
func (v *OllamaVLM) GetModelID() string { return v.modelID }
|
||||
@@ -0,0 +1,66 @@
|
||||
package vlm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"academy/internal/models/utils/ollama"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestOllamaPredictThinkingRequest(t *testing.T) {
|
||||
on, off := true, false
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
opts *PredictOptions
|
||||
want *bool
|
||||
}{
|
||||
{"legacy", nil, nil},
|
||||
{"unset", &PredictOptions{}, nil},
|
||||
{"enabled", &PredictOptions{Thinking: &on}, &on},
|
||||
{"disabled", &PredictOptions{Thinking: &off}, &off},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
requests := make(chan map[string]any, 1)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodHead {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
var body map[string]any
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
requests <- body
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"message":{"role":"assistant","content":"caption"},"done":true}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
t.Setenv("OLLAMA_BASE_URL", server.URL)
|
||||
service, err := ollama.GetOllamaService()
|
||||
require.NoError(t, err)
|
||||
model, err := NewOllamaVLM(&Config{ModelName: "test"}, service)
|
||||
require.NoError(t, err)
|
||||
var result string
|
||||
if tc.opts == nil {
|
||||
result, err = model.Predict(context.Background(), nil, "describe")
|
||||
} else {
|
||||
result, err = model.PredictWithOptions(context.Background(), nil, "describe", tc.opts)
|
||||
}
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "caption", result)
|
||||
body := <-requests
|
||||
if tc.want == nil {
|
||||
require.NotContains(t, body, "think")
|
||||
} else {
|
||||
require.Equal(t, *tc.want, body["think"])
|
||||
}
|
||||
options := body["options"].(map[string]any)
|
||||
require.NotContains(t, options, "think")
|
||||
require.Equal(t, 0.1, options["temperature"])
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package vlm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"academy/internal/logger"
|
||||
"academy/internal/models/chat"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
const (
|
||||
// defaultTimeout is the fallback HTTP timeout for a single VLM request.
|
||||
// Dense scanned-PDF OCR (full-page text + layout extraction) can take well
|
||||
// over a minute on slow endpoints, so this is intentionally generous and
|
||||
// can be raised further via VLM_HTTP_TIMEOUT_SECONDS.
|
||||
defaultTimeout = 180 * time.Second
|
||||
defaultMaxToks = 5000
|
||||
defaultTemp = float32(0.1)
|
||||
)
|
||||
|
||||
// vlmHTTPTimeout returns the HTTP client timeout for VLM requests, read from
|
||||
// the VLM_HTTP_TIMEOUT_SECONDS env var when set (and positive), falling back to
|
||||
// defaultTimeout otherwise. Shared by all OpenAI-compatible VLM backends.
|
||||
func vlmHTTPTimeout() time.Duration {
|
||||
if v := strings.TrimSpace(os.Getenv("VLM_HTTP_TIMEOUT_SECONDS")); v != "" {
|
||||
if secs, err := strconv.Atoi(v); err == nil && secs > 0 {
|
||||
return time.Duration(secs) * time.Second
|
||||
}
|
||||
}
|
||||
return defaultTimeout
|
||||
}
|
||||
|
||||
// RemoteAPIVLM implements VLM on top of the catalog-driven chat client: a
|
||||
// vision call is a chat call whose user turn carries images, so the vendor
|
||||
// dialect (max_tokens field, sampling restrictions, protocol) is resolved
|
||||
// exactly like it is for chat models.
|
||||
type RemoteAPIVLM struct {
|
||||
modelName string
|
||||
modelID string
|
||||
chat chat.Chat
|
||||
temperature float64
|
||||
}
|
||||
|
||||
// NewRemoteAPIVLM creates a remote-API backed VLM instance.
|
||||
func NewRemoteAPIVLM(config *Config) (*RemoteAPIVLM, error) {
|
||||
if err := validateVLMBaseURL(config.BaseURL); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
temp := float64(defaultTemp)
|
||||
extra := make(map[string]string, len(config.Extra))
|
||||
for k, v := range config.Extra {
|
||||
if s, ok := v.(string); ok {
|
||||
extra[k] = s
|
||||
}
|
||||
}
|
||||
if raw, ok := extra["temperature"]; ok {
|
||||
if f, err := strconv.ParseFloat(raw, 64); err == nil {
|
||||
temp = f
|
||||
}
|
||||
}
|
||||
|
||||
client, err := chat.NewRemoteChat(&chat.ChatConfig{
|
||||
Source: types.ModelSourceRemote,
|
||||
BaseURL: config.BaseURL,
|
||||
ModelName: config.ModelName,
|
||||
APIKey: config.APIKey,
|
||||
ModelID: config.ModelID,
|
||||
Provider: config.Provider,
|
||||
ExtraConfig: extra,
|
||||
CustomHeaders: config.CustomHeaders,
|
||||
AppID: config.AppID,
|
||||
AppSecret: config.AppSecret,
|
||||
Spec: config.Spec,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &RemoteAPIVLM{
|
||||
modelName: config.ModelName,
|
||||
modelID: config.ModelID,
|
||||
chat: client,
|
||||
temperature: temp,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Predict sends images with a text prompt through the chat client.
|
||||
func (v *RemoteAPIVLM) Predict(ctx context.Context, imgBytesList [][]byte, prompt string) (string, error) {
|
||||
return v.PredictWithOptions(ctx, imgBytesList, prompt, nil)
|
||||
}
|
||||
|
||||
// PredictWithOptions sends the same request, carrying a per-call thinking
|
||||
// switch into the chat client. The switch rides on Options.Thinking, which the
|
||||
// protocol layer turns into whatever key this vendor uses, so a model that only
|
||||
// understands chat_template_kwargs still gets that spelling rather than a
|
||||
// bare enable_thinking the server would ignore.
|
||||
func (v *RemoteAPIVLM) PredictWithOptions(
|
||||
ctx context.Context, imgBytesList [][]byte, prompt string, opts *PredictOptions,
|
||||
) (string, error) {
|
||||
parts := []chat.MessageContentPart{{Type: "text", Text: prompt}}
|
||||
totalImageSize := 0
|
||||
for _, imgBytes := range imgBytesList {
|
||||
if len(imgBytes) == 0 {
|
||||
continue
|
||||
}
|
||||
totalImageSize += len(imgBytes)
|
||||
dataURI := fmt.Sprintf("data:%s;base64,%s",
|
||||
detectImageMIME(imgBytes), base64.StdEncoding.EncodeToString(imgBytes))
|
||||
parts = append(parts, chat.MessageContentPart{
|
||||
Type: "image_url", ImageURL: &chat.ImageURL{URL: dataURI, Detail: "auto"},
|
||||
})
|
||||
}
|
||||
logger.Infof(ctx, "[VLM] Calling chat protocol, model=%s, numImages=%d, totalImageSize=%d",
|
||||
v.modelName, len(imgBytesList), totalImageSize)
|
||||
|
||||
chatOpts := &chat.ChatOptions{
|
||||
Temperature: v.temperature,
|
||||
MaxTokens: defaultMaxToks,
|
||||
}
|
||||
// Only an explicit preference is forwarded. The protocol layer skips the
|
||||
// thinking fields entirely when nobody asked for a level, which is what
|
||||
// leaves an always-on reasoning model running as its vendor intends.
|
||||
if opts != nil && opts.Thinking != nil {
|
||||
chatOpts.Thinking = opts.Thinking
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(ctx, vlmHTTPTimeout())
|
||||
defer cancel()
|
||||
resp, err := v.chat.Chat(ctx, []chat.Message{{Role: "user", MultiContent: parts}}, chatOpts)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("VLM request: %w", err)
|
||||
}
|
||||
content := resp.Content
|
||||
if resp.FinishReason == "length" {
|
||||
// Non-empty partial output is still incomplete and must not be indexed
|
||||
// as successful OCR. Returning an error also marks the model trace failed.
|
||||
return "", fmt.Errorf("%w at %d tokens (finish_reason=length)", ErrTruncatedCompletion, defaultMaxToks)
|
||||
}
|
||||
logger.Infof(ctx, "[VLM] response received, len=%d", len(content))
|
||||
return content, nil
|
||||
}
|
||||
|
||||
func (v *RemoteAPIVLM) GetModelName() string { return v.modelName }
|
||||
func (v *RemoteAPIVLM) GetModelID() string { return v.modelID }
|
||||
|
||||
// detectImageMIME returns the MIME type for the given image bytes.
|
||||
func detectImageMIME(data []byte) string {
|
||||
ct := http.DetectContentType(data)
|
||||
if strings.HasPrefix(ct, "image/") {
|
||||
return ct
|
||||
}
|
||||
return "image/png"
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package vlm
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// newVLMChatTestServer emulates an OpenAI-compatible chat completions endpoint
|
||||
// and records the last decoded request body.
|
||||
func newVLMChatTestServer(t *testing.T, lastRequest *map[string]interface{}) *httptest.Server {
|
||||
t.Helper()
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var req map[string]interface{}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
t.Errorf("decode VLM request: %v", err)
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
*lastRequest = req
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{
|
||||
"id": "chatcmpl-test",
|
||||
"object": "chat.completion",
|
||||
"choices": [
|
||||
{"index": 0, "message": {"role": "assistant", "content": "extracted text"}, "finish_reason": "stop"}
|
||||
]
|
||||
}`))
|
||||
}))
|
||||
}
|
||||
|
||||
// testPNG is a minimal byte slice that http.DetectContentType reports as a PNG.
|
||||
var testPNG = []byte("\x89PNG\r\n\x1a\n" + strings.Repeat("\x00", 16))
|
||||
|
||||
// TestRemoteAPIVLMSendsMaxCompletionTokensForReasoningModel is the regression
|
||||
// test for issue #2537: GPT-5 / o-series vision models reject max_tokens and
|
||||
// every non-default sampling parameter. The catalog marks those families on
|
||||
// the OpenAI vendor, and the generic vendor carries the same family entries
|
||||
// so relays that forward to OpenAI behave the same way.
|
||||
func TestRemoteAPIVLMSendsMaxCompletionTokensForReasoningModel(t *testing.T) {
|
||||
withVLMSSRFWhitelist(t, "127.0.0.1")
|
||||
|
||||
for _, provider := range []string{"openai", ""} {
|
||||
var lastRequest map[string]interface{}
|
||||
server := newVLMChatTestServer(t, &lastRequest)
|
||||
|
||||
v, err := NewRemoteAPIVLM(&Config{
|
||||
BaseURL: server.URL,
|
||||
ModelName: "gpt-5-nano",
|
||||
APIKey: "sk-test",
|
||||
Provider: provider,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewRemoteAPIVLM: %v", err)
|
||||
}
|
||||
|
||||
content, err := v.Predict(t.Context(), [][]byte{testPNG}, "extract the text")
|
||||
if err != nil {
|
||||
t.Fatalf("Predict (provider=%q): %v", provider, err)
|
||||
}
|
||||
if content != "extracted text" {
|
||||
t.Errorf("content = %q, want %q", content, "extracted text")
|
||||
}
|
||||
if _, ok := lastRequest["max_tokens"]; ok {
|
||||
t.Errorf("provider=%q: request carries max_tokens, which reasoning models reject: %v",
|
||||
provider, lastRequest["max_tokens"])
|
||||
}
|
||||
if got, ok := lastRequest["max_completion_tokens"]; !ok {
|
||||
t.Errorf("provider=%q: request is missing max_completion_tokens", provider)
|
||||
} else if got != float64(defaultMaxToks) {
|
||||
t.Errorf("max_completion_tokens = %v, want %d", got, defaultMaxToks)
|
||||
}
|
||||
if _, ok := lastRequest["temperature"]; ok {
|
||||
t.Errorf("provider=%q: request carries temperature, which reasoning models reject: %v",
|
||||
provider, lastRequest["temperature"])
|
||||
}
|
||||
server.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// TestRemoteAPIVLMKeepsMaxTokensForNonReasoningModel guards against the fix
|
||||
// regressing ordinary vision models on an unknown (generic) endpoint, which
|
||||
// still expect max_tokens.
|
||||
func TestRemoteAPIVLMKeepsMaxTokensForNonReasoningModel(t *testing.T) {
|
||||
withVLMSSRFWhitelist(t, "127.0.0.1")
|
||||
|
||||
var lastRequest map[string]interface{}
|
||||
server := newVLMChatTestServer(t, &lastRequest)
|
||||
defer server.Close()
|
||||
|
||||
v, err := NewRemoteAPIVLM(&Config{
|
||||
BaseURL: server.URL,
|
||||
ModelName: "qwen2.5-vl-7b-instruct",
|
||||
APIKey: "sk-test",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewRemoteAPIVLM: %v", err)
|
||||
}
|
||||
|
||||
if _, err := v.Predict(t.Context(), [][]byte{testPNG}, "extract the text"); err != nil {
|
||||
t.Fatalf("Predict: %v", err)
|
||||
}
|
||||
|
||||
if got, ok := lastRequest["max_tokens"]; !ok {
|
||||
t.Error("request is missing max_tokens")
|
||||
} else if got != float64(defaultMaxToks) {
|
||||
t.Errorf("max_tokens = %v, want %d", got, defaultMaxToks)
|
||||
}
|
||||
if _, ok := lastRequest["max_completion_tokens"]; ok {
|
||||
t.Error("request carries max_completion_tokens for a non-reasoning model")
|
||||
}
|
||||
if got, ok := lastRequest["temperature"]; !ok {
|
||||
t.Error("request is missing temperature")
|
||||
} else if f, isFloat := got.(float64); !isFloat || math.Abs(f-float64(defaultTemp)) > 1e-6 {
|
||||
t.Errorf("temperature = %v, want %v", got, defaultTemp)
|
||||
}
|
||||
messages := lastRequest["messages"].([]interface{})
|
||||
parts := messages[0].(map[string]interface{})["content"].([]interface{})
|
||||
if len(parts) != 2 {
|
||||
t.Fatalf("user content parts = %d, want text + image", len(parts))
|
||||
}
|
||||
image := parts[1].(map[string]interface{})["image_url"].(map[string]interface{})
|
||||
if !strings.HasPrefix(image["url"].(string), "data:image/png;base64,") {
|
||||
t.Errorf("image url = %q, want a PNG data URI", image["url"])
|
||||
}
|
||||
}
|
||||
|
||||
// A completion stopped by the budget is not successful OCR, even when the
|
||||
// response has a non-empty prefix or a long run of repeated empty table cells.
|
||||
func TestRemoteAPIVLMReportsTruncatedCompletion(t *testing.T) {
|
||||
withVLMSSRFWhitelist(t, "127.0.0.1")
|
||||
for _, content := range []string{"", "partial extracted text", strings.Repeat("| ", 2500)} {
|
||||
t.Run(fmt.Sprintf("chars=%d", len(content)), func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"choices": []any{map[string]any{
|
||||
"index": 0, "message": map[string]any{"role": "assistant", "content": content},
|
||||
"finish_reason": "length",
|
||||
}},
|
||||
})
|
||||
}))
|
||||
defer server.Close()
|
||||
v, err := NewRemoteAPIVLM(&Config{BaseURL: server.URL, ModelName: "generic-vision", Provider: "generic"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := v.Predict(t.Context(), [][]byte{testPNG}, "extract text")
|
||||
if got != "" || !errors.Is(err, ErrTruncatedCompletion) {
|
||||
t.Fatalf("content=%q error=%v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package vlm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// TestConfigFromModelCarriesSpecOverride pins the per-row catalog override on
|
||||
// the VLM path. dto.NewModelResponse computes a VLLM row's advertised
|
||||
// capabilities from Parameters.Spec, so dropping the override here made the UI
|
||||
// describe a model the runtime never built: /models reported the pinned
|
||||
// protocol and levels while the request went out with the vendor defaults.
|
||||
func TestConfigFromModelCarriesSpecOverride(t *testing.T) {
|
||||
override := &types.ModelSpecOverride{MaxOutputTokens: 4096}
|
||||
m := &types.Model{
|
||||
ID: "vlm-1",
|
||||
Name: "gpt-4o",
|
||||
Source: types.ModelSourceRemote,
|
||||
Parameters: types.ModelParameters{
|
||||
BaseURL: "https://api.example.com/v1",
|
||||
Provider: "openai",
|
||||
Spec: override,
|
||||
},
|
||||
}
|
||||
cfg := ConfigFromModel(m, "", "")
|
||||
if cfg.Spec != override {
|
||||
t.Fatalf("Spec not propagated: %+v", cfg.Spec)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRemoteAPIVLMAppliesSpecOverride checks the override actually reaches the
|
||||
// wire: pinning max_output_tokens on the row must clamp the VLM's own default
|
||||
// completion budget.
|
||||
func TestRemoteAPIVLMAppliesSpecOverride(t *testing.T) {
|
||||
withVLMSSRFWhitelist(t, "127.0.0.1")
|
||||
|
||||
var lastRequest map[string]interface{}
|
||||
server := newVLMChatTestServer(t, &lastRequest)
|
||||
defer server.Close()
|
||||
|
||||
v, err := NewRemoteAPIVLM(&Config{
|
||||
BaseURL: server.URL,
|
||||
ModelName: "some-unlisted-vision-model",
|
||||
APIKey: "sk-test",
|
||||
Provider: "openai",
|
||||
Spec: &types.ModelSpecOverride{API: "openai-responses"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewRemoteAPIVLM: %v", err)
|
||||
}
|
||||
// The override selects a different protocol, which is only observable
|
||||
// through the request shape the server receives.
|
||||
if _, err := v.Predict(context.Background(), [][]byte{testPNG}, "read this"); err != nil {
|
||||
t.Fatalf("Predict: %v", err)
|
||||
}
|
||||
if _, ok := lastRequest["input"]; !ok {
|
||||
t.Errorf("spec.api override ignored: expected an openai-responses body, got %v keys", lastRequest)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package vlm
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
secutils "academy/internal/utils"
|
||||
)
|
||||
|
||||
func validateVLMBaseURL(baseURL string) error {
|
||||
if baseURL == "" {
|
||||
return nil
|
||||
}
|
||||
if err := secutils.ValidateURLForSSRF(baseURL); err != nil {
|
||||
return fmt.Errorf("base URL SSRF check failed: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func newVLMHTTPClient(timeout time.Duration) *http.Client {
|
||||
cfg := secutils.DefaultSSRFSafeHTTPClientConfig()
|
||||
cfg.Timeout = timeout
|
||||
return secutils.NewSSRFSafeHTTPClient(cfg)
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package vlm
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
secutils "academy/internal/utils"
|
||||
)
|
||||
|
||||
func withVLMSSRFWhitelist(t *testing.T, raw string) {
|
||||
t.Helper()
|
||||
t.Setenv("SSRF_WHITELIST", raw)
|
||||
secutils.ResetSSRFWhitelistForTest()
|
||||
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
|
||||
}
|
||||
|
||||
func TestRemoteAPIVLMRejectsInternalBaseURL(t *testing.T) {
|
||||
withVLMSSRFWhitelist(t, "")
|
||||
|
||||
_, err := NewRemoteAPIVLM(&Config{
|
||||
BaseURL: "http://169.254.169.254/latest/meta-data/",
|
||||
ModelName: "vlm-test",
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatalf("NewRemoteAPIVLM returned nil error for blocked internal BaseURL")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package vlm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"academy/internal/logger"
|
||||
"academy/internal/models/providers"
|
||||
modelruntime "academy/internal/models/runtime"
|
||||
"academy/internal/models/utils/ollama"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// ErrTruncatedCompletion means the model exhausted its output budget
|
||||
// (finish_reason=length). Callers can errors.Is it to tell a truncated answer
|
||||
// apart from a genuinely empty one.
|
||||
var ErrTruncatedCompletion = errors.New("VLM completion truncated")
|
||||
|
||||
// VLM defines the interface for Vision Language Model operations.
|
||||
type VLM interface {
|
||||
// Predict sends one or more images with a text prompt to the VLM and returns the generated text.
|
||||
Predict(ctx context.Context, imgBytes [][]byte, prompt string) (string, error)
|
||||
// PredictWithOptions sends the same request with per-call tunings that the
|
||||
// client-level config cannot express. Implementations must honour it; the
|
||||
// decorators below pass it through untouched.
|
||||
PredictWithOptions(ctx context.Context, imgBytes [][]byte, prompt string, opts *PredictOptions) (string, error)
|
||||
|
||||
GetModelName() string
|
||||
GetModelID() string
|
||||
}
|
||||
|
||||
// PredictOptions tunes a single image request. Every field is optional and nil
|
||||
// means "whatever this client was built with", which is what keeps the model
|
||||
// row, the knowledge base and the per-action switch from overriding each other
|
||||
// by accident: an unset field never writes anything.
|
||||
type PredictOptions struct {
|
||||
// Thinking pins the thinking switch for this call. Leaving a reasoning model
|
||||
// on costs a vision call more than it returns it: the completion budget goes
|
||||
// to reasoning, and at the vision default temperature the answer can come
|
||||
// back empty after the model has already listed the answer in its reasoning.
|
||||
// An OCR caller cannot tell that apart from an image with no text, so the
|
||||
// switch is per-action rather than per-model.
|
||||
Thinking *bool
|
||||
}
|
||||
|
||||
// Config holds the configuration needed to create a VLM instance.
|
||||
type Config struct {
|
||||
Source types.ModelSource
|
||||
BaseURL string
|
||||
ModelName string
|
||||
APIKey string
|
||||
ModelID string
|
||||
InterfaceType string // "ollama" or "openai" (default)
|
||||
Provider string
|
||||
// MaxConcurrency caps concurrent background calls to this model; 0 falls
|
||||
// back to the process-wide default (see limiter.GateN).
|
||||
MaxConcurrency int
|
||||
// Spec carries per-row catalog overrides (protocol, compat, levels). VLM
|
||||
// calls now go through the chat factory, so the override has to travel
|
||||
// with them — otherwise /models reports capabilities computed WITH the
|
||||
// override while the actual request is built without it.
|
||||
Spec *types.ModelSpecOverride
|
||||
Extra map[string]any
|
||||
// CustomHeaders 允许在调用远程 API 时附加自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。
|
||||
CustomHeaders map[string]string
|
||||
AppID string
|
||||
AppSecret string
|
||||
}
|
||||
|
||||
// ConfigFromModel 根据 types.Model 构造 vlm.Config。
|
||||
// 生产路径(从 DB 拉起)和测试连接路径(临时表单)共享这份映射。
|
||||
// appID / appSecret 是已解密的 AcademyCloud 凭证,调用方负责传入。
|
||||
// InterfaceType 会根据 source / 模型参数自动回退到合理默认值。
|
||||
func ConfigFromModel(m *types.Model, appID, appSecret string) *Config {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
ifType := m.Parameters.InterfaceType
|
||||
if ifType == "" {
|
||||
if m.Source == types.ModelSourceLocal {
|
||||
ifType = "ollama"
|
||||
} else {
|
||||
ifType = "openai"
|
||||
}
|
||||
}
|
||||
return &Config{
|
||||
ModelID: m.ID,
|
||||
APIKey: m.Parameters.APIKey,
|
||||
BaseURL: m.Parameters.BaseURL,
|
||||
ModelName: m.Name,
|
||||
Source: m.Source,
|
||||
InterfaceType: ifType,
|
||||
Provider: m.Parameters.Provider,
|
||||
MaxConcurrency: m.Parameters.MaxConcurrency,
|
||||
Spec: m.Parameters.Spec,
|
||||
Extra: stringMapToAnyMap(m.Parameters.ExtraConfig),
|
||||
CustomHeaders: m.Parameters.CustomHeaders,
|
||||
AppID: appID,
|
||||
AppSecret: appSecret,
|
||||
}
|
||||
}
|
||||
|
||||
func stringMapToAnyMap(in map[string]string) map[string]any {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := make(map[string]any, len(in))
|
||||
for k, v := range in {
|
||||
out[k] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// NewVLM creates a VLM instance based on the provided configuration.
|
||||
func NewVLM(config *Config, ollamaService *ollama.OllamaService) (VLM, error) {
|
||||
v, err := newVLM(config, ollamaService)
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
if logger.LLMDebugEnabled() {
|
||||
v = &debugVLM{inner: v}
|
||||
}
|
||||
v, err = wrapVLMLangfuse(v, nil)
|
||||
// Outermost: hold the per-model concurrency slot only around the real
|
||||
// provider round-trip, so the wait is excluded from debug/langfuse timing.
|
||||
return wrapVLMConcurrency(v, config.MaxConcurrency, err)
|
||||
}
|
||||
|
||||
func newVLM(config *Config, ollamaService *ollama.OllamaService) (VLM, error) {
|
||||
ifType := strings.ToLower(config.InterfaceType)
|
||||
|
||||
if ifType == "ollama" || config.Source == types.ModelSourceLocal {
|
||||
return NewOllamaVLM(config, ollamaService)
|
||||
}
|
||||
|
||||
providerID := config.Provider
|
||||
if providerID == "" {
|
||||
providerID = modelruntime.DetectByURL(config.BaseURL)
|
||||
}
|
||||
if providerID == providers.AcademyCloudID {
|
||||
return NewAcademyCloudVLM(config)
|
||||
}
|
||||
|
||||
return NewRemoteAPIVLM(config)
|
||||
}
|
||||
|
||||
// NewVLMFromLegacyConfig creates a VLM from a legacy VLMConfig (inline BaseURL/APIKey/ModelName).
|
||||
func NewVLMFromLegacyConfig(vlmCfg types.VLMConfig, ollamaService *ollama.OllamaService) (VLM, error) {
|
||||
if !vlmCfg.IsEnabled() {
|
||||
return nil, fmt.Errorf("VLM config is not enabled")
|
||||
}
|
||||
|
||||
ifType := vlmCfg.InterfaceType
|
||||
if ifType == "" {
|
||||
ifType = "openai"
|
||||
}
|
||||
|
||||
source := types.ModelSourceRemote
|
||||
if strings.EqualFold(ifType, "ollama") {
|
||||
source = types.ModelSourceLocal
|
||||
}
|
||||
|
||||
return NewVLM(&Config{
|
||||
Source: source,
|
||||
BaseURL: vlmCfg.BaseURL,
|
||||
ModelName: vlmCfg.ModelName,
|
||||
APIKey: vlmCfg.APIKey,
|
||||
InterfaceType: ifType,
|
||||
}, ollamaService)
|
||||
}
|
||||
Reference in new issue
Block a user