Files
HomeAgent/providers/ollama/generator.go
JianFeeeee f256098c9f refactor: 全面改名为 HologramAgent + 提示词技术内容下沉到 skill/工具描述 + 修 21 处乱码
## ① 全面改名 HomeAgent → HologramAgent

仓库已改名,但代码与文档里仍有大量旧名。本次按"用户能看到的优先"全量替换:

- 用户可见:登录页标题/页脚、默认人格第一句、CLI 状态输出、启动日志、
  plugin_install 的工具描述、AI 图片插件的 User-Agent
- 文档与脚本:README、assets/docs、docs/zh、deploy/*.sh、.github/workflows
- 鸿蒙工程:cmd/ohos/HomeAgent → cmd/ohos/HologramAgent(git mv)
  目录内的 module/app 描述同步;**证书路径原样保留**
  (default_HomeAgent_xxx.cer/p7b/p12 是签名材料的实际文件名,改了会找不到证书)
- 插件元数据:plugin.json 的 author

★ 必须保持原样的两处(改了会坏):
  · legacySeededPromptSignature = "你是 HomeAgent 的看板娘「小宅」…"
    —— 那是识别历史播种人格卡的**原文锚点**,改了就识别不出旧数据
  · 公开 SDK 的 ProxyAuthHomeAgent = "homeagent"
    —— 那是 SDK 契约里的值,属独立仓库,本仓不改

## ② 修 21 处乱码(U+FFFD)

这些是历史编辑留下的编码破坏,全在注释里,例如:
  「赌注重下���遍」→「赌注重下一遍」
  「「不��滤」」  →「「不过滤」」
  「**待��退场**」→「**待退场**」

★ 保留 providers/chineseclip/tokenizer.go 里的 2 处:那是**故意**用
  U+FFFD 演示"非法 UTF-8 字节被归一成 U+FFFD",不是乱码。

## ③ 提示词技术内容下沉(用户:技术性内容应该收敛到 skill 与 -help 中)

实测系统提示词 2309 字,其中两段几乎全是**模型无法据以行动的实现细节**:

  【工具执行顺序】1272 字(ParallelSafe 声明、批内降级、batchRunnable 判据…)
  【三层记忆】   1069 字(L1/L2/L3 编号、消费式删除、向量空间、指纹…)

收敛后 **2309 → 1723 字(-25%)**,保留的全是"模型据此做什么不同的事":

  工具顺序:默认并行 / 不要依赖先后 / 同通道保序 / 写类工具可能串行
  三层记忆:时序里能看最近 / doc_query 把历史事件按原始时间戳插回时序 /
           关系用 memory_recall / 成文知识用 knowledge_search

判断口径写进判据:新加一段提示词前先问"模型会据此做什么不同的事",
答不上来就该进 skill 或工具描述。

## 判据

prompt_memory_test.go 新增 2 条:
- TestSystemPromptHasNoImplementationJargon
  黑名单:ParallelSafe / batchRunnable / 消费式 / DenseCosine / fingerprint /
  向量空间 / 批内降级 / 自激
- TestSystemPromptStaysCompact:上限 2000 字(当前 1723)

变异:把 "ParallelSafe 声明、批内降级" 加回工具顺序段 ⇒ 第一条立刻红。

## 验证

- go build ./... / go vet ./... 干净
- go test ./... -count=1:58 包 0 失败
- make check-client-versions:客户端与内核版本一致
2026-10-22 20:49:44 +08:00

213 lines
6.8 KiB
Go

// Package ollamagen implements the generation.Provider SPI over a local Ollama
// HTTP endpoint.
//
// It lives outside the HologramAgent core: the core depends only on pkg/generation
// and selects this provider by name through configuration. Prompt rendering,
// JSON-schema constraint, sampling, and the Ollama wire format are all owned
// here.
//
// Why Ollama rather than an in-process ONNX runtime for generation: the
// distillation path runs on a 30-minute timer, not the request hot path, so a
// local HTTP round-trip is acceptable; and the structured-output constraint
// (format=<schema>) that makes a 1.7B model usable for triple extraction is a
// first-class Ollama feature. Measured on this host: qwen3:1.7b with a JSON
// schema produced 30/30 field pairs with 0 hallucinations across 6 real
// records of varied structure, versus free-form prompting which either emitted
// chat filler (0 parsed pairs) or replayed few-shot example answers (100%
// hallucination on structurally-dissimilar records).
package ollamagen
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"github.com/JianFeeeee/HologramAgent/pkg/generation"
)
const (
defaultEndpoint = "http://localhost:11434/api/generate"
defaultModel = "qwen3:1.7b"
defaultKeepAlive = "30m"
defaultThreads = 10
defaultTimeout = 240 * time.Second
)
func init() {
generation.Register("ollama", func(cfg generation.Config) (generation.Provider, error) {
return New(cfg)
})
}
// Provider talks to a local Ollama server over HTTP.
type Provider struct {
endpoint string
model string
keepAlive string
threads int
numCtx int
timeout time.Duration
client *http.Client
}
// New builds a provider from options. Recognized options:
//
// endpoint Ollama generate URL (default http://localhost:11434/api/generate)
// model model tag (default qwen3:1.7b)
// keep_alive model residency hint (default 30m) — avoids per-call reload
// num_thread CPU threads (default 10) — critical: the Ollama default badly
// under-threads on this 12-core host (0.1 tok/s vs 2-3 tok/s)
// num_ctx context window in tokens (default 1024)
// timeout_sec per-request timeout seconds (default 240)
func New(cfg generation.Config) (*Provider, error) {
p := &Provider{
endpoint: optString(cfg, "endpoint", defaultEndpoint),
model: optString(cfg, "model", defaultModel),
keepAlive: optString(cfg, "keep_alive", defaultKeepAlive),
threads: optInt(cfg, "num_thread", defaultThreads),
numCtx: optInt(cfg, "num_ctx", 1024),
timeout: time.Duration(optInt(cfg, "timeout_sec", int(defaultTimeout/time.Second))) * time.Second,
}
if p.model == "" {
return nil, fmt.Errorf("ollamagen: model is empty")
}
p.client = &http.Client{Timeout: p.timeout}
return p, nil
}
type genRequest struct {
Model string `json:"model"`
Prompt string `json:"prompt"`
Stream bool `json:"stream"`
Think bool `json:"think"`
KeepAlive string `json:"keep_alive,omitempty"`
Format json.RawMessage `json:"format,omitempty"`
Options genOptions `json:"options"`
}
type genOptions struct {
Temperature float64 `json:"temperature"`
NumPredict int `json:"num_predict"`
NumCtx int `json:"num_ctx"`
NumThread int `json:"num_thread"`
Stop []string `json:"stop,omitempty"`
}
type genResponse struct {
Response string `json:"response"`
Done bool `json:"done"`
DoneReason string `json:"done_reason"`
Error string `json:"error"`
}
// Generate runs one non-streaming completion.
//
// When req.JSONSchema is set it is passed through as Ollama's `format` field,
// which constrains decoding to that schema. This is the mechanism that makes a
// small model reliable for structured extraction; without it the model emits
// prose. Unlike a provider that cannot honor a schema, this one does — so it
// never returns ErrSchemaUnsupported.
func (p *Provider) Generate(ctx context.Context, req generation.Request) (generation.Response, error) {
maxTokens := req.MaxTokens
if maxTokens <= 0 {
maxTokens = 256
}
body := genRequest{
Model: p.model,
Prompt: req.Prompt,
Stream: false,
Think: false,
KeepAlive: p.keepAlive,
Options: genOptions{
Temperature: req.Temperature,
NumPredict: maxTokens,
NumCtx: p.numCtx,
NumThread: p.threads,
Stop: req.Stop,
},
}
if s := strings.TrimSpace(req.JSONSchema); s != "" {
// Ollama accepts either the literal string "json" or a schema object.
// A caller-supplied schema is passed verbatim; it must be valid JSON.
if !json.Valid([]byte(s)) {
return generation.Response{}, fmt.Errorf("ollamagen: JSONSchema is not valid JSON")
}
body.Format = json.RawMessage(s)
}
payload, err := json.Marshal(body)
if err != nil {
return generation.Response{}, fmt.Errorf("ollamagen: marshal request: %w", err)
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, p.endpoint, bytes.NewReader(payload))
if err != nil {
return generation.Response{}, fmt.Errorf("ollamagen: build request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
resp, err := p.client.Do(httpReq)
if err != nil {
return generation.Response{}, fmt.Errorf("ollamagen: request %s: %w", p.model, err)
}
defer resp.Body.Close()
raw, err := io.ReadAll(resp.Body)
if err != nil {
return generation.Response{}, fmt.Errorf("ollamagen: read response: %w", err)
}
if resp.StatusCode != http.StatusOK {
return generation.Response{}, fmt.Errorf("ollamagen: http %d: %s", resp.StatusCode, truncate(string(raw), 200))
}
var out genResponse
if err := json.Unmarshal(raw, &out); err != nil {
return generation.Response{}, fmt.Errorf("ollamagen: decode response: %w", err)
}
if out.Error != "" {
return generation.Response{}, fmt.Errorf("ollamagen: model error: %s", out.Error)
}
return generation.Response{
Text: out.Response,
Truncated: out.DoneReason == "length",
}, nil
}
// Info reports the model id and that schema-constrained output is supported.
func (p *Provider) Info() generation.Info {
return generation.Info{Model: p.model, SupportsJSONSchema: true}
}
// Close is a no-op: the HTTP client holds no persistent model state. Residency
// is governed by the server's keep_alive, not this process.
func (p *Provider) Close() {}
func optString(cfg generation.Config, key, def string) string {
if v, ok := cfg.Options[key]; ok && strings.TrimSpace(v) != "" {
return v
}
return def
}
func optInt(cfg generation.Config, key string, def int) int {
if v, ok := cfg.Options[key]; ok {
if n, err := strconv.Atoi(strings.TrimSpace(v)); err == nil && n > 0 {
return n
}
}
return def
}
func truncate(s string, n int) string {
if len(s) <= n {
return s
}
return s[:n] + "…"
}