chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

+224
View File
@@ -0,0 +1,224 @@
// Package chat exposes the Chat interface used by the application layer and
// builds the right protocol client for a configured model. Every vendor fact
// comes from internal/models/catalog; every wire protocol lives under
// internal/models/api. This package only glues the two together and wraps
// the client with debug / tracing / concurrency decorators.
package chat
import (
"context"
"fmt"
"strings"
"academy/internal/models/api"
"academy/internal/models/api/anthropicmessages"
"academy/internal/models/api/googlegenai"
"academy/internal/models/api/openaicompletions"
"academy/internal/models/api/openairesponses"
modelruntime "academy/internal/models/runtime"
"academy/internal/models/utils/ollama"
"academy/internal/types"
secutils "academy/internal/utils"
)
// Message and the other aliases below re-export the request model defined
// in internal/models/api so historical chat.* names keep working.
//
//nolint:revive // ChatOptions is the historical name every caller uses.
type (
Message = api.Message
MessageContentPart = api.MessageContentPart
ImageURL = api.ImageURL
MessageKind = api.MessageKind
ToolCall = api.ToolCall
FunctionCall = api.FunctionCall
Tool = api.Tool
FunctionDef = api.FunctionDef
ChatOptions = api.Options
CacheRetention = api.CacheRetention
ReasoningEffort = api.ReasoningEffort
)
// Re-exported constants of the request model.
const (
MessageKindCompactionSummary = api.MessageKindCompactionSummary
CacheRetentionNone = api.CacheRetentionNone
CacheRetentionShort = api.CacheRetentionShort
CacheRetentionLong = api.CacheRetentionLong
)
// SanitizeReasoningEffort is re-exported for the callers that build
// ChatOptions from stored strings (agent config, session SummaryConfig).
var SanitizeReasoningEffort = api.SanitizeReasoningEffort
// Prompt-cache helpers re-exported for the application layer.
var (
FingerprintPromptPrefix = api.FingerprintPromptPrefix
PromptPrefixFingerprint = api.PromptPrefixFingerprint
BuildPromptCacheKey = api.BuildPromptCacheKey
)
// Chat 定义了聊天接口
type Chat interface {
// Chat 进行非流式聊天
Chat(ctx context.Context, messages []Message, opts *ChatOptions) (*types.ChatResponse, error)
// ChatStream 进行流式聊天
ChatStream(ctx context.Context, messages []Message, opts *ChatOptions) (<-chan types.StreamResponse, error)
// GetModelName 获取模型名称
GetModelName() string
// GetModelID 获取模型ID
GetModelID() string
}
// ChatConfig is the operator-facing configuration of one chat model.
type ChatConfig struct {
Source types.ModelSource
BaseURL string
ModelName string
APIKey string
ModelID string
Provider string
// MaxConcurrency caps concurrent background calls to this model; 0 falls
// back to the process-wide default (see limiter.GateN).
MaxConcurrency int
ExtraConfig map[string]string
// CustomHeaders 允许在调用远程 API 时附加自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。
CustomHeaders map[string]string
AppID string
AppSecret string // 加密值,由工厂函数调用方传入,在使用前已解密
// Spec carries per-row catalog overrides (protocol, compat, levels).
Spec *types.ModelSpecOverride
}
// ConfigFromModel 根据 types.Model 构造 ChatConfig。
// 保证生产路径(service 层根据 DB 中的模型配置拉起实例)和测试路径
// (handler 层根据前端表单临时拉起实例)走完全相同的字段映射。
// appID / appSecret 是已经解密/解析好的 AcademyCloud 凭证,调用方负责传入。
func ConfigFromModel(m *types.Model, appID, appSecret string) *ChatConfig {
if m == nil {
return nil
}
return &ChatConfig{
ModelID: m.ID,
APIKey: m.Parameters.APIKey,
BaseURL: m.Parameters.BaseURL,
ModelName: m.Name,
Source: m.Source,
Provider: m.Parameters.Provider,
MaxConcurrency: m.Parameters.MaxConcurrency,
ExtraConfig: m.Parameters.ExtraConfig,
CustomHeaders: m.Parameters.CustomHeaders,
AppID: appID,
AppSecret: appSecret,
Spec: m.Parameters.Spec,
}
}
// NewChat 创建聊天实例
func NewChat(config *ChatConfig, ollamaService *ollama.OllamaService) (Chat, error) {
var c Chat
var err error
switch strings.ToLower(string(config.Source)) {
case string(types.ModelSourceLocal):
c, err = NewOllamaChat(config, ollamaService)
case string(types.ModelSourceRemote):
c, err = NewRemoteChat(config)
default:
return nil, fmt.Errorf("unsupported chat model source: %s", config.Source)
}
c, err = wrapChatDebug(c, err)
c, err = wrapChatLangfuse(c, err)
// Outermost: hold the per-model concurrency slot only around the real
// provider round-trip, so the wait is excluded from debug/langfuse timing.
return wrapChatConcurrency(c, config.MaxConcurrency, err)
}
// Resolve looks the configuration up in the catalog. It is exposed so the
// handler layer can report the effective protocol and capabilities.
func Resolve(config *ChatConfig) (*modelruntime.Resolved, error) {
if config == nil {
return nil, fmt.Errorf("chat config is nil")
}
return modelruntime.Resolve(modelruntime.Ref{
Provider: config.Provider,
Model: config.ModelName,
BaseURL: config.BaseURL,
ModelType: types.ModelTypeKnowledgeQA,
Extra: config.ExtraConfig,
Override: config.Spec,
})
}
// EffectiveThinkingControl reports how the resolved model encodes thinking
// ("none" when it cannot be asked to think). Kept for the model debug view.
func EffectiveThinkingControl(config *ChatConfig) string {
resolved, err := Resolve(config)
if err != nil {
return "none"
}
caps := resolved.Capabilities()
if len(caps.ThinkingLevels) == 0 {
return "none"
}
return caps.ThinkingFormat
}
// NewRemoteChat builds the protocol client for a remote model.
func NewRemoteChat(config *ChatConfig) (Chat, error) {
resolved, err := Resolve(config)
if err != nil {
return nil, err
}
vendor := resolved.Vendor
if resolved.BaseURL != "" {
if err := secutils.ValidateURLForSSRF(resolved.BaseURL); err != nil {
return nil, fmt.Errorf("baseURL SSRF check failed: %w", err)
}
}
endpoint, err := resolved.Endpoint(types.ModelTypeKnowledgeQA, modelruntime.Connection{
ModelID: config.ModelID,
Credentials: api.Credentials{APIKey: config.APIKey, AppID: config.AppID, AppSecret: config.AppSecret},
Headers: config.CustomHeaders,
Extra: config.ExtraConfig,
})
if err != nil {
return nil, err
}
switch resolved.API {
case api.APIOpenAICompletions:
return openaicompletions.New(openaicompletions.Config{
Endpoint: endpoint,
Settings: resolved.OpenAICompletions,
ThinkingLevels: resolved.ThinkingLevels,
Reasoning: resolved.Spec.Reasoning,
}), nil
case api.APIOpenAIResponses:
return openairesponses.New(openairesponses.Config{
Endpoint: endpoint,
Settings: resolved.OpenAIResponses,
ThinkingLevels: resolved.ThinkingLevels,
Reasoning: resolved.Spec.Reasoning,
}), nil
case api.APIAnthropicMessages:
return anthropicmessages.New(anthropicmessages.Config{
Endpoint: endpoint,
Settings: resolved.AnthropicMessages,
ThinkingLevels: resolved.ThinkingLevels,
Reasoning: resolved.Spec.Reasoning,
}), nil
case api.APIGoogleGenerativeAI:
return googlegenai.New(googlegenai.Config{
Endpoint: endpoint,
Settings: resolved.GoogleGenerativeAI,
ThinkingLevels: resolved.ThinkingLevels,
Reasoning: resolved.Spec.Reasoning,
}), nil
default:
return nil, fmt.Errorf("unsupported chat api %q for provider %s", resolved.API, vendor.ID)
}
}
@@ -0,0 +1,82 @@
package chat
import (
"context"
"academy/internal/models/limiter"
"academy/internal/types"
)
// Model provider budgets are the real bottleneck shared by every LLM-backed
// background stage (summary / question / graph / multimodal enrichment), which
// all target the same model. This governor caps concurrent calls per model at
// the client layer — the one place that sees all task types — instead of at the
// asynq queue layer, whose weights are scheduling priority rather than
// throttling.
//
// Only background (asynq worker) calls are throttled; interactive chat is left
// untouched (see types.IsBackgroundTask), so a document-ingestion storm cannot
// exhaust the provider yet user-facing latency is never gated behind the
// semaphore. The governor singleton itself lives in the limiter package so chat
// and vlm share the same limiter and per-model budget.
// concurrencyChat throttles background LLM calls through a per-model
// distributed semaphore. It is the outermost wrapper so the slot is held only
// around the actual provider round-trip and the wait time is excluded from the
// inner debug/langfuse timing.
type concurrencyChat struct {
inner Chat
// 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 *concurrencyChat) GetModelName() string { return w.inner.GetModelName() }
func (w *concurrencyChat) GetModelID() string { return w.inner.GetModelID() }
func (w *concurrencyChat) Chat(ctx context.Context, messages []Message, opts *ChatOptions) (*types.ChatResponse, error) {
release := limiter.GateNamedN(ctx, w.inner.GetModelID(), w.inner.GetModelName(), w.limit)
defer release()
return w.inner.Chat(ctx, messages, opts)
}
func (w *concurrencyChat) ChatStream(ctx context.Context, messages []Message, opts *ChatOptions) (<-chan types.StreamResponse, error) {
release := limiter.GateNamedN(ctx, w.inner.GetModelID(), w.inner.GetModelName(), w.limit)
ch, err := w.inner.ChatStream(ctx, messages, opts)
if err != nil || ch == nil {
release()
return ch, err
}
// Hold the slot until the stream fully drains, then release. If the
// consumer abandons the stream (stops reading out) we would otherwise
// block forever on the send and never release the slot; select on
// ctx.Done() so a cancelled call frees its slot promptly, and drain the
// inner channel in the background so the upstream producer can exit.
out := make(chan types.StreamResponse)
go func() {
defer close(out)
defer release()
for resp := range ch {
select {
case out <- resp:
case <-ctx.Done():
go func() {
for range ch {
}
}()
return
}
}
}()
return out, nil
}
// wrapChatConcurrency installs the background concurrency governor as the
// outermost Chat decorator. It is always applied; when no limiter is installed
// or the call is interactive, the wrapper is a cheap passthrough.
func wrapChatConcurrency(c Chat, limit int, err error) (Chat, error) {
if err != nil || c == nil {
return c, err
}
return &concurrencyChat{inner: c, limit: limit}, nil
}
@@ -0,0 +1,93 @@
package chat
import (
"context"
"testing"
"time"
"academy/internal/models/limiter"
"academy/internal/types"
)
// fakeChat is a minimal Chat whose stream emits continuously until ctx is done,
// so we can exercise the concurrency wrapper's slot lifecycle.
type fakeChat struct{ id string }
func (f *fakeChat) GetModelName() string { return f.id }
func (f *fakeChat) GetModelID() string { return f.id }
func (f *fakeChat) Chat(ctx context.Context, _ []Message, _ *ChatOptions) (*types.ChatResponse, error) {
return &types.ChatResponse{}, nil
}
func (f *fakeChat) ChatStream(ctx context.Context, _ []Message, _ *ChatOptions) (<-chan types.StreamResponse, error) {
ch := make(chan types.StreamResponse)
go func() {
defer close(ch)
for {
select {
case <-ctx.Done():
return
case ch <- types.StreamResponse{}:
}
}
}()
return ch, nil
}
// TestConcurrencyChatInteractiveNotGated verifies interactive calls bypass the
// governor entirely even at limit 1.
func TestConcurrencyChatInteractiveNotGated(t *testing.T) {
t.Cleanup(func() { limiter.SetGovernor(nil, 0) })
limiter.SetGovernor(limiter.NewLocalLimiter(), 1)
w := &concurrencyChat{inner: &fakeChat{id: "model-x"}}
// No background marker: neither call should be throttled.
if _, err := w.Chat(context.Background(), nil, nil); err != nil {
t.Fatalf("interactive chat: %v", err)
}
if _, err := w.Chat(context.Background(), nil, nil); err != nil {
t.Fatalf("interactive chat 2: %v", err)
}
}
// TestConcurrencyChatStreamReleasesOnAbandon verifies that when the consumer
// stops reading and cancels the context, the held slot is released rather than
// leaked (the #9 fix).
func TestConcurrencyChatStreamReleasesOnAbandon(t *testing.T) {
t.Cleanup(func() { limiter.SetGovernor(nil, 0) })
limiter.SetGovernor(limiter.NewLocalLimiter(), 1)
const id = "model-y"
w := &concurrencyChat{inner: &fakeChat{id: id}}
streamCtx, cancel := context.WithCancel(types.WithBackgroundTask(context.Background()))
out, err := w.ChatStream(streamCtx, nil, nil)
if err != nil {
t.Fatalf("stream: %v", err)
}
// Consume one item so the relay goroutine is running and holding the slot.
<-out
// The single slot is now held: a background acquire must block.
blocked := make(chan struct{})
go func() {
rel := limiter.Gate(types.WithBackgroundTask(context.Background()), id)
rel()
close(blocked)
}()
select {
case <-blocked:
t.Fatal("slot should be held by the live stream")
case <-time.After(50 * time.Millisecond):
}
// Abandon the stream: stop reading and cancel. The relay must release.
cancel()
select {
case <-blocked:
// released and reacquired successfully
case <-time.After(2 * time.Second):
t.Fatal("stream slot leaked: not released after consumer abandoned + cancelled")
}
}
@@ -0,0 +1,59 @@
package chat
import (
"testing"
"academy/internal/types"
)
// TestConfigFromModel 验证 ConfigFromModel 能把 types.Model 完整映射到 ChatConfig,
// 避免后续新加字段时只在生产路径或测试路径其中一侧更新导致功能漏配。
func TestConfigFromModel(t *testing.T) {
m := &types.Model{
ID: "model-123",
Name: "gpt-4o-mini",
Source: types.ModelSourceRemote,
Parameters: types.ModelParameters{
BaseURL: "https://api.example.com/v1",
APIKey: "sk-xxx",
Provider: "openai",
ExtraConfig: map[string]string{
"deployment": "prod",
},
CustomHeaders: map[string]string{
"X-Gateway-Token": "abc",
"X-Trace-ID": "t-1",
},
},
}
cfg := ConfigFromModel(m, "app-id", "app-secret")
if cfg == nil {
t.Fatal("ConfigFromModel returned nil")
}
if cfg.ModelID != "model-123" || cfg.ModelName != "gpt-4o-mini" {
t.Errorf("model identity not propagated: %+v", cfg)
}
if cfg.BaseURL != "https://api.example.com/v1" || cfg.APIKey != "sk-xxx" {
t.Errorf("connection fields not propagated: %+v", cfg)
}
if cfg.Provider != "openai" {
t.Errorf("provider not propagated: %q", cfg.Provider)
}
if cfg.ExtraConfig["deployment"] != "prod" {
t.Errorf("ExtraConfig not propagated: %+v", cfg.ExtraConfig)
}
if cfg.CustomHeaders["X-Gateway-Token"] != "abc" ||
cfg.CustomHeaders["X-Trace-ID"] != "t-1" {
t.Errorf("CustomHeaders not propagated: %+v", cfg.CustomHeaders)
}
if cfg.AppID != "app-id" || cfg.AppSecret != "app-secret" {
t.Errorf("cloud credentials not propagated: %+v", cfg)
}
}
func TestConfigFromModel_Nil(t *testing.T) {
if got := ConfigFromModel(nil, "", ""); got != nil {
t.Fatalf("expected nil for nil model, got %+v", got)
}
}
+295
View File
@@ -0,0 +1,295 @@
package chat
import (
"context"
"fmt"
"strings"
"time"
"academy/internal/tracing/langfuse"
"academy/internal/types"
)
// langfuseChat wraps a Chat implementation and emits a Langfuse generation
// observation for every Chat/ChatStream call, capturing prompt, response and
// token usage. The wrapper is only installed when the Langfuse manager is
// enabled, so there is no cost for deployments that don't use Langfuse.
type langfuseChat struct {
inner Chat
}
func (l *langfuseChat) GetModelName() string { return l.inner.GetModelName() }
func (l *langfuseChat) GetModelID() string { return l.inner.GetModelID() }
func (l *langfuseChat) Chat(ctx context.Context, messages []Message, opts *ChatOptions) (*types.ChatResponse, error) {
mgr := langfuse.GetManager()
if !mgr.Enabled() {
return l.inner.Chat(ctx, messages, opts)
}
purpose, prefixFingerprint := types.LLMCallMetadataFromContext(ctx)
genCtx, gen := mgr.StartGeneration(ctx, langfuse.GenerationOptions{
Name: "chat.completion",
Model: l.inner.GetModelName(),
Input: buildLangfuseMessages(messages),
ModelParameters: buildLangfuseModelParams(opts),
Metadata: buildLangfuseChatMetadata(l.inner.GetModelID(), purpose, prefixFingerprint, false, opts),
})
resp, err := l.inner.Chat(genCtx, messages, opts)
var usage *langfuse.TokenUsage
var output interface{}
if resp != nil {
usage = convertUsage(&resp.Usage)
output = buildLangfuseGenerationOutput(
resp.Content, resp.ReasoningContent, resp.FinishReason, resp.ToolCalls,
)
}
gen.Finish(output, usage, err)
return resp, err
}
func (l *langfuseChat) ChatStream(ctx context.Context, messages []Message, opts *ChatOptions) (<-chan types.StreamResponse, error) {
mgr := langfuse.GetManager()
if !mgr.Enabled() {
return l.inner.ChatStream(ctx, messages, opts)
}
purpose, prefixFingerprint := types.LLMCallMetadataFromContext(ctx)
genCtx, gen := mgr.StartGeneration(ctx, langfuse.GenerationOptions{
Name: "chat.completion.stream",
Model: l.inner.GetModelName(),
Input: buildLangfuseMessages(messages),
ModelParameters: buildLangfuseModelParams(opts),
Metadata: buildLangfuseChatMetadata(l.inner.GetModelID(), purpose, prefixFingerprint, true, opts),
})
ch, err := l.inner.ChatStream(genCtx, messages, opts)
if err != nil {
gen.Finish(nil, nil, err)
return ch, err
}
if ch == nil {
gen.Finish(nil, nil, nil)
return nil, nil
}
wrapped := make(chan types.StreamResponse)
go func() {
defer close(wrapped)
var contentBuf []byte
var reasoningBuf []byte
var usage *types.TokenUsage
var toolCalls []types.LLMToolCall
var finishReason string
var firstToken bool
for resp := range ch {
if resp.ResponseType == types.ResponseTypeThinking && resp.Content != "" {
if !firstToken {
gen.MarkCompletionStart(time.Now())
firstToken = true
}
reasoningBuf = append(reasoningBuf, resp.Content...)
}
if resp.ResponseType == types.ResponseTypeAnswer && resp.Content != "" {
if !firstToken {
gen.MarkCompletionStart(time.Now())
firstToken = true
}
contentBuf = append(contentBuf, resp.Content...)
}
if resp.Usage != nil {
usage = resp.Usage
}
if len(resp.ToolCalls) > 0 {
// The downstream model-context registry decodes arguments in
// place before tool execution. Snapshot the provider payload so
// the generation observation remains the exact model output and
// cannot be changed through the shared slice backing array.
toolCalls = snapshotLangfuseToolCalls(resp.ToolCalls)
}
if resp.FinishReason != "" {
finishReason = resp.FinishReason
}
wrapped <- resp
}
output := buildLangfuseGenerationOutput(
string(contentBuf), string(reasoningBuf), finishReason, toolCalls,
)
gen.Finish(output, convertUsage(usage), nil)
}()
return wrapped, nil
}
func snapshotLangfuseToolCalls(toolCalls []types.LLMToolCall) []types.LLMToolCall {
return append([]types.LLMToolCall(nil), toolCalls...)
}
const (
langfuseDiscoverMCPTool = "discover_mcp_tools"
langfuseMCPCatalogRunes = 8000
)
func buildLangfuseChatMetadata(
modelID, purpose, prefixFingerprint string,
streaming bool,
opts *ChatOptions,
) map[string]interface{} {
meta := map[string]interface{}{
"model_id": modelID,
"streaming": streaming,
"has_tools": opts != nil && len(opts.Tools) > 0,
"call_purpose": purpose,
"prompt_prefix_fingerprint": prefixFingerprint,
}
if opts == nil || len(opts.Tools) == 0 {
return meta
}
names := make([]string, 0, len(opts.Tools))
for _, tool := range opts.Tools {
names = append(names, tool.Function.Name)
if tool.Function.Name == langfuseDiscoverMCPTool && tool.Function.Description != "" {
meta["mcp_catalog"] = truncateLangfuseText(tool.Function.Description, langfuseMCPCatalogRunes)
}
}
meta["tool_names"] = names
return meta
}
func truncateLangfuseText(s string, maxRunes int) string {
if maxRunes <= 0 {
return ""
}
runes := []rune(s)
if len(runes) <= maxRunes {
return s
}
return string(runes[:maxRunes]) + "…"
}
func buildLangfuseMessages(messages []Message) []map[string]interface{} {
out := make([]map[string]interface{}, 0, len(messages))
for _, m := range messages {
entry := map[string]interface{}{
"role": m.Role,
}
if m.Content != "" {
entry["content"] = m.Content
}
if len(m.MultiContent) > 0 {
entry["content"] = m.MultiContent
}
if len(m.Images) > 0 {
images := make([]string, len(m.Images))
for i, img := range m.Images {
images[i] = describeLangfuseImage(img)
}
entry["images"] = images
}
if m.Name != "" {
entry["name"] = m.Name
}
if m.ToolCallID != "" {
entry["tool_call_id"] = m.ToolCallID
}
if len(m.ToolCalls) > 0 {
entry["tool_calls"] = m.ToolCalls
}
if m.ReasoningContent != "" {
entry["reasoning_content"] = m.ReasoningContent
}
out = append(out, entry)
}
return out
}
// describeLangfuseImage keeps base64 payloads out of traces: a data URI is
// recorded as its media type and size, a URL as itself.
func describeLangfuseImage(img string) string {
if !strings.HasPrefix(img, "data:") {
return img
}
mediaType, _, _ := strings.Cut(strings.TrimPrefix(img, "data:"), ";")
return fmt.Sprintf("data:%s (%d KB)", mediaType, (len(img)+1023)/1024)
}
func buildLangfuseGenerationOutput(
content, reasoningContent, finishReason string,
toolCalls []types.LLMToolCall,
) map[string]interface{} {
output := map[string]interface{}{
"content": content,
"tool_calls": toolCalls,
"finish_reason": finishReason,
}
if reasoningContent != "" {
output["reasoning_content"] = reasoningContent
}
return output
}
func buildLangfuseModelParams(opts *ChatOptions) map[string]interface{} {
if opts == nil {
return nil
}
params := map[string]interface{}{}
if opts.Temperature != 0 {
params["temperature"] = opts.Temperature
}
if opts.TopP != 0 {
params["top_p"] = opts.TopP
}
if budget := opts.CompletionBudget(); budget > 0 {
params["max_completion_tokens"] = budget
}
if opts.FrequencyPenalty != 0 {
params["frequency_penalty"] = opts.FrequencyPenalty
}
if opts.PresencePenalty != 0 {
params["presence_penalty"] = opts.PresencePenalty
}
if opts.Seed != 0 {
params["seed"] = opts.Seed
}
if opts.ToolChoice != "" {
params["tool_choice"] = opts.ToolChoice
}
if len(params) == 0 {
return nil
}
return params
}
func convertUsage(u *types.TokenUsage) *langfuse.TokenUsage {
if u == nil {
return nil
}
if u.PromptTokens == 0 && u.CompletionTokens == 0 && u.TotalTokens == 0 {
return nil
}
return &langfuse.TokenUsage{
Input: u.PromptTokens,
Output: u.CompletionTokens,
Total: u.TotalTokens,
CacheRead: u.CacheReadTokens,
CacheWrite: u.CacheWriteTokens,
CacheMiss: u.CacheMissTokens,
Unit: "TOKENS",
}
}
// wrapChatLangfuse wraps a Chat in a Langfuse-aware decorator when the
// manager is enabled. Called from NewChat after the debug wrapper so both
// sinks observe the same call.
func wrapChatLangfuse(c Chat, err error) (Chat, error) {
if err != nil || c == nil {
return c, err
}
if !langfuse.GetManager().Enabled() {
return c, nil
}
return &langfuseChat{inner: c}, nil
}
@@ -0,0 +1,113 @@
package chat
import (
"reflect"
"strings"
"testing"
"academy/internal/types"
)
func TestBuildLangfuseGenerationOutput(t *testing.T) {
toolCalls := []types.LLMToolCall{{ID: "call_1", Type: "function"}}
got := buildLangfuseGenerationOutput("", "", "tool_calls", toolCalls)
want := map[string]interface{}{
"content": "",
"tool_calls": toolCalls,
"finish_reason": "tool_calls",
}
if !reflect.DeepEqual(got, want) {
t.Fatalf("output without reasoning = %#v; want %#v", got, want)
}
got = buildLangfuseGenerationOutput("answer", "thinking", "stop", nil)
want = map[string]interface{}{
"content": "answer",
"tool_calls": []types.LLMToolCall(nil),
"finish_reason": "stop",
"reasoning_content": "thinking",
}
if !reflect.DeepEqual(got, want) {
t.Fatalf("output with reasoning = %#v; want %#v", got, want)
}
}
func TestSnapshotLangfuseToolCallsKeepsModelArguments(t *testing.T) {
providerCalls := []types.LLMToolCall{{
ID: "call_1",
Function: types.FunctionCall{Name: "wiki_read_page", Arguments: `{"slugs":["res://0001"]}`},
}}
snapshot := snapshotLangfuseToolCalls(providerCalls)
providerCalls[0].Function.Arguments = `{"slugs":["summary/uuid"]}`
if got := snapshot[0].Function.Arguments; got != `{"slugs":["res://0001"]}` {
t.Fatalf("Langfuse snapshot was mutated to %s", got)
}
}
func TestBuildLangfuseMessagesReasoningContent(t *testing.T) {
msgs := buildLangfuseMessages([]Message{
{Role: "assistant", ReasoningContent: "chain of thought", ToolCalls: []ToolCall{{ID: "tc1"}}},
})
if len(msgs) != 1 {
t.Fatalf("len(messages) = %d; want 1", len(msgs))
}
if msgs[0]["reasoning_content"] != "chain of thought" {
t.Fatalf("reasoning_content = %v; want chain of thought", msgs[0]["reasoning_content"])
}
}
func TestBuildLangfuseMessagesRecordsImagesWithoutPayload(t *testing.T) {
dataURI := "data:image/png;base64," + strings.Repeat("A", 2048)
msgs := buildLangfuseMessages([]Message{
{Role: "user", Content: "look", Images: []string{dataURI, "https://example.com/a.png"}},
})
want := []string{"data:image/png (3 KB)", "https://example.com/a.png"}
if !reflect.DeepEqual(msgs[0]["images"], want) {
t.Fatalf("images = %#v; want %#v", msgs[0]["images"], want)
}
}
func TestConvertUsageIncludesPromptCacheCounters(t *testing.T) {
got := convertUsage(&types.TokenUsage{
PromptTokens: 1000, CompletionTokens: 50, TotalTokens: 1050,
CacheReadTokens: 800, CacheWriteTokens: 100, CacheMissTokens: 200,
})
if got == nil {
t.Fatal("convertUsage returned nil")
}
if got.CacheRead != 800 || got.CacheWrite != 100 || got.CacheMiss != 200 {
t.Fatalf("cache usage = read:%d write:%d miss:%d", got.CacheRead, got.CacheWrite, got.CacheMiss)
}
}
func TestBuildLangfuseChatMetadataIncludesMCPCatalog(t *testing.T) {
meta := buildLangfuseChatMetadata("model-1", "agent", "fp", true, &ChatOptions{
Tools: []Tool{
{Function: FunctionDef{Name: "knowledge_search", Description: "search kb"}},
{Function: FunctionDef{
Name: langfuseDiscoverMCPTool,
Description: "MCP tools are available without an @mention.\n{\"server_id\":\"svc\"}",
}},
{Function: FunctionDef{Name: "call_mcp_tool", Description: "call"}},
},
})
if meta["has_tools"] != true || meta["streaming"] != true {
t.Fatalf("flags = %#v", meta)
}
names, _ := meta["tool_names"].([]string)
if !reflect.DeepEqual(names, []string{"knowledge_search", langfuseDiscoverMCPTool, "call_mcp_tool"}) {
t.Fatalf("tool_names = %#v", names)
}
catalog, _ := meta["mcp_catalog"].(string)
if !strings.Contains(catalog, `"server_id":"svc"`) {
t.Fatalf("mcp_catalog = %q", catalog)
}
}
func TestTruncateLangfuseText(t *testing.T) {
if got := truncateLangfuseText("一二三四五", 3); got != "一二三…" {
t.Fatalf("got %q", got)
}
}
+206
View File
@@ -0,0 +1,206 @@
package chat
import (
"context"
"fmt"
"strings"
"time"
"academy/internal/logger"
"academy/internal/models/api"
"academy/internal/types"
)
func buildLLMMessages(messages []Message) []logger.LLMMessage {
out := make([]logger.LLMMessage, 0, len(messages))
for _, m := range messages {
lm := logger.LLMMessage{
Role: m.Role,
Content: m.Content,
Name: m.Name,
ToolCallID: m.ToolCallID,
Images: m.Images,
}
if lm.Content == "" && len(m.MultiContent) > 0 {
var parts []string
for _, mc := range m.MultiContent {
switch mc.Type {
case "text":
parts = append(parts, mc.Text)
case "image_url":
if mc.ImageURL != nil {
parts = append(parts,
fmt.Sprintf("[image_url: %s]", api.TruncateForDebug(mc.ImageURL.URL, 120)))
}
}
}
lm.Content = strings.Join(parts, "\n")
}
for _, tc := range m.ToolCalls {
lm.ToolCalls = append(lm.ToolCalls, logger.LLMToolCallInfo{
ID: tc.ID,
FuncName: tc.Function.Name,
Arguments: tc.Function.Arguments,
})
}
out = append(out, lm)
}
return out
}
func buildOptionsSection(opts *ChatOptions) string {
if opts == nil {
return ""
}
var parts []string
parts = append(parts, fmt.Sprintf("Temperature=%.2f", opts.Temperature))
if opts.TopP > 0 {
parts = append(parts, fmt.Sprintf("TopP=%.2f", opts.TopP))
}
if budget := opts.CompletionBudget(); budget > 0 {
parts = append(parts, fmt.Sprintf("CompletionBudget=%d", budget))
}
if opts.FrequencyPenalty > 0 {
parts = append(parts, fmt.Sprintf("FrequencyPenalty=%.2f", opts.FrequencyPenalty))
}
if opts.PresencePenalty > 0 {
parts = append(parts, fmt.Sprintf("PresencePenalty=%.2f", opts.PresencePenalty))
}
if opts.ToolChoice != "" {
parts = append(parts, fmt.Sprintf("ToolChoice=%s", opts.ToolChoice))
}
if len(opts.Format) > 0 {
parts = append(parts, "ResponseFormat=json_object")
}
return strings.Join(parts, ", ")
}
func buildToolsSection(opts *ChatOptions) string {
if opts == nil || len(opts.Tools) == 0 {
return ""
}
var b strings.Builder
for i, t := range opts.Tools {
if i > 0 {
b.WriteString("\n")
}
b.WriteString(fmt.Sprintf("- %s: %s", t.Function.Name, t.Function.Description))
}
return b.String()
}
func buildResponseToolCalls(tcs []types.LLMToolCall) []logger.LLMToolCallInfo {
if len(tcs) == 0 {
return nil
}
out := make([]logger.LLMToolCallInfo, 0, len(tcs))
for _, tc := range tcs {
out = append(out, logger.LLMToolCallInfo{
ID: tc.ID,
FuncName: tc.Function.Name,
Arguments: tc.Function.Arguments,
})
}
return out
}
func usageString(u types.TokenUsage) string {
return fmt.Sprintf("Prompt: %d, Completion: %d, Total: %d, CacheRead: %d, CacheWrite: %d, CacheMiss: %d, CacheStatus: %s",
u.PromptTokens, u.CompletionTokens, u.TotalTokens, u.CacheReadTokens,
u.CacheWriteTokens, u.CacheMissTokens, u.CacheStatus)
}
// logLLMDebugCall logs a complete non-stream LLM chat call.
func logLLMDebugCall(ctx context.Context, model string, messages []Message, opts *ChatOptions, resp *types.ChatResponse, callErr error, dur time.Duration) {
if !logger.LLMDebugEnabled() {
return
}
record := &logger.LLMCallRecord{
CallType: "Chat",
Model: model,
Duration: dur,
}
record.Sections = append(record.Sections, logger.RecordSection{
Title: "Messages",
Content: logger.FormatMessages(buildLLMMessages(messages)),
})
if s := buildOptionsSection(opts); s != "" {
record.Sections = append(record.Sections, logger.RecordSection{Title: "Options", Content: s})
}
if s := buildToolsSection(opts); s != "" {
record.Sections = append(record.Sections, logger.RecordSection{Title: "Tools", Content: s})
}
if resp != nil {
var respText strings.Builder
if resp.Content != "" {
respText.WriteString("[assistant]\n")
respText.WriteString(resp.Content)
respText.WriteString("\n")
}
tcs := buildResponseToolCalls(resp.ToolCalls)
if len(tcs) > 0 {
respText.WriteString(logger.FormatToolCalls(tcs))
}
if respText.Len() > 0 {
record.Sections = append(record.Sections, logger.RecordSection{Title: "Response", Content: respText.String()})
}
record.Sections = append(record.Sections, logger.RecordSection{Title: "Usage", Content: usageString(resp.Usage)})
}
if callErr != nil {
record.Error = callErr.Error()
}
logger.LLMDebugLog(ctx, record)
}
// logLLMDebugStream logs a complete stream LLM chat call after all chunks have been received.
func logLLMDebugStream(ctx context.Context, model string, messages []Message, opts *ChatOptions, fullContent string, toolCalls []types.LLMToolCall, usage *types.TokenUsage, callErr error, dur time.Duration) {
if !logger.LLMDebugEnabled() {
return
}
record := &logger.LLMCallRecord{
CallType: "Chat Stream",
Model: model,
Duration: dur,
}
record.Sections = append(record.Sections, logger.RecordSection{
Title: "Messages",
Content: logger.FormatMessages(buildLLMMessages(messages)),
})
if s := buildOptionsSection(opts); s != "" {
record.Sections = append(record.Sections, logger.RecordSection{Title: "Options", Content: s})
}
if s := buildToolsSection(opts); s != "" {
record.Sections = append(record.Sections, logger.RecordSection{Title: "Tools", Content: s})
}
var respText strings.Builder
if fullContent != "" {
respText.WriteString("[assistant]\n")
respText.WriteString(fullContent)
respText.WriteString("\n")
}
tcs := buildResponseToolCalls(toolCalls)
if len(tcs) > 0 {
respText.WriteString(logger.FormatToolCalls(tcs))
}
if respText.Len() > 0 {
record.Sections = append(record.Sections, logger.RecordSection{Title: "Response", Content: respText.String()})
}
if usage != nil {
record.Sections = append(record.Sections, logger.RecordSection{Title: "Usage", Content: usageString(*usage)})
}
if callErr != nil {
record.Error = callErr.Error()
}
logger.LLMDebugLog(ctx, record)
}
+77
View File
@@ -0,0 +1,77 @@
package chat
import (
"context"
"fmt"
"strings"
"time"
"academy/internal/logger"
"academy/internal/types"
)
// debugChat wraps a Chat implementation and logs all calls to the LLM debug log.
// It works with both RemoteAPIChat and OllamaChat (or any future Chat impl).
type debugChat struct {
inner Chat
}
func (d *debugChat) GetModelName() string { return d.inner.GetModelName() }
func (d *debugChat) GetModelID() string { return d.inner.GetModelID() }
func (d *debugChat) Chat(ctx context.Context, messages []Message, opts *ChatOptions) (*types.ChatResponse, error) {
callStart := time.Now()
resp, err := d.inner.Chat(ctx, messages, opts)
logLLMDebugCall(ctx, d.inner.GetModelName(), messages, opts, resp, err, time.Since(callStart))
return resp, err
}
func (d *debugChat) ChatStream(ctx context.Context, messages []Message, opts *ChatOptions) (<-chan types.StreamResponse, error) {
callStart := time.Now()
ch, err := d.inner.ChatStream(ctx, messages, opts)
if err != nil {
logLLMDebugStream(ctx, d.inner.GetModelName(), messages, opts, "", nil, nil, err, time.Since(callStart))
return ch, err
}
if ch == nil {
return nil, nil
}
wrapped := make(chan types.StreamResponse)
go func() {
defer close(wrapped)
var content strings.Builder
var usage *types.TokenUsage
var toolCalls []types.LLMToolCall
var streamErr error
for resp := range ch {
if resp.ResponseType == types.ResponseTypeAnswer && resp.Content != "" {
content.WriteString(resp.Content)
}
if resp.ResponseType == types.ResponseTypeError {
streamErr = fmt.Errorf("%s", resp.Content)
}
if resp.Usage != nil {
usage = resp.Usage
}
if len(resp.ToolCalls) > 0 {
toolCalls = resp.ToolCalls
}
wrapped <- resp
}
logLLMDebugStream(ctx, d.inner.GetModelName(), messages, opts,
content.String(), toolCalls, usage, streamErr, time.Since(callStart))
}()
return wrapped, nil
}
// wrapChatDebug wraps a Chat if LLM debug logging is enabled.
func wrapChatDebug(c Chat, err error) (Chat, error) {
if err != nil || !logger.LLMDebugEnabled() {
return c, err
}
return &debugChat{inner: c}, nil
}
+418
View File
@@ -0,0 +1,418 @@
package chat
import (
"context"
"encoding/json"
"fmt"
"io"
"strconv"
"strings"
"time"
"academy/internal/logger"
"academy/internal/models/api"
"academy/internal/models/utils/ollama"
"academy/internal/types"
secutils "academy/internal/utils"
ollamaapi "github.com/ollama/ollama/api"
)
// OllamaChat 实现了基于 Ollama 的聊天
type OllamaChat struct {
modelName string
modelID string
ollamaService *ollama.OllamaService
}
// NewOllamaChat 创建 Ollama 聊天实例
func NewOllamaChat(config *ChatConfig, ollamaService *ollama.OllamaService) (*OllamaChat, error) {
return &OllamaChat{
modelName: config.ModelName,
modelID: config.ModelID,
ollamaService: ollamaService,
}, nil
}
// convertMessages 转换消息格式为Ollama API格式
func (c *OllamaChat) convertMessages(messages []Message) []ollamaapi.Message {
ollamaMessages := make([]ollamaapi.Message, 0, len(messages))
for _, msg := range messages {
msg = api.NeutralizeMessageSpecialTokens(msg)
msgOllama := ollamaapi.Message{
Role: msg.Role,
Content: msg.Content,
ToolCalls: c.toolCallFrom(msg.ToolCalls),
}
if msg.Role == "tool" {
msgOllama.ToolName = msg.Name
}
// The agent builds multimodal turns as MultiContent parts, the shape
// every remote protocol prefers, and only the older callers fill
// Images. Reading just Images dropped both the text and the pictures
// of such a turn: Ollama answered about nothing, without an error.
images := msg.Images
if len(msg.MultiContent) > 0 {
// Copy first: appending to the caller's slice could write into
// its spare capacity and leak an image into another message.
images = append([]string(nil), msg.Images...)
var text strings.Builder
for _, part := range msg.MultiContent {
switch part.Type {
case "text":
text.WriteString(part.Text)
case "image_url":
if part.ImageURL != nil && part.ImageURL.URL != "" {
images = append(images, part.ImageURL.URL)
}
}
}
if msgOllama.Content == "" {
msgOllama.Content = text.String()
}
}
if len(images) > 0 && msg.Role == "user" {
for _, imgURL := range images {
if imgData := resolveImageForOllama(imgURL); imgData != nil {
msgOllama.Images = append(msgOllama.Images, imgData)
}
}
}
ollamaMessages = append(ollamaMessages, msgOllama)
}
return ollamaMessages
}
// resolveImageForOllama resolves an image URL into raw bytes for Ollama.
// Handles local serving paths (/files/...), data URIs, and remote HTTP URLs.
func resolveImageForOllama(imageURL string) ollamaapi.ImageData {
if data := api.ResolveImageURLForOllama(imageURL); data != nil {
return data
}
if strings.HasPrefix(imageURL, "http://") || strings.HasPrefix(imageURL, "https://") {
if err := secutils.ValidateURLForSSRF(imageURL); err != nil {
return nil
}
client := secutils.NewSSRFSafeHTTPClient(secutils.SSRFSafeHTTPClientConfig{
Timeout: 30 * time.Second,
MaxRedirects: 5,
})
resp, err := client.Get(imageURL)
if err != nil {
return nil
}
defer resp.Body.Close()
data, err := io.ReadAll(io.LimitReader(resp.Body, 20*1024*1024))
if err != nil {
return nil
}
return data
}
return nil
}
// buildChatRequest 构建聊天请求参数
func (c *OllamaChat) buildChatRequest(messages []Message, opts *ChatOptions, isStream bool) *ollamaapi.ChatRequest {
// 设置流式标志
streamFlag := isStream
// 构建请求参数
chatReq := &ollamaapi.ChatRequest{
Model: c.modelName,
Messages: c.convertMessages(messages),
Stream: &streamFlag,
Options: make(map[string]interface{}),
}
// Keep request-scoped notices out of the system prefix and stored history.
if opts != nil && opts.RuntimeNotice != "" {
chatReq.Messages = append(chatReq.Messages, ollamaapi.Message{Role: "user", Content: opts.RuntimeNotice})
}
// 添加可选参数
if opts != nil {
chatReq.Options["temperature"] = opts.Temperature
if opts.TopP > 0 {
chatReq.Options["top_p"] = opts.TopP
}
if budget := opts.CompletionBudget(); budget > 0 {
chatReq.Options["num_predict"] = budget
}
if level, requested := opts.Reasoning(); requested {
// Ollama accepts a boolean switch; graded levels only exist for a
// few models, so they collapse to on/off here.
chatReq.Think = &ollamaapi.ThinkValue{Value: level.Enabled()}
}
if len(opts.Format) > 0 {
chatReq.Format = opts.Format
}
if len(opts.Tools) > 0 {
chatReq.Tools = c.toolFrom(opts.Tools)
}
}
return chatReq
}
// Chat 进行非流式聊天
func (c *OllamaChat) Chat(ctx context.Context, messages []Message, opts *ChatOptions) (*types.ChatResponse, error) {
// 确保模型可用
if err := c.ensureModelAvailable(ctx); err != nil {
return nil, err
}
// 构建请求参数
chatReq := c.buildChatRequest(messages, opts, false)
// 记录请求日志
logger.GetLogger(ctx).Infof("发送聊天请求到模型 %s", c.modelName)
var responseContent string
var toolCalls []types.LLMToolCall
var promptTokens, completionTokens int
var finishReason string
// 使用 Ollama 客户端发送请求
err := c.ollamaService.Chat(ctx, chatReq, func(resp ollamaapi.ChatResponse) error {
responseContent = resp.Message.Content
// 当 Content 为空但 Thinking 有内容时(如推理模型未正确配置 thinking 参数),使用 Thinking 作为兜底
if responseContent == "" && resp.Message.Thinking != "" {
responseContent = resp.Message.Thinking
}
toolCalls = c.toolCallTo(resp.Message.ToolCalls)
// done_reason 是 "stop" / "length" 等;不透传的话调用方分不清拒答和
// num_predict 打满导致的截断(图谱抽取据此决定跳过还是重试)。
if resp.DoneReason != "" {
finishReason = resp.DoneReason
}
// 获取token计数。eval_count 本身就是回答的 token 数,不含 prompt
// (https://github.com/ollama/ollama/blob/main/docs/api.md),所以不能再
// 减去 prompt_eval_count —— 流式分支一直是直接采用的,这里对齐它。
if resp.EvalCount > 0 {
promptTokens = resp.PromptEvalCount
completionTokens = resp.EvalCount
}
return nil
})
if err != nil {
return nil, fmt.Errorf("聊天请求失败: %w", err)
}
usage := types.TokenUsage{
PromptTokens: promptTokens,
CompletionTokens: completionTokens,
TotalTokens: promptTokens + completionTokens,
}
usage.MarkPromptCacheUnsupported()
api.LogUsage(ctx, c.modelName, &usage)
return &types.ChatResponse{
Content: responseContent,
ToolCalls: toolCalls,
FinishReason: finishReason,
Usage: usage,
}, nil
}
// ChatStream 进行流式聊天
func (c *OllamaChat) ChatStream(
ctx context.Context,
messages []Message,
opts *ChatOptions,
) (<-chan types.StreamResponse, error) {
// 确保模型可用
if err := c.ensureModelAvailable(ctx); err != nil {
return nil, err
}
// 构建请求参数
chatReq := c.buildChatRequest(messages, opts, true)
// 记录请求日志
logger.GetLogger(ctx).Infof("发送流式聊天请求到模型 %s", c.modelName)
// 创建流式响应通道
streamChan := make(chan types.StreamResponse)
// 启动goroutine处理流式响应
go func() {
defer close(streamChan)
var thinking api.ThinkingEmitter
err := c.ollamaService.Chat(ctx, chatReq, func(resp ollamaapi.ChatResponse) error {
// 发送思考内容(支持 Qwen3、DeepSeek 等推理模型)
if resp.Message.Thinking != "" {
thinking.Emit(streamChan, resp.Message.Thinking)
}
if resp.Message.Content != "" {
// 思考阶段结束后,发送思考完成事件
thinking.Finish(streamChan)
streamChan <- types.StreamResponse{
ResponseType: types.ResponseTypeAnswer,
Content: resp.Message.Content,
Done: false,
}
}
if len(resp.Message.ToolCalls) > 0 {
streamChan <- types.StreamResponse{
ResponseType: types.ResponseTypeToolCall,
ToolCalls: c.toolCallTo(resp.Message.ToolCalls),
Done: false,
}
// Ollama returns tool calls as complete objects (not incremental deltas).
// Log this so we can trace non-streaming thought delivery.
for _, tc := range resp.Message.ToolCalls {
if tc.Function.Name == "thinking" {
argsBytes, _ := json.Marshal(tc.Function.Arguments)
logger.Warnf(ctx, "[Ollama Stream] Tool %q arrived non-incrementally (%d bytes args), "+
"thought will not be token-streamed to frontend",
tc.Function.Name, len(argsBytes))
}
}
for _, tc := range resp.Message.ToolCalls {
argsMap := tc.Function.Arguments.ToMap()
switch tc.Function.Name {
case "thinking":
if thought, ok := argsMap["thought"].(string); ok && thought != "" {
streamChan <- types.StreamResponse{
ResponseType: types.ResponseTypeThinking,
Content: thought,
Done: false,
Data: map[string]interface{}{
"source": "thinking_tool",
"tool_call_id": tooli2s(tc.Function.Index),
},
}
}
}
}
}
if resp.Done {
var usage *types.TokenUsage
if resp.PromptEvalCount > 0 || resp.EvalCount > 0 {
usage = &types.TokenUsage{
PromptTokens: resp.PromptEvalCount,
CompletionTokens: resp.EvalCount,
TotalTokens: resp.PromptEvalCount + resp.EvalCount,
}
usage.MarkPromptCacheUnsupported()
}
api.LogUsage(ctx, c.modelName, usage)
streamChan <- types.StreamResponse{
ResponseType: types.ResponseTypeAnswer,
Done: true,
Usage: usage,
}
}
return nil
})
if err != nil {
logger.GetLogger(ctx).Errorf("流式聊天请求失败: %v", err)
// 发送错误响应
streamChan <- types.StreamResponse{
ResponseType: types.ResponseTypeError,
Content: err.Error(),
Done: true,
}
}
}()
return streamChan, nil
}
// 确保模型可用
func (c *OllamaChat) ensureModelAvailable(ctx context.Context) error {
logger.GetLogger(ctx).Infof("确保模型 %s 可用", c.modelName)
return c.ollamaService.EnsureModelAvailable(ctx, c.modelName)
}
// GetModelName 获取模型名称
func (c *OllamaChat) GetModelName() string {
return c.modelName
}
// GetModelID 获取模型ID
func (c *OllamaChat) GetModelID() string {
return c.modelID
}
// toolFrom 将本模块的 Tool 转换为 Ollama 的 Tool
func (c *OllamaChat) toolFrom(tools []Tool) ollamaapi.Tools {
if len(tools) == 0 {
return nil
}
ollamaTools := make(ollamaapi.Tools, 0, len(tools))
for _, tool := range tools {
function := ollamaapi.ToolFunction{
Name: tool.Function.Name,
Description: tool.Function.Description,
}
if len(tool.Function.Parameters) > 0 {
_ = json.Unmarshal(tool.Function.Parameters, &function.Parameters)
}
ollamaTools = append(ollamaTools, ollamaapi.Tool{
Type: tool.Type,
Function: function,
})
}
return ollamaTools
}
// toolCallFrom 将本模块的 ToolCall 转换为 Ollama 的 ToolCall
func (c *OllamaChat) toolCallFrom(toolCalls []ToolCall) []ollamaapi.ToolCall {
if len(toolCalls) == 0 {
return nil
}
ollamaToolCalls := make([]ollamaapi.ToolCall, 0, len(toolCalls))
for _, tc := range toolCalls {
args := ollamaapi.NewToolCallFunctionArguments()
if tc.Function.Arguments != "" {
_ = args.UnmarshalJSON([]byte(tc.Function.Arguments))
}
ollamaToolCalls = append(ollamaToolCalls, ollamaapi.ToolCall{
Function: ollamaapi.ToolCallFunction{
Index: tools2i(tc.ID),
Name: tc.Function.Name,
Arguments: args,
},
})
}
return ollamaToolCalls
}
// toolCallTo 将 Ollama 的 ToolCall 转换为本模块的 ToolCall
func (c *OllamaChat) toolCallTo(ollamaToolCalls []ollamaapi.ToolCall) []types.LLMToolCall {
if len(ollamaToolCalls) == 0 {
return nil
}
toolCalls := make([]types.LLMToolCall, 0, len(ollamaToolCalls))
for _, tc := range ollamaToolCalls {
argsBytes, _ := json.Marshal(tc.Function.Arguments)
toolCalls = append(toolCalls, types.LLMToolCall{
ID: tooli2s(tc.Function.Index),
Type: "function",
Function: types.FunctionCall{
Name: tc.Function.Name,
Arguments: string(argsBytes),
},
})
}
return toolCalls
}
func tooli2s(i int) string {
return strconv.Itoa(i)
}
func tools2i(s string) int {
i, _ := strconv.Atoi(s)
return i
}
@@ -0,0 +1,54 @@
package chat
import (
"testing"
"academy/internal/models/api"
)
// The agent composes multimodal turns as MultiContent parts — the shape every
// remote protocol prefers — while older callers fill Images. Ollama read only
// the latter, so such a turn reached the model with neither its question nor
// its picture and came back answering about nothing.
func TestOllamaConvertMessagesReadsMultiContent(t *testing.T) {
c := &OllamaChat{}
original := []string{"data:image/png;base64,aGVsbG8="}
messages := []Message{
{
Role: "user",
Images: original,
MultiContent: []api.MessageContentPart{
{Type: "text", Text: "what is this?"},
{Type: "image_url", ImageURL: &api.ImageURL{URL: "data:image/png;base64,d29ybGQ="}},
},
},
}
got := c.convertMessages(messages)
if len(got) != 1 {
t.Fatalf("expected one message, got %d", len(got))
}
if got[0].Content != "what is this?" {
t.Errorf("text parts should become the content, got %q", got[0].Content)
}
if len(got[0].Images) != 2 {
t.Errorf("both the legacy image and the MultiContent one should survive, got %d", len(got[0].Images))
}
if len(original) != 1 || original[0] != "data:image/png;base64,aGVsbG8=" {
t.Errorf("the caller's slice must not be written through, got %v", original)
}
}
func TestOllamaConvertMessagesKeepsExplicitContent(t *testing.T) {
c := &OllamaChat{}
got := c.convertMessages([]Message{{
Role: "user",
Content: "already set",
MultiContent: []api.MessageContentPart{
{Type: "text", Text: "ignored"},
},
}})
if got[0].Content != "already set" {
t.Errorf("an explicit Content wins over the parts, got %q", got[0].Content)
}
}
@@ -0,0 +1,22 @@
package chat
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestOllamaRuntimeNoticePreservesHistory(t *testing.T) {
client := &OllamaChat{modelName: "local"}
messages := []Message{{Role: "system", Content: "Stable policy"}, {Role: "user", Content: "Task"}}
opts := &ChatOptions{PromptCacheKey: "session"}
before := client.buildChatRequest(messages, opts, true)
retryOpts := *opts
retryOpts.RuntimeNotice = `<runtime_event>{"source":"runtime","type":"empty_response_retry"}</runtime_event>`
retry := client.buildChatRequest(messages, &retryOpts, true)
require.Len(t, retry.Messages, len(before.Messages)+1)
require.Equal(t, before.Messages, retry.Messages[:len(before.Messages)])
require.Equal(t, retryOpts.RuntimeNotice, retry.Messages[len(before.Messages)].Content)
require.Equal(t, before, client.buildChatRequest(messages, opts, true))
require.Len(t, messages, 2)
}
+76
View File
@@ -0,0 +1,76 @@
package chat
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/models/utils/ollama"
secutils "academy/internal/utils"
)
func TestResolveImageForOllamaRejectsInternalURL(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "")
secutils.ResetSSRFWhitelistForTest()
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
if data := resolveImageForOllama("http://169.254.169.254/latest/meta-data/"); data != nil {
t.Fatalf("resolveImageForOllama returned data for blocked internal URL")
}
}
func TestResolveImageForOllamaBlocksRedirectToInternalURL(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
secutils.ResetSSRFWhitelistForTest()
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "http://169.254.169.254/latest/meta-data/", http.StatusFound)
}))
defer server.Close()
if data := resolveImageForOllama(server.URL); data != nil {
t.Fatalf("resolveImageForOllama returned data after redirect to blocked internal URL")
}
}
// Graph extraction tells a prose refusal from an answer cut off by num_predict
// through FinishReason, so the non-streaming Chat must carry Ollama's
// done_reason instead of leaving it empty.
func TestOllamaChatPropagatesDoneReason(t *testing.T) {
for _, reason := range []string{"stop", "length"} {
t.Run(reason, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/":
w.WriteHeader(http.StatusOK)
case "/api/tags":
_, _ = fmt.Fprint(w, `{"models":[{"name":"m:latest"}]}`)
case "/api/chat":
_, _ = fmt.Fprintf(w, `{"model":"m","message":{"role":"assistant","content":"Step 1"},`+
`"done":true,"done_reason":%q,"eval_count":3}`, reason)
default:
http.NotFound(w, r)
}
}))
defer server.Close()
t.Setenv("OLLAMA_BASE_URL", server.URL)
t.Setenv("OLLAMA_OPTIONAL", "")
svc, err := ollama.GetOllamaService()
if err != nil {
t.Fatal(err)
}
c := &OllamaChat{modelName: "m", ollamaService: svc}
resp, err := c.Chat(context.Background(), []Message{{Role: "user", Content: "hi"}}, &ChatOptions{})
if err != nil {
t.Fatal(err)
}
if resp.FinishReason != reason {
t.Fatalf("FinishReason = %q, want %q", resp.FinishReason, reason)
}
})
}
}