
Genkit Dart Agent Artifacts 實戰指南會話級交付物的生產、流轉與消費【免費下載鏈接】skillsAgent Skills for Google products and technologies項目地址: https://gitcode.com/GitHub_Trending/skills29/skills導讀在 Genkit Dart 的 Agent 體系中**Artifact產物**是 Agent 在一次會話期間產生的具名、帶內容的交付物——例如生成的代碼文件、報告、詩歌等它們存活于會話狀態中隨對話流轉并流式同步到客戶端。本文基于 skills/cloud/genkit-dart 技能庫中的 agents-artifacts.md 參考文檔系統講解如何為模型提供write_artifact/read_artifact工具、Artifact 的底層流動機制與去重規則、服務端與客戶端的讀寫 API以及多智能體編排下的產物合并策略。讀完本文你將能夠為 Dart / Flutter 中的 Genkit Agent 完整實現會話級產物能力并清楚區分它與filesystem()磁盤工作區的適用邊界。閱讀前置Artifact 是 Agent 會話狀態的一部分建議先閱讀 agents.md 了解 Agent 基礎涉及Schema()等類型安全機制時可參考 schemantic.md。一、Artifact 是什么會話級交付物的定位按 agents-artifacts.md 的定義Artifacts是 Agent 在一次會話期間產生的具名、內容承載的交付物——文件、報告、代碼等都屬于此類。它們有兩個關鍵特性存活于會話狀態中Artifact 隨會話狀態SessionState一起被保存、流轉并流式同步到客戶端。從 agents-sessions.md 可以看到SessionState由messages、custom自定義狀態和artifacts三部分組成Artifact 正是其中的第一等公民。按名稱去重同一個會話中寫入相同name的 Artifact 會被替換見下文流動機制因此一個 Artifact 名稱在會話中唯一。在服務端Artifact 通過響應對象暴露res.artifactsListArtifact在客戶端通過chat.artifacts追蹤整個會話累積的所有 Artifact。API 分布如下Artifact類型與ai.currentSession()/session.addArtifacts()/session.getArtifacts()來自package:genkit/genkit.dart服務端瀏覽器 / HTTP 客戶端能力來自package:genkit/client.dartremoteAgent。1.1 與 Agent 會話模型的關系從 agents.md 可知Agent 是在 prompt tools 之上構建的持久化多輪對話原語相比裸的ai.generate循環增加了Sessions以不可變快照snapshot形式記錄的多輪歷史State類型化的會話狀態消息 自定義數據 產物Interrupts人在回路中的暫停/恢復Branching從任意快照分叉對話Detaching后臺運行輪次并輪詢結果。Artifact 正是 State 中產物維度的核心承載也是這些能力組合下最常用的數據形態之一。二、會話級 Artifact 與磁盤文件的取舍agents-artifacts.md 明確指出了兩種互補的工作模式務必在動手前先做區分維度會話級 Artifactfilesystem()中間件數據位置會話狀態內隨對話流轉、流式推送到客戶端磁盤上的真實文件沙箱工作區生存周期會話生命周期內持久化落盤用途會話范圍的交付物代碼、報告、詩歌等持久的磁盤工作讀寫文件、搜索替換工具自定義write_artifact/read_artifact內置list_files/read_file/write_file/search_and_replacefilesystem()中間件來自package:genkit_middleware/filesystem.dart用法為filesystem(rootDirectory: ...)由FilesystemPlugin()提供運行時支撐。它會為模型注入一組根目錄受限的文件工具——list_files、read_file、write_file、search_and_replace參見 genkit_middleware.md。兩套能力是互補的會話級 Artifact適合對話范圍內的交付物隨聊天流式到達客戶端例如 Flutter UI 實時渲染filesystem()適合需要持久落盤、跨會話保留的工作區操作。重要限制Dart 目前尚無artifacts()中間件SKILL.md 與 agents-artifacts.md 均明確說明。因此不能像其他語言一樣一行掛載中間件而需要直接在會話 Artifact APIai.currentSession().addArtifacts()/getArtifacts()之上自行定義write_artifact/read_artifact工具。三、為模型提供 Artifact 工具完整實現本節給出 agents-artifacts.md 中的完整可運行示例并補充必要的實現細節說明。3.1 定義輸入 Schemaschemantic由于工具入參需要類型安全的 JSON Schema必須使用schemantic庫聲明抽象 Schema 類$前綴 Schema()注解再通過代碼生成得到帶$schema的實體類。相關依賴安裝與生成命令可參考 schemantic.mddart pub add schemantic dart pub add dev:schemantic_builder dart pub add dev:build_runner # 生成 .g.dart注意缺少 schemantic_builder 時會成功但輸出 0 個文件 dart run build_runner buildimport package:genkit/genkit.dart; import package:schemantic/schemantic.dart; import genkit.dart; part workspace_agent.g.dart; Schema() abstract class $WriteArtifactInput { Field(description: The name (e.g. filename) of the artifact.) String get name; Field(description: The full content of the artifact.) String get content; } Schema() abstract class $ReadArtifactInput { Field(description: The name of the artifact to read.) String get name; }Field(description: ...)中的描述會被模型看到用于引導模型正確傳參——例如write_artifact要求把文件名放進name、把完整內容放進content這一約定必須在工具描述里反復強調。3.2 定義write_artifact與read_artifact工具核心邏輯圍繞ai.currentSession()展開寫入用session.addArtifacts(...)讀取用session.getArtifacts()final writeArtifact ai.defineTool( name: write_artifact, description: Create or overwrite a named artifact (e.g. a file). Pass the filename as name and the full content as content., inputSchema: WriteArtifactInput.$schema, outputSchema: SchemanticType.string(), fn: (input, _) async { final session ai.currentSession()!; session.addArtifacts([ Artifact(name: input.name, parts: [TextPart(text: input.content)]), ]); return Wrote artifact ${input.name}.; }, ); final readArtifact ai.defineTool( name: read_artifact, description: Read the content of a previously created artifact by name., inputSchema: ReadArtifactInput.$schema, outputSchema: SchemanticType.string(), fn: (input, _) async { final session ai.currentSession()!; final match session.getArtifacts().where((a) a.name input.name); if (match.isEmpty) return Artifact ${input.name} not found.; return match.first.parts.map((p) p.text ?? ).join(); }, );實現要點寫工具session.addArtifacts([Artifact(name: ..., parts: [TextPart(text: ...)])])——Artifact 的內容放在parts中此處使用文本部件TextPart讀工具按name在session.getArtifacts()中過濾未命中時返回明確的not found提示模型會據此決定是否重新生成命中時把parts中的文本拼回完整內容輸出 Schema兩個工具都返回SchemanticType.string()即純字符串的工具結果便于模型理解。3.3 組裝 Agentfinal workspaceAgent ai.defineAgent( name: workspaceAgent, system: You are a code generation assistant. Use write_artifact to create files (pass the filename as name and the full content as content). Use read_artifact to review or modify a previously created file., tools: [writeArtifact, readArtifact], use: [retry()], store: InMemorySessionStore(), );此處值得注意的點結合 agents.md 的defineAgent選項說明system提示詞再次強化了工具使用約定是提升工具調用準確率的關鍵use: [retry()]掛載了核心包自帶的retry()中間件用于模型瞬時錯誤的自動重試RetryPlugin需注冊在Genkit實例上store: InMemorySessionStore()讓服務端持有會話Artifact 隨快照持久化若不設store則會話狀態由客戶端全權管理、每次輪次自動往返二者都支持 Artifact見 agents-sessions.md。四、Artifacts 的流動機制事件、流式塊與按名稱去重agents-artifacts.md 對底層機制做了精煉說明向會話添加 Artifact 會發出一個事件Agent 運行時將其轉發給客戶端表現為流中的artifactstream chunkArtifact按名稱去重deduplicated by name——再次寫入同名 Artifact 會直接替換舊值不會累積。這意味著客戶端可以在輪次尚未結束時就實時收到產物例如邊生成邊渲染文件內容而最終響應中的res.artifacts是本次輪次產出的完整集合。服務端運行一次會話即可驗證final chat workspaceAgent.chat(); final res await chat.send(text: Write poem.txt with a poem about Genkit); print(res.artifacts); // ListArtifact由于按名稱去重若同一輪內模型先寫了poem.txt再重寫poem.txt最終res.artifacts中只有一份后者覆蓋前者。這也解釋了write_artifact描述中 Create oroverwrite 的語義來源。五、Artifact 的類型形狀name partsArtifact 的內容承載在parts部件列表中name與metadata在類型上可選但實踐上必須始終設置name去重與讀取都依賴它// An artifacts content lives in parts (text parts). name and metadata // are optional on the type but you should always set name. final artifact Artifact( name: poem.txt, parts: [TextPart(text: Roses are red…)], );parts的設計為未來擴展非文本部件如圖片、二進制塊預留了空間當前文檔中使用的TextPart通過text字段攜帶內容客戶端可通過p.text讀取。六、程序化訪問在工具與自定義 Agent 內部讀寫 Artifact在工具函數或自定義 Agent 內部通過活動會話active session訪問 Artifact。注意ai.currentSession()在沒有活動會話時返回null因此只能在 Agent 輪次內調用即工具執行期間否則需要判空處理final session ai.currentSession()!; // Read all artifacts: final all session.getArtifacts(); // ListArtifact final found all.where((a) a.name poem.txt).firstOrNull; // Create / replace artifacts: session.addArtifacts([ Artifact(name: notes.md, parts: [TextPart(text: # Notes)]), ]);這兩組 APIgetArtifacts()/addArtifacts()正是第三節中read_artifact/write_artifact兩個工具的底層實現也是自定義 Agent如defineCustomAgent需要直接面對的原語。結合 agents-sessions.md 可以看到Artifact 隨快照一起被SessionStore持久化內存 / 文件 / Firestore 三種實現因此換輪次后依然可讀。七、客戶端讀取 Artifact流式與累積兩種形態瀏覽器 / Dart 客戶端含 Flutter通過package:genkit/client.dart的remoteAgent消費 Agent。Artifact 在客戶端有三個暴露點chat.artifacts整個會話追蹤到的全部 Artifact跨輪次累積res.artifacts本次輪次產出的 Artifactchunk.artifact流式塊中實時到達的單條 Artifact。import package:genkit/client.dart; final agent remoteAgent(url: /api/workspaceAgent); final chat agent.chat(); final turn chat.sendStream(text: Create index.html and styles.css); await for (final chunk in turn.stream) { final artifact chunk.artifact; if (artifact ! null) { // artifact.name, artifact.parts — render/store it live. } } final res await turn.response; print(res.artifacts); // artifacts produced this turn print(chat.artifacts); // all artifacts tracked for the session在 Flutter 場景中參見 agents.md 的 Flutter 小節這一能力與流式文本一樣可接入setState實時渲染Artifact、中斷interrupts、自定義狀態custom state在 Flutter 端與服務端行為完全一致。服務端可通過 agents-deployment.md 中介紹的genkit_shelf將workspaceAgent.action暴露為/api/workspaceAgent之類的 HTTP 端點。八、多智能體場景子 Agent 產物如何匯入父會話在 agents-multi-agent.md 描述的多智能體編排中agents()委派中間件支持把子 Agent 的 Artifact 合并進父會話由artifactStrategy選項控制策略行為inline默認產物內容直接包含在委派工具結果中模型可直接看到并且合并進父會話session僅合并進父會話工具結果只列出產物名稱而非內容合并產物以調用 id 命名空間化鍵形如invocationId/nameinline適合父 Agent 需要閱讀子 Agent 產物內容以便綜合決策的場景內容可見但會占用上下文session適合只希望產物沉淀到會話、父 Agent 按需讀取的場景。委派中間件的其他選項agents、toolPrefix、maxDelegations、historyLength詳見 agents-multi-agent.md。九、最佳實踐與注意事項綜合 agents-artifacts.md 與整個 skills/cloud/genkit-dart 技能庫落地 Artifact 能力時建議遵循以下實踐先判場景再選機制會話內交付物代碼、報告、詩歌等用 Artifact需要落盤、跨會話持久的工作區操作用filesystem(rootDirectory: ...)二者互補而非互斥。在工具描述與 system prompt 中雙重強化參數約定write_artifact要求name傳文件名、content傳完整內容模型越明確越不容易誤用。ai.currentSession()只能在 Agent 輪次內調用沒有活動會話時返回null在工具外部使用必須判空。始終設置name雖然類型上可選但去重、讀取、客戶端追蹤全部依賴它。利用按名稱去重實現覆蓋寫模型對同一文件迭代修改時重復調用write_artifact同名即可無需先刪除。配合會話持久化需要服務端持有 Artifact 歷史時配置storeInMemorySessionStore/FileSessionStore/FirestoreSessionStore多智能體需要產物匯總時配置artifactStrategy。開發期用 Genkit CLI 校驗通過genkit start -- dart run main.dart啟動并捕獲 trace再用genkit trace:get traceId查看工具調用與模型 I/O可直觀驗證write_artifact/read_artifact是否被正確調用參見 SKILL.md 的 Genkit CLI 章節。十、小結Artifact 是 Genkit Dart Agent 會話狀態中的一等公民它以命名 內容的形式承載 Agent 交付物按名稱去重隨事件流式同步到客戶端并可通過服務端會話 API 程序化讀寫。由于 Dart 暫無artifacts()中間件標準做法是在ai.currentSession().addArtifacts()/getArtifacts()之上自定義write_artifact/read_artifact工具——本文給出的完整示例可直接復制運行。結合filesystem()處理持久磁盤工作、agents()中間件的artifactStrategy處理多智能體產物匯總即可在 Dart / Flutter 應用中構建完整的生產 → 流轉 → 消費產物鏈路。【免費下載鏈接】skillsAgent Skills for Google products and technologies項目地址: https://gitcode.com/GitHub_Trending/skills29/skills創作聲明:本文部分內容由AI輔助生成(AIGC),僅供參考