- 使用 SemanticMemory 索引一组知识片段 - Workflow Agent 在执行时先进行语义检索, 再将检索结果作为上下文交给 LLM Agent 生成回答 注意: 示例默认使用 MockEmbedder + MemoryStore 实现语义记忆, 运行不依赖外部服务。 如果你已经在 agentsdk.yaml 中配置了 pgvector + OpenAI, 可以在实际项目中复用相同配置。
()
| 32 | // 如果你已经在 agentsdk.yaml 中配置了 pgvector + OpenAI, 可以在实际项目中复用相同配置。 |
| 33 | |
| 34 | func main() { |
| 35 | ctx := context.Background() |
| 36 | |
| 37 | // 1. 初始化语义记忆: MemoryStore + MockEmbedder |
| 38 | store := vector.NewMemoryStore() |
| 39 | embedder := vector.NewMockEmbedder(16) |
| 40 | semMem := memory.NewSemanticMemory(memory.SemanticMemoryConfig{ |
| 41 | Store: store, |
| 42 | Embedder: embedder, |
| 43 | NamespaceScope: "resource", |
| 44 | TopK: 3, |
| 45 | }) |
| 46 | |
| 47 | // 2. 索引一些百科知识片段 |
| 48 | docs := []struct { |
| 49 | id string |
| 50 | text string |
| 51 | meta map[string]any |
| 52 | }{ |
| 53 | { |
| 54 | id: "doc-paris", |
| 55 | text: "Paris is the capital and most populous city of France.", |
| 56 | meta: map[string]any{"user_id": "alice", "resource_id": "world-facts"}, |
| 57 | }, |
| 58 | { |
| 59 | id: "doc-berlin", |
| 60 | text: "Berlin is the capital city of Germany.", |
| 61 | meta: map[string]any{"user_id": "alice", "resource_id": "world-facts"}, |
| 62 | }, |
| 63 | { |
| 64 | id: "doc-tokyo", |
| 65 | text: "Tokyo is the capital of Japan and one of its 47 prefectures.", |
| 66 | meta: map[string]any{"user_id": "alice", "resource_id": "asia-notes"}, |
| 67 | }, |
| 68 | } |
| 69 | |
| 70 | for _, d := range docs { |
| 71 | if err := semMem.Index(ctx, d.id, d.text, d.meta); err != nil { |
| 72 | log.Fatalf("index %s: %v", d.id, err) |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | // 3. 初始化 Agent 依赖 (与 examples/server-http 类似, 但使用内存 Store) |
| 77 | toolRegistry := tools.NewRegistry() |
| 78 | builtin.RegisterAll(toolRegistry) |
| 79 | |
| 80 | memStore := storepkg() |
| 81 | |
| 82 | deps := &agent.Dependencies{ |
| 83 | Store: memStore, |
| 84 | SandboxFactory: sandbox.NewFactory(), |
| 85 | ToolRegistry: toolRegistry, |
| 86 | // 使用多提供商工厂,根据模板中的模型配置选择实际模型。 |
| 87 | // 默认会使用 Anthropic 提供商,因此需要设置 ANTHROPIC_API_KEY。 |
| 88 | ProviderFactory: provider.NewMultiProviderFactory(), |
| 89 | TemplateRegistry: func() *agent.TemplateRegistry { |
| 90 | tr := agent.NewTemplateRegistry() |
| 91 | tr.Register(&types.AgentTemplateDefinition{ |
nothing calls this directly
no test coverage detected