工件(Artifacts)¶
在 ADK 中, 工件(Artifacts) 这些机制对于管理具有名称和版本信息的二进制数据至关重要;这些数据既可以与特定的用户交互会话相关联,也可以在多个会话中持续地与用户相关联。它们使您的代理程序和工具能够处理不仅仅是简单的文本字符串的数据,从而支持更丰富的交互方式(例如涉及文件、图像、音频以及其他二进制格式的数据)。
注意:
这些基本类型(primitives)的具体参数或方法名称可能会因所使用的 SDK 语言的不同而略有差异(例如: save_artifact 在 Python 中, saveArtifact (在 Java 中)。有关详细信息,请参阅特定于该语言的 API 文档。
什么是“Artifacts”(工件/产物)?¶
-
定义: “Artifact”本质上是一段二进制数据(例如文件的内容),它通过一个唯一的标识符来被区分。
filename字符串存在于特定的范围内(会话或用户范围内)。每次您使用相同的文件名保存某个数据时,都会创建一个新的版本。 -
**表示方式(Representation):** 这些“工件”(Artifacts)始终使用标准格式进行表示。
google.genai.types.Part对象。核心数据通常存储在该对象的嵌入式数据结构中。Part(通过……访问)inline_data),其中又包含:data:原始的二进制数据(以字节形式表示)。mime_type:一个字符串,用于表示数据的类型(例如:"image/png","application/pdf"这一点对于后续正确解读数据至关重要。
# Example of how an artifact might be represented as a types.Part
import google.genai.types as types
# Assume 'image_bytes' contains the binary data of a PNG image
image_bytes = b'\x89PNG\r\n\x1a\n...' # Placeholder for actual image bytes
image_artifact = types.Part(
inline_data=types.Blob(
mime_type="image/png",
data=image_bytes
)
)
# You can also use the convenience constructor:
# image_artifact_alt = types.Part.from_bytes(data=image_bytes, mime_type="image/png")
print(f"Artifact MIME Type: {image_artifact.inline_data.mime_type}")
print(f"Artifact Data (first 10 bytes): {image_artifact.inline_data.data[:10]}...")
import {createPartFromBase64, type Part} from '@google/genai';
// Assume 'imageBytes' contains the binary data of a PNG image.
const imageBytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
// Using Buffer.from(bytes).toString('base64') for Node.js environments.
const imageArtifact: Part = createPartFromBase64(
Buffer.from(imageBytes).toString('base64'),
'image/png',
);
console.log(`Artifact MIME Type: ${imageArtifact.inlineData?.mimeType}`);
// Note: Accessing raw bytes would require decoding from base64.
import (
"log"
"google.golang.org/genai"
)
// Create a byte slice with the image data.
imageBytes, err := os.ReadFile("image.png")
if err != nil {
log.Fatalf("Failed to read image file: %v", err)
}
// Create a new artifact with the image data.
imageArtifact := &genai.Part{
InlineData: &genai.Blob{
MIMEType: "image/png",
Data: imageBytes,
},
}
log.Printf("Artifact MIME Type: %s", imageArtifact.InlineData.MIMEType)
log.Printf("Artifact Data (first 8 bytes): %x...", imageArtifact.InlineData.Data[:8])
import com.google.genai.types.Part;
import java.nio.charset.StandardCharsets;
public class ArtifactExample {
public static void main(String[] args) {
// Assume 'imageBytes' contains the binary data of a PNG image
byte[] imageBytes = {(byte) 0x89, (byte) 0x50, (byte) 0x4E, (byte) 0x47, (byte) 0x0D, (byte) 0x0A, (byte) 0x1A, (byte) 0x0A, (byte) 0x01, (byte) 0x02}; // Placeholder for actual image bytes
// Create an image artifact using Part.fromBytes
Part imageArtifact = Part.fromBytes(imageBytes, "image/png");
System.out.println("Artifact MIME Type: " + imageArtifact.inlineData().get().mimeType().get());
System.out.println(
"Artifact Data (first 10 bytes): "
+ new String(imageArtifact.inlineData().get().data().get(), 0, 10, StandardCharsets.UTF_8)
+ "...");
}
}
fun artifactRepresentationExample() {
// Assume 'imageBytes' contains the binary data of a PNG image
val imageBytes = byteArrayOf(0x89.toByte(), 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A)
val imageArtifact =
Part(
inlineData =
Blob(
mimeType = "image/png",
data = imageBytes,
),
)
println("Artifact MIME Type: ${imageArtifact.inlineData?.mimeType}")
println("Artifact Data (first 8 bytes): ${imageArtifact.inlineData?.data?.take(8)}")
}
- 持久性(Persistence)与管理(Management): 这些“工件”(Artifacts)并不会直接存储在代理(agent)或会话状态(session state)中。它们的存储与检索过程是由专门的系统或机制来管理的。 Artifact Service (一种实现方式)
BaseArtifactService在……中定义的google.adk.artifactsADK 提供了多种实现方式,例如:- 一种用于测试或临时存储的内存服务(例如:
InMemoryArtifactService在 Python 中,这些内容是在……(in Python, these contents are defined in……)google.adk.artifacts.in_memory_artifact_service.py). - 这是一个用于使用 Google Cloud Storage (GCS) 进行持久化数据存储的服务(例如:
GcsArtifactService在 Python 中,这些内容是在……(in Python, these contents are defined in……)google.adk.artifacts.gcs_artifact_service.py). - 这是一种将生成的艺术品(artifacts)持久化到本地文件系统目录中的服务。
FileArtifactService在 Kotlin 中,该函数仅接受一个参数(即基础目录)。当你保存数据时,所选的服务实现会自动处理版本控制相关的问题。
- 一种用于测试或临时存储的内存服务(例如:
为什么使用“Artifacts”(工件/生成物)?¶
在会话期间(While the session is active)… state Artifacts 适用于存储少量的配置信息或对话上下文数据(例如字符串、数字、布尔值,或者小型字典/列表);而其他类型的存储解决方案则更适合处理二进制数据或大型数据。
- 处理非文本数据: 可以轻松存储和检索图片、音频片段、视频片段、PDF文件、电子表格,或任何与您的代理工作相关的其他文件格式。
- 如何持久化存储大量数据: 会话状态(session state)通常并不适合用于存储大量数据。Artifacts 提供了一种专门用于存储较大数据块的机制,从而避免会话状态被数据冗余所占用(即避免会话状态变得混乱)。
- 用户文件管理: 为用户提供上传文件的功能(这些文件可以保存为“工件”),以及检索或下载由代理生成的文件(这些文件是从“工件”中加载的)。
- 共享输出结果: 启用相关工具或代理程序,以生成二进制格式的输出文件(例如 PDF 报告或生成的图片),这些文件可以直接保存下来。
save_artifact之后,应用程序的其他部分甚至可以在后续会话中(如果使用了用户名空间管理功能)访问这些数据。 - 缓存二进制数据: 将那些计算成本较高、会产生二进制数据(例如渲染复杂的图表图像)的操作的结果保存为“工件”(artifacts),以避免在后续请求中再次生成这些数据。
从本质上讲,每当您的代理需要处理类似文件的二进制数据时(这些数据需要被持久化、版本控制或共享),这些数据就会由 Artifacts 管理系统来处理。 ArtifactService 这些机制是否属于 ADK(Android Development Kit)中的合适组成部分?
常见使用场景¶
这些“工件”(Artifacts)为在您的 ADK(Android Development Kit)应用程序中处理二进制数据提供了一种灵活的方式。
以下是一些典型的场景,在这些场景中,它们能够发挥重要作用(即展现出其价值):
-
生成的报告/文件:
- 该工具或代理会生成一份报告(例如:PDF格式的分析报告、CSV格式的数据导出文件,或包含图像和图表的文档)。
-
处理用户上传的内容:
- 用户通过前端界面上传文件(例如,用于分析的图片或用于摘要生成的文档)。
-
存储中间二进制结果:
- 该代理执行一个复杂的多步骤流程;其中每个步骤都会生成中间二进制数据(例如音频合成结果、仿真结果等)。
-
持久用户数据(Persistent User Data):
- 用于存储用户特定的配置信息或数据;这些信息/数据并非简单的键值对形式(即不属于简单的键值结构)。
-
缓存生成的二进制内容:
- 某个代理程序经常会根据某些输入(例如公司标志图像、标准的音频问候语)生成相同的二进制输出文件。
核心概念¶
要理解这些“工件”(artifacts),需要掌握几个关键组成部分:管理它们的服务、用于存储它们的数据结构,以及它们是如何被识别和版本控制的。
Artifact Service(BaseArtifactService)¶
-
角色: 该组件的核心功能是负责实际的数据存储与检索逻辑(即如何将数据保存到系统中,以及如何从系统中读取数据)。它还定义了相关的规则和流程。 如何;怎样 和 where 这些“artifacts”(即生成的结果或数据)会被永久保存下来。
-
接口(Interface): 由该抽象基类定义。
BaseArtifactService任何具体的实现都必须提供以下方法:Save Artifact:用于存储工件数据,并返回其被分配的版本号。Load Artifact:检索某个特定版本(或最新版本)的工件(artifact)。List Artifact keys:列出给定范围内所有工件的唯一文件名。Delete Artifact:删除一个工件(根据实现方式,可能会删除该工件的所有版本)。List versions:列出特定工件文件名的所有可用版本号。List artifact versions和Get artifact version在 Python 中,这些函数会返回相应的值。ArtifactVersion元数据(metadata)包含了版本号(version number)、规范的 URI(canonical URI)、MIME 类型(MIME type)、创建时间(creation time)以及自定义元数据(custom metadata),而不是实际的数据内容(artifact payload)。
-
配置: 在初始化时,您需要提供一个名为“artifact service”的服务的实例。
Runner例如:InMemoryArtifactService,GcsArtifactService,或FileArtifactService在 Kotlin 中。Runner然后通过该方式,将该服务提供给代理程序和工具使用。InvocationContext.
from google.adk.runners import Runner
from google.adk.artifacts import InMemoryArtifactService # Or GcsArtifactService
from google.adk.agents import LlmAgent # Any agent
from google.adk.sessions import InMemorySessionService
# Example: Configuring the Runner with an Artifact Service
my_agent = LlmAgent(name="artifact_user_agent", model="gemini-flash-latest")
artifact_service = InMemoryArtifactService() # Choose an implementation
session_service = InMemorySessionService()
runner = Runner(
agent=my_agent,
app_name="my_artifact_app",
session_service=session_service,
artifact_service=artifact_service # Provide the service instance here
)
# Now, contexts within runs managed by this runner can use artifact methods
import {
InMemoryArtifactService,
InMemorySessionService,
LlmAgent,
Runner,
} from '@google/adk';
// Example: Configuring the Runner with an Artifact Service
const myAgent = new LlmAgent({
name: 'artifact_user_agent',
model: 'gemini-flash-latest',
});
const artifactService = new InMemoryArtifactService();
const sessionService = new InMemorySessionService();
const runner = new Runner({
agent: myAgent,
appName: 'my_artifact_app',
sessionService: sessionService,
artifactService: artifactService,
});
// Now, contexts within runs managed by this runner can use artifact methods.
import (
"context"
"log"
"google.golang.org/adk/v2/agent/llmagent"
"google.golang.org/adk/v2/artifact"
"google.golang.org/adk/v2/model/gemini"
"google.golang.org/adk/v2/runner"
"google.golang.org/adk/v2/session"
"google.golang.org/genai"
)
// Create a new context.
ctx := context.Background()
// Set the app name.
const appName = "my_artifact_app"
// Create a new Gemini model.
model, err := gemini.NewModel(ctx, "gemini-2.5-flash", &genai.ClientConfig{})
if err != nil {
log.Fatalf("Failed to create model: %v", err)
}
// Create a new LLM agent.
myAgent, err := llmagent.New(llmagent.Config{
Model: model,
Name: "artifact_user_agent",
Instruction: "You are an agent that describes images.",
BeforeModelCallbacks: []llmagent.BeforeModelCallback{
BeforeModelCallback,
},
})
if err != nil {
log.Fatalf("Failed to create agent: %v", err)
}
// Create a new in-memory artifact service.
artifactService := artifact.InMemoryService()
// Create a new in-memory session service.
sessionService := session.InMemoryService()
// Create a new runner.
r, err := runner.New(runner.Config{
Agent: myAgent,
AppName: appName,
SessionService: sessionService,
ArtifactService: artifactService, // Provide the service instance here
})
if err != nil {
log.Fatalf("Failed to create runner: %v", err)
}
log.Printf("Runner created successfully: %v", r)
import com.google.adk.agents.LlmAgent;
import com.google.adk.runner.Runner;
import com.google.adk.sessions.InMemorySessionService;
import com.google.adk.artifacts.InMemoryArtifactService;
// Example: Configuring the Runner with an Artifact Service
LlmAgent myAgent = LlmAgent.builder()
.name("artifact_user_agent")
.model("gemini-flash-latest")
.build();
InMemoryArtifactService artifactService = new InMemoryArtifactService(); // Choose an implementation
InMemorySessionService sessionService = new InMemorySessionService();
Runner runner = new Runner(myAgent, "my_artifact_app", artifactService, sessionService); // Provide the service instance here
// Now, contexts within runs managed by this runner can use artifact methods
fun configureRunnerExample() {
val myAgent =
LlmAgent(name = "artifact_user_agent", model = Gemini(name = "gemini-flash-latest"))
val artifactService = InMemoryArtifactService()
val sessionService = InMemorySessionService()
val runner =
InMemoryRunner(
agent = myAgent,
appName = "my_artifact_app",
sessionService = sessionService,
artifactService = artifactService,
)
}
工件数据(Artifact Data)¶
-
标准表示法(Standard Representation): Artifact 的内容在全球范围内都使用相同的格式进行表示。
google.genai.types.Part该对象采用了与大型语言模型(LLM)消息的某些部分相同的结构。 -
**关键属性(Key Attribute)**
inline_data): 对于这些“工件”(artifacts)来说,最相关的属性是……inline_data这是一个……(具体内容在文档中未提供)。google.genai.types.Blob包含以下内容的对象:data(bytes该文件的原始二进制内容。mime_type(str): 一个标准的 MIME 类型字符串(例如,'application/pdf','image/png','audio/mpeg')用于描述二进制数据的性质。 在加载该文件时,这一点对于正确理解其内容至关重要。
import google.genai.types as types
# Example: Creating an artifact Part from raw bytes
pdf_bytes = b'%PDF-1.4...' # Your raw PDF data
pdf_mime_type = "application/pdf"
# Using the constructor
pdf_artifact_py = types.Part(
inline_data=types.Blob(data=pdf_bytes, mime_type=pdf_mime_type)
)
# Using the convenience class method (equivalent)
pdf_artifact_alt_py = types.Part.from_bytes(data=pdf_bytes, mime_type=pdf_mime_type)
print(f"Created Python artifact with MIME type: {pdf_artifact_py.inline_data.mime_type}")
import {createPartFromBase64, type Part} from '@google/genai';
// Example: Creating an artifact Part from raw bytes.
const pdfBytes = new Uint8Array([0x25, 0x50, 0x44, 0x46, 0x2d, 0x31, 0x2e, 0x34]);
const pdfMimeType = 'application/pdf';
// Using Buffer.from(bytes).toString('base64') for Node.js environments.
const pdfArtifact: Part = createPartFromBase64(
Buffer.from(pdfBytes).toString('base64'),
pdfMimeType,
);
console.log(`Created TypeScript artifact with MIME Type: ${pdfArtifact.inlineData?.mimeType}`);
import (
"log"
"os"
"google.golang.org/genai"
)
// Load imageBytes from a file
imageBytes, err := os.ReadFile("image.png")
if err != nil {
log.Fatalf("Failed to read image file: %v", err)
}
// genai.NewPartFromBytes is a convenience function that is a shorthand for
// creating a &genai.Part with the InlineData field populated.
// Create a new artifact from the image data.
imageArtifact := genai.NewPartFromBytes([]byte(imageBytes), "image/png")
log.Printf("Artifact MIME Type: %s", imageArtifact.InlineData.MIMEType)
import com.google.genai.types.Blob;
import com.google.genai.types.Part;
import java.nio.charset.StandardCharsets;
public class ArtifactDataExample {
public static void main(String[] args) {
// Example: Creating an artifact Part from raw bytes
byte[] pdfBytes = "%PDF-1.4...".getBytes(StandardCharsets.UTF_8); // Your raw PDF data
String pdfMimeType = "application/pdf";
// Using the Part.fromBlob() constructor with a Blob
Blob pdfBlob = Blob.builder()
.data(pdfBytes)
.mimeType(pdfMimeType)
.build();
Part pdfArtifactJava = Part.builder().inlineData(pdfBlob).build();
// Using the convenience static method Part.fromBytes() (equivalent)
Part pdfArtifactAltJava = Part.fromBytes(pdfBytes, pdfMimeType);
// Accessing mimeType, note the use of Optional
String mimeType = pdfArtifactJava.inlineData()
.flatMap(Blob::mimeType)
.orElse("unknown");
System.out.println("Created Java artifact with MIME type: " + mimeType);
// Accessing data
byte[] data = pdfArtifactJava.inlineData()
.flatMap(Blob::data)
.orElse(new byte[0]);
System.out.println("Java artifact data (first 10 bytes): "
+ new String(data, 0, Math.min(data.length, 10), StandardCharsets.UTF_8) + "...");
}
}
文件名¶
- 标识符: 这是一个简单的字符串,用于在特定的命名空间内为某个“工件”(artifact)命名并检索该工件。
- 唯一性: 文件名在其所属范围内(无论是会话范围还是用户命名空间)必须是唯一的。
- 最佳实践: 请使用描述性强的名称,这些名称可以包含文件扩展名(例如:)。
"monthly_report.pdf","user_avatar.jpg"),尽管该扩展本身并不决定程序的具体行为(即程序应该如何运行)。mime_typedoes.
版本控制(Versioning)¶
- 自动版本控制: 该工件服务会自动处理版本控制相关的工作。当您发起请求时(即调用相关接口时),该服务会自动完成版本的更新或管理等工作。
save_artifact该服务会为该特定的文件名和作用域确定下一个可用的版本号(通常从 0 开始,并逐个递增)。 - 由……返回
save_artifact: Thesave_artifact该方法返回一个整数版本号,该版本号被分配给新保存的工件(artifact)。 - 检索(Retrieval):
load_artifact(..., version=None)(默认值):检索 latest 该工件的可用版本。load_artifact(..., version=N):检索特定版本的信息。N.- 列出版本: The
list_versions`method`(位于服务层面,而非上下文层面)可用于查找某个软件组件的所有现有版本号。对于 ADK Go,请调用……Versions在……上;关于……artifact.Service.
命名空间(会话级 vs. 用户级)¶
-
概念: 这些“工件”(Artifacts)可以被限定在特定的会话(session)范围内,也可以更广泛地应用于用户在该应用程序内的所有会话中。这种范围的划分是由相关设置或规则决定的。
filename该内容由系统内部进行格式化处理。ArtifactService. -
默认值(会话范围): 如果你使用一个普通的文件名(例如:`my_file.txt`),
"report.pdf"该文物与特定的……相关联。app_name,user_id, 和session_id它只能在特定的会话上下文中被访问。 -
用户范围(User Scope):
"user:"(前缀): 如果你在文件名前加上一个前缀……"user:"就像……"user:profile.png"该文物仅与……相关联。app_name和user_id可以从……访问或更新该内容。 任何;任何一个 该用户在应用程序中拥有的会话(session)。 -
商品展示行为: 在 Python 中,从会话中列出相关文件时,会返回属于该会话范围的文件名。 和 该用户的用户级文件名(user-scoped filenames)。
"user:"前缀被保留了下来,例如……["summary.txt", "user:settings.json"].
# Example illustrating namespace difference (conceptual)
# Session-specific artifact filename
session_report_filename = "summary.txt"
# User-specific artifact filename
user_config_filename = "user:settings.json"
# When saving 'summary.txt' via context.save_artifact,
# it's tied to the current app_name, user_id, and session_id.
# When saving 'user:settings.json' via context.save_artifact,
# the ArtifactService implementation should recognize the "user:" prefix
# and scope it to app_name and user_id, making it accessible across sessions for that user.
// Example illustrating namespace difference (conceptual)
// Session-specific artifact filename
const sessionReportFilename = "summary.txt";
// User-specific artifact filename
const userConfigFilename = "user:settings.json";
// When saving 'summary.txt' via context.saveArtifact, it's tied to the current appName, userId, and sessionId.
// When saving 'user:settings.json' via context.saveArtifact, the ArtifactService implementation recognizes the "user:" prefix and scopes it to appName and userId, making it accessible across sessions for that user.
import (
"log"
)
// Note: Namespacing is only supported when using the GCS ArtifactService implementation.
// A session-scoped artifact is only available within the current session.
sessionReportFilename := "summary.txt"
// A user-scoped artifact is available across all sessions for the current user.
userConfigFilename := "user:settings.json"
// When saving 'summary.txt' via ctx.Artifacts().Save,
// it's tied to the current app_name, user_id, and session_id.
// ctx.Artifacts().Save(sessionReportFilename, *artifact);
// When saving 'user:settings.json' via ctx.Artifacts().Save,
// the ArtifactService implementation should recognize the "user:" prefix
// and scope it to app_name and user_id, making it accessible across sessions for that user.
// ctx.Artifacts().Save(userConfigFilename, *artifact);
// Example illustrating namespace difference (conceptual)
// Session-specific artifact filename
String sessionReportFilename = "summary.txt";
// User-specific artifact filename
String userConfigFilename = "user:settings.json"; // The "user:" prefix is key
// When saving 'summary.txt' via context.save_artifact,
// it's tied to the current app_name, user_id, and session_id.
// artifactService.saveArtifact(appName, userId, sessionId1, sessionReportFilename, someData);
// When saving 'user:settings.json' via context.save_artifact,
// the ArtifactService implementation should recognize the "user:" prefix
// and scope it to app_name and user_id, making it accessible across sessions for that user.
// artifactService.saveArtifact(appName, userId, sessionId1, userConfigFilename, someData);
这些核心概念共同作用,为在 ADK 框架内管理二进制数据提供了一个灵活的系统。
通过上下文对象与工件进行交互¶
在代理的逻辑中(特别是在回调函数或工具中),与各种“工件”(artifacts)进行交互的主要方式是通过这些工件所提供的方法来实现的。 CallbackContext 和 ToolContext `objects`。这些方法抽象出了底层存储的细节(即由存储系统管理的具体存储机制),使得开发者无需关心这些细节。 ArtifactService.
(注意:在 Python 和 TypeScript 中,……) CallbackContext 和 ToolContext 这些内容被统一成了一个整体。 Context 在 Python 中,这两个名称仍然可以作为该类型的别名来使用。
先决条件:配置相关设置。 ArtifactService¶
在通过上下文对象使用任何工件(artifact)的方法之前,你需要先完成一些准备工作。 必须;应当 提供一个……的实例。 BaseArtifactService 实现方式;具体执行细节 (就像……一样) InMemoryArtifactService 或者 GcsArtifactService在初始化您的……时 Runner.
在 Python 中,你需要在初始化对象时提供这个实例。 Runner.
from google.adk.runners import Runner
from google.adk.artifacts import InMemoryArtifactService # Or GcsArtifactService
from google.adk.agents import LlmAgent
from google.adk.sessions import InMemorySessionService
# Your agent definition
agent = LlmAgent(name="my_agent", model="gemini-flash-latest")
# Instantiate the desired artifact service
artifact_service = InMemoryArtifactService()
# Provide it to the Runner
runner = Runner(
agent=agent,
app_name="artifact_app",
session_service=InMemorySessionService(),
artifact_service=artifact_service # Service must be provided here
)
artifact_service 已在……中进行了配置。 InvocationContext (如果该参数没有被传递给……,就会发生这种情况。) Runner),然后进行调用(calling)。 save_artifact, load_artifact,或 list_artifacts 在上下文对象(context objects)上进行操作时,会引发一个错误(或异常)。 ValueError.
import {
InMemoryArtifactService,
InMemorySessionService,
LlmAgent,
Runner,
} from '@google/adk';
// Your agent definition.
const agent = new LlmAgent({
name: 'my_agent',
model: 'gemini-flash-latest',
});
// Instantiate the desired artifact service.
const artifactService = new InMemoryArtifactService();
// Provide it to the Runner.
const runner = new Runner({
agent: agent,
appName: 'artifact_app',
sessionService: new InMemorySessionService(),
artifactService: artifactService,
});
// If no artifactService is configured, calling artifact methods on context objects will throw an error.
ArtifactService 该实例不可用(例如: null) 当尝试对某个“artifacts”(可以理解为某种数据对象或资源)进行操作时,通常会导致以下结果: NullPointerException 或者会显示一个自定义的错误信息,具体取决于应用程序的架构。健壮的应用程序通常会使用依赖注入框架来管理服务的生命周期,并确保服务的可用性。
import (
"context"
"log"
"google.golang.org/adk/v2/agent/llmagent"
"google.golang.org/adk/v2/artifact"
"google.golang.org/adk/v2/model/gemini"
"google.golang.org/adk/v2/runner"
"google.golang.org/adk/v2/session"
"google.golang.org/genai"
)
// Create a new context.
ctx := context.Background()
// Set the app name.
const appName = "my_artifact_app"
// Create a new Gemini model.
model, err := gemini.NewModel(ctx, "gemini-2.5-flash", &genai.ClientConfig{})
if err != nil {
log.Fatalf("Failed to create model: %v", err)
}
// Create a new LLM agent.
myAgent, err := llmagent.New(llmagent.Config{
Model: model,
Name: "artifact_user_agent",
Instruction: "You are an agent that describes images.",
BeforeModelCallbacks: []llmagent.BeforeModelCallback{
BeforeModelCallback,
},
})
if err != nil {
log.Fatalf("Failed to create agent: %v", err)
}
// Create a new in-memory artifact service.
artifactService := artifact.InMemoryService()
// Create a new in-memory session service.
sessionService := session.InMemoryService()
// Create a new runner.
r, err := runner.New(runner.Config{
Agent: myAgent,
AppName: appName,
SessionService: sessionService,
ArtifactService: artifactService, // Provide the service instance here
})
if err != nil {
log.Fatalf("Failed to create runner: %v", err)
}
log.Printf("Runner created successfully: %v", r)
在 Java 中,你需要创建一个对象的实例(即实例化该对象)。 BaseArtifactService 首先需要实现该服务,然后确保应用程序中负责管理相关资源(如“artifacts”)的部分能够访问该服务。这通常是通过依赖注入(dependency injection)或显式传递服务实例来实现的。
import com.google.adk.agents.LlmAgent;
import com.google.adk.artifacts.InMemoryArtifactService; // Or GcsArtifactService
import com.google.adk.runner.Runner;
import com.google.adk.sessions.InMemorySessionService;
public class SampleArtifactAgent {
public static void main(String[] args) {
// Your agent definition
LlmAgent agent = LlmAgent.builder()
.name("my_agent")
.model("gemini-flash-latest")
.build();
// Instantiate the desired artifact service
InMemoryArtifactService artifactService = new InMemoryArtifactService();
// Provide it to the Runner
Runner runner = new Runner(agent,
"APP_NAME",
artifactService, // Service must be provided here
new InMemorySessionService());
}
}
在 Kotlin 中,你需要在初始化对象时提供这个实例。 Runner.
fun configureRunnerExample() {
val myAgent =
LlmAgent(name = "artifact_user_agent", model = Gemini(name = "gemini-flash-latest"))
val artifactService = InMemoryArtifactService()
val sessionService = InMemorySessionService()
val runner =
InMemoryRunner(
agent = myAgent,
appName = "my_artifact_app",
sessionService = sessionService,
artifactService = artifactService,
)
}
artifactService 配置已完成,现在正在调用相关功能。 saveArtifact, loadArtifact,或 listArtifacts 如果对上下文对象(context objects)进行操作,将会抛出异常。
访问方法¶
这些与“artifacts”(文物/人工制品)交互的方法可以直接在相应的实例上使用。 CallbackContext (传递给代理和模型的回调函数) ToolContext 在 Go 和 Java 中,这些功能会被传递给相应的工具回调函数(tool callbacks);同时,这些功能也通过统一的接口(unified interface)被提供出来。 Context 在 Python 和 TypeScript 中实现。
保存文物(或艺术品)¶
-
代码示例:
import google.genai.types as types from google.adk.agents.callback_context import CallbackContext # Or ToolContext async def save_generated_report_py(context: CallbackContext, report_bytes: bytes): """Saves generated PDF report bytes as an artifact.""" report_artifact = types.Part.from_bytes( data=report_bytes, mime_type="application/pdf" ) filename = "generated_report.pdf" try: version = await context.save_artifact(filename=filename, artifact=report_artifact) print(f"Successfully saved Python artifact '{filename}' as version {version}.") # The event generated after this callback will contain: # event.actions.artifact_delta == {"generated_report.pdf": version} except ValueError as e: print(f"Error saving Python artifact: {e}. Is ArtifactService configured in Runner?") except Exception as e: # Handle potential storage errors (e.g., GCS permissions) print(f"An unexpected error occurred during Python artifact save: {e}") # --- Example Usage Concept (Python) --- # async def main_py(): # callback_context: CallbackContext = ... # obtain context # report_data = b'...' # Assume this holds the PDF bytes # await save_generated_report_py(callback_context, report_data)import {Context} from '@google/adk'; import {createPartFromBase64, type Part} from '@google/genai'; async function saveGeneratedReport(context: Context, reportBytes: Uint8Array): Promise<void> { /** Saves generated PDF report bytes as an artifact. */ const reportArtifact: Part = createPartFromBase64( Buffer.from(reportBytes).toString('base64'), 'application/pdf', ); const filename = 'generated_report.pdf'; try { const version = await context.saveArtifact(filename, reportArtifact); console.log(`Successfully saved TypeScript artifact '${filename}' as version ${version}.`); } catch (e: any) { console.error( `Error saving TypeScript artifact: ${e.message}. Is ArtifactService configured in Runner?`, ); } }import ( "log" "google.golang.org/adk/v2/agent" "google.golang.org/adk/v2/model" "google.golang.org/genai" ) // saveReportCallback is a BeforeModel callback that saves a report from session state. func saveReportCallback(ctx agent.Context, req *model.LLMRequest) (*model.LLMResponse, error) { // Get the report data from the session state. reportData, err := ctx.State().Get("report_bytes") if err != nil { log.Printf("No report data found in session state: %v", err) return nil, nil // No report to save, continue normally. } // Check if the report data is in the expected format. reportBytes, ok := reportData.([]byte) if !ok { log.Printf("Report data in session state was not in the expected byte format.") return nil, nil } // Create a new artifact with the report data. reportArtifact := &genai.Part{ InlineData: &genai.Blob{ MIMEType: "application/pdf", Data: reportBytes, }, } // Set the filename for the artifact. filename := "generated_report.pdf" // Save the artifact to the artifact service. _, err = ctx.Artifacts().Save(ctx, filename, reportArtifact) if err != nil { log.Printf("An unexpected error occurred during Go artifact save: %v", err) // Depending on requirements, you might want to return an error to the user. return nil, nil } log.Printf("Successfully saved Go artifact '%s'.", filename) // Return nil to continue to the next callback or the model. return nil, nil }import com.google.adk.agents.CallbackContext; import com.google.adk.artifacts.BaseArtifactService; import com.google.adk.artifacts.InMemoryArtifactService; import com.google.genai.types.Part; import java.nio.charset.StandardCharsets; public class SaveArtifactExample { public void saveGeneratedReport(CallbackContext callbackContext, byte[] reportBytes) { // Saves generated PDF report bytes as an artifact. Part reportArtifact = Part.fromBytes(reportBytes, "application/pdf"); String filename = "generatedReport.pdf"; callbackContext.saveArtifact(filename, reportArtifact); System.out.println("Successfully saved Java artifact '" + filename); // The event generated after this callback will contain: // event().actions().artifactDelta == {"generated_report.pdf": version} } // --- Example Usage Concept (Java) --- public static void main(String[] args) { BaseArtifactService service = new InMemoryArtifactService(); // Or GcsArtifactService SaveArtifactExample myTool = new SaveArtifactExample(); byte[] reportData = "...".getBytes(StandardCharsets.UTF_8); // PDF bytes CallbackContext callbackContext; // ... obtain callback context from your app myTool.saveGeneratedReport(callbackContext, reportData); // Due to async nature, in a real app, ensure program waits or handles completion. } }在 Kotlin 中,你可以通过以下方式访问相关内容:
ArtifactServicefrom theToolContext(或CallbackContext通过;经由invocationContext)以保存该文物。suspend fun saveGeneratedReport( context: ToolContext, reportBytes: ByteArray, ) { val reportArtifact = Part( inlineData = Blob( data = reportBytes, mimeType = "application/pdf", ), ) val filename = "generated_report.pdf" val service = context.invocationContext.artifactService if (service != null) { val version = service.saveArtifact( context.invocationContext.session.key, filename, reportArtifact, ) println("Successfully saved Kotlin artifact '$filename' as version $version.") } else { println("Artifact service not available.") } }
正在加载工件(Artifacts)……¶
-
代码示例:
import google.genai.types as types from google.adk.agents.callback_context import CallbackContext # Or ToolContext async def process_latest_report_py(context: CallbackContext): """Loads the latest report artifact and processes its data.""" filename = "generated_report.pdf" try: # Load the latest version report_artifact = await context.load_artifact(filename=filename) if report_artifact and report_artifact.inline_data: print(f"Successfully loaded latest Python artifact '{filename}'.") print(f"MIME Type: {report_artifact.inline_data.mime_type}") # Process the report_artifact.inline_data.data (bytes) pdf_bytes = report_artifact.inline_data.data print(f"Report size: {len(pdf_bytes)} bytes.") # ... further processing ... else: print(f"Python artifact '{filename}' not found.") # Example: Load a specific version (if version 0 exists) # specific_version_artifact = await context.load_artifact(filename=filename, version=0) # if specific_version_artifact: # print(f"Loaded version 0 of '{filename}'.") except ValueError as e: print(f"Error loading Python artifact: {e}. Is ArtifactService configured?") except Exception as e: # Handle potential storage errors print(f"An unexpected error occurred during Python artifact load: {e}") # --- Example Usage Concept (Python) --- # async def main_py(): # callback_context: CallbackContext = ... # obtain context # await process_latest_report_py(callback_context)import {Context} from '@google/adk'; async function processLatestReport(context: Context): Promise<void> { /** Loads the latest report artifact and processes its data. */ const filename = 'generated_report.pdf'; try { // Load the latest version const reportArtifact = await context.loadArtifact(filename); if (reportArtifact?.inlineData) { console.log(`Successfully loaded latest TypeScript artifact '${filename}'.`); console.log(`MIME Type: ${reportArtifact.inlineData.mimeType}`); // Process the reportArtifact.inlineData.data (base64 string) const pdfData = Buffer.from(reportArtifact.inlineData.data || '', 'base64'); console.log(`Report size: ${pdfData.length} bytes.`); // ... further processing ... } else { console.log(`TypeScript artifact '${filename}' not found.`); } } catch (e: any) { console.error( `Error loading TypeScript artifact: ${e.message}. Is ArtifactService configured?`, ); } }import ( "log" "google.golang.org/adk/v2/agent" "google.golang.org/adk/v2/model" ) // loadArtifactsCallback is a BeforeModel callback that loads a specific artifact // and adds its content to the LLM request. func loadArtifactsCallback(ctx agent.Context, req *model.LLMRequest) (*model.LLMResponse, error) { log.Println("[Callback] loadArtifactsCallback triggered.") // In a real app, you would parse the user's request to find a filename. // For this example, we'll hardcode a filename to demonstrate. const filenameToLoad = "generated_report.pdf" // Load the artifact from the artifact service. loadedPartResponse, err := ctx.Artifacts().Load(ctx, filenameToLoad) if err != nil { log.Printf("Callback could not load artifact '%s': %v", filenameToLoad, err) return nil, nil // File not found or error, continue to model. } loadedPart := loadedPartResponse.Part log.Printf("Callback successfully loaded artifact '%s'.", filenameToLoad) // Ensure there's at least one content in the request to append to. if len(req.Contents) == 0 { req.Contents = []*genai.Content{{Parts: []*genai.Part{ genai.NewPartFromText("SYSTEM: The following file is provided for context:\n"), }}} } // Add the loaded artifact to the request for the model. lastContent := req.Contents[len(req.Contents)-1] lastContent.Parts = append(lastContent.Parts, loadedPart) log.Printf("Added artifact '%s' to LLM request.", filenameToLoad) // Return nil to continue to the next callback or the model. return nil, nil // Continue to next callback or LLM call }import com.google.adk.artifacts.BaseArtifactService; import com.google.genai.types.Part; import io.reactivex.rxjava3.core.MaybeObserver; import io.reactivex.rxjava3.disposables.Disposable; import java.util.Optional; public class MyArtifactLoaderService { private final BaseArtifactService artifactService; private final String appName; public MyArtifactLoaderService(BaseArtifactService artifactService, String appName) { this.artifactService = artifactService; this.appName = appName; } public void processLatestReportJava(String userId, String sessionId, String filename) { // Load the latest version by passing Optional.empty() for the version artifactService .loadArtifact(appName, userId, sessionId, filename) .subscribe( new MaybeObserver<Part>() { @Override public void onSubscribe(Disposable d) { // Optional: handle subscription } @Override public void onSuccess(Part reportArtifact) { System.out.println( "Successfully loaded latest Java artifact '" + filename + "'."); reportArtifact .inlineData() .ifPresent( blob -> { System.out.println( "MIME Type: " + blob.mimeType().orElse("N/A")); byte[] pdfBytes = blob.data().orElse(new byte[0]); System.out.println("Report size: " + pdfBytes.length + " bytes."); // ... further processing of pdfBytes ... }); } @Override public void onError(Throwable e) { // Handle potential storage errors or other exceptions System.err.println( "An error occurred during Java artifact load for '" + filename + "': " + e.getMessage()); } @Override public void onComplete() { // Called if the artifact (latest version) is not found System.out.println("Java artifact '" + filename + "' not found."); } }); // Example: Load a specific version (e.g., version 0) /* artifactService.loadArtifact(appName, userId, sessionId, filename, 0) .subscribe(part -> { System.out.println("Loaded version 0 of Java artifact '" + filename + "'."); }, throwable -> { System.err.println("Error loading version 0 of '" + filename + "': " + throwable.getMessage()); }, () -> { System.out.println("Version 0 of Java artifact '" + filename + "' not found."); }); */ } // --- Example Usage Concept (Java) --- public static void main(String[] args) { // BaseArtifactService service = new InMemoryArtifactService(); // Or GcsArtifactService // MyArtifactLoaderService loader = new MyArtifactLoaderService(service, "myJavaApp"); // loader.processLatestReportJava("user123", "sessionABC", "java_report.pdf"); // Due to async nature, in a real app, ensure program waits or handles completion. } }在 Kotlin 中,你可以直接从某个来源加载某个“artifacts”(即编译生成的文件或资源)。
ToolContext(或CallbackContext)使用context.loadArtifact(name).suspend fun processLatestReport(context: ToolContext) { val filename = "generated_report.pdf" val reportArtifact = context.loadArtifact(filename) if (reportArtifact != null && reportArtifact.inlineData != null) { println("Successfully loaded latest Kotlin artifact '$filename'.") println("MIME Type: ${reportArtifact.inlineData?.mimeType}") val pdfBytes = reportArtifact.inlineData?.data println("Report size: ${pdfBytes?.size} bytes.") } else { println("Kotlin artifact '$filename' not found.") } }
使用 LoadArtifactsTool¶
你可以添加…… LoadArtifactsTool 模型需要在回答问题之前决定加载哪些可用的“工件”(artifacts)。当用户对已上传的文件或大型生成结果提出后续问题时,这种方法非常有用;这些文件或结果通常会被存储为“工件”,而不是保留在对话的上下文中。
LoadArtifactsTool 在模型说明中列出了可用的工件(artifacts)。当模型调用这些工件时…… load_artifacts 该工具(tool)或 ADK(可能是某个特定的软件组件)会暂时将所选“artifact”的内容添加到请求中,以便模型能够根据文件内容来生成相应的响应。需要注意的是,这些被加载的“artifact”内容并不会被永久保存到会话历史记录(session history)中;因此,当模型后续需要再次使用相同的“artifact”时,必须再次调用该工具。
from google.adk.agents import LlmAgent
from google.adk.tools.load_artifacts_tool import LoadArtifactsTool
root_agent = LlmAgent(
name="artifact_reader",
model="gemini-flash-latest",
instruction=(
"Answer questions about available user files. "
"Call load_artifacts before answering when you need file contents."
),
tools=[
LoadArtifactsTool(),
],
)
请确保…… Runner 该代理已配置为使用……(具体配置内容需根据实际情况填写)。
artifact_service否则,工件的列表显示和加载将会失败。如果你的工件需要人类可读的摘要信息,可以对其进行子类化(即创建一个继承自相应基类的新类)。 LoadArtifactsTool
在加载所选的艺术品(artifact)内容之前,还需要自定义其请求指令(request instructions)。
解析电子表格文件中的数据(仅支持 Python):
默认情况下,电子表格文件(.xlsx, .xls该数据无法被模型直接读取(即无法在模型代码中直接使用该数据)。在 Python 中,你可以设置相关属性或方法来处理这种情况。 enable_spreadsheet_parsing=True 需要将这些内容解析成 Markdown 格式的表格。
- 每张表格都会被渲染成一个独立的 Markdown 表格,并显示在相应的表格标题下方。
- 表格的输出结果被限制在每张表格的前 100 行以内,以避免超出上下文窗口的显示限制。
import (
"google.golang.org/adk/v2/agent/llmagent"
"google.golang.org/adk/v2/tool"
"google.golang.org/adk/v2/tool/loadartifactstool"
)
agent, err := llmagent.New(llmagent.Config{
Name: "artifact_reader",
Model: model,
Instruction: "Answer questions about available user files. " +
"When user asks about artifacts, load them and describe them.",
Tools: []tool.Tool{
loadartifactstool.New(),
},
})
请确保…… runner.Config 对于这个代理来说,包含以下内容:
ArtifactService否则,艺术品的列表显示及加载过程将会失败。
fun loadArtifactsToolExample() {
val rootAgent =
LlmAgent(
name = "artifact_reader",
model = Gemini(name = "gemini-flash-latest"),
instruction =
Instruction(
"Answer questions about available user files. " +
"Call load_artifacts before answering when you need file contents.",
),
tools = listOf(LoadArtifactsTool()),
)
}
请确保…… Runner 该代理已配置为使用……(具体配置内容需根据实际情况填写)。
artifactService否则,艺术品的列表显示及加载过程将会失败。
列出工件(Artifact)的文件名¶
-
代码示例:
from google.adk.tools.tool_context import ToolContext async def list_user_files_py(tool_context: ToolContext) -> str: """Tool to list available artifacts for the user.""" try: available_files = await tool_context.list_artifacts() if not available_files: return "You have no saved artifacts." else: # Format the list for the user/LLM file_list_str = "\n".join([f"- {fname}" for fname in available_files]) return f"Here are your available Python artifacts:\n{file_list_str}" except ValueError as e: print(f"Error listing Python artifacts: {e}. Is ArtifactService configured?") return "Error: Could not list Python artifacts." except Exception as e: print(f"An unexpected error occurred during Python artifact list: {e}") return "Error: An unexpected error occurred while listing Python artifacts." # This function would typically be wrapped in a FunctionTool # from google.adk.tools import FunctionTool # list_files_tool = FunctionTool(func=list_user_files_py)import {Context} from '@google/adk'; async function listUserFiles(context: Context): Promise<string> { /** Tool to list available artifacts for the user. */ try { const availableFiles = await context.listArtifacts(); if (!availableFiles || availableFiles.length === 0) { return 'You have no saved artifacts.'; } else { // Format the list for the user/LLM const fileListStr = availableFiles.map((fname) => `- ${fname}`).join('\n'); return `Here are your available TypeScript artifacts:\n${fileListStr}`; } } catch (e: any) { console.error( `Error listing TypeScript artifacts: ${e.message}. Is ArtifactService configured?`, ); return 'Error: Could not list TypeScript artifacts.'; } }import ( "fmt" "log" "strings" "google.golang.org/adk/v2/agent" "google.golang.org/adk/v2/model" "google.golang.org/genai" ) // listUserFilesCallback is a BeforeModel callback that lists available artifacts // and adds the list as context to the LLM request. func listUserFilesCallback(ctx agent.Context, req *model.LLMRequest) (*model.LLMResponse, error) { log.Println("[Callback] listUserFilesCallback triggered.") // List the available artifacts from the artifact service. listResponse, err := ctx.Artifacts().List(ctx) if err != nil { log.Printf("An unexpected error occurred during Go artifact list: %v", err) return nil, nil // Continue, but log the error. } availableFiles := listResponse.FileNames log.Printf("Found %d available files.", len(availableFiles)) // If there are available files, add them to the LLM request. if len(availableFiles) > 0 { var fileListStr strings.Builder fileListStr.WriteString("SYSTEM: The following files are available:\n") for _, fname := range availableFiles { fileListStr.WriteString(fmt.Sprintf("- %s\n", fname)) } // Prepend this information to the user's request for the model. if len(req.Contents) > 0 { lastContent := req.Contents[len(req.Contents)-1] if len(lastContent.Parts) > 0 { fileListStr.WriteString("\n") // Add a newline for separation. lastContent.Parts[0] = genai.NewPartFromText(fileListStr.String() + lastContent.Parts[0].Text) log.Println("Added file list to LLM request context.") } } log.Printf("Available files:\n%s", fileListStr.String()) } else { log.Println("No available files found to list.") } // Return nil to continue to the next callback or the model. return nil, nil // Continue to next callback or LLM call }import com.google.adk.artifacts.BaseArtifactService; import com.google.adk.artifacts.ListArtifactsResponse; import com.google.common.collect.ImmutableList; import io.reactivex.rxjava3.core.SingleObserver; import io.reactivex.rxjava3.disposables.Disposable; public class MyArtifactListerService { private final BaseArtifactService artifactService; private final String appName; public MyArtifactListerService(BaseArtifactService artifactService, String appName) { this.artifactService = artifactService; this.appName = appName; } // Example method that might be called by a tool or agent logic public void listUserFilesJava(String userId, String sessionId) { artifactService .listArtifactKeys(appName, userId, sessionId) .subscribe( new SingleObserver<ListArtifactsResponse>() { @Override public void onSubscribe(Disposable d) { // Optional: handle subscription } @Override public void onSuccess(ListArtifactsResponse response) { ImmutableList<String> availableFiles = response.filenames(); if (availableFiles.isEmpty()) { System.out.println( "User " + userId + " in session " + sessionId + " has no saved Java artifacts."); } else { StringBuilder fileListStr = new StringBuilder( "Here are the available Java artifacts for user " + userId + " in session " + sessionId + ":\n"); for (String fname : availableFiles) { fileListStr.append("- ").append(fname).append("\n"); } System.out.println(fileListStr.toString()); } } @Override public void onError(Throwable e) { System.err.println( "Error listing Java artifacts for user " + userId + " in session " + sessionId + ": " + e.getMessage()); // In a real application, you might return an error message to the user/LLM } }); } // --- Example Usage Concept (Java) --- public static void main(String[] args) { // BaseArtifactService service = new InMemoryArtifactService(); // Or GcsArtifactService // MyArtifactListerService lister = new MyArtifactListerService(service, "myJavaApp"); // lister.listUserFilesJava("user123", "sessionABC"); // Due to async nature, in a real app, ensure program waits or handles completion. } }
suspend fun listUserFiles(context: ToolContext): String {
val availableFiles = context.listArtifacts()
if (availableFiles.isEmpty()) {
return "You have no saved artifacts."
} else {
val fileListStr = availableFiles.joinToString("\n") { "- $it" }
return "Here are your available Kotlin artifacts:\n$fileListStr"
}
}
这些用于保存、加载和列出二进制数据的方法为在 ADK 中管理二进制数据的持久性提供了一种便捷且一致的方式。无论您是通过传递给回调函数和工具的上下文对象来使用这些方法,还是通过与其他组件进行交互来使用它们,都可以实现相同的功能。 BaseArtifactService 无论选择哪种后端存储实现方式,数据都可以被直接读取或写入。
可用的实现方式(Available Implementations)¶
ADK 提供了这些接口的具体实现(即提供了如何使用这些接口的具体方法)。 BaseArtifactService 该接口提供了多种存储后端选项,适用于不同的开发阶段和部署需求。这些实现方案负责处理与存储、版本控制以及检索相关数据(即“artifact data”)相关的所有细节。 app_name, user_id, session_id,以及 filename (包括……) user: `namespace prefix)`。
InMemoryArtifactService¶
- 存储机制:
- Python:使用 Python 字典。
self.artifacts这些数据存储在应用程序的内存中。字典的键表示文物的路径,而值则是包含多个条目的列表;每个列表元素代表一个版本(version),其中存储了与该文物相关的信息。types.Part有效载荷(payload)及其相关内容。ArtifactVersionmetadata. - Java:使用嵌套结构(nested structures)。
HashMap实例(Instances)private final Map<String, Map<String, Map<String, Map<String, List<Part>>>>> artifacts;)存储在内存中。每一层的键(keys)分别是……appName,userId,sessionId,以及filename分别(respectively)。最内层的(the innermost)List<Part>该存储结构用于保存某个“工件”(artifact)的各个版本信息;其中,列表的索引值对应于该版本的编号。
- Python:使用 Python 字典。
- 主要特点:
- 简洁性: 除了核心的 ADK 库之外,无需任何外部设置或依赖项。
- 速度: 这些操作通常执行得非常快,因为它们涉及对内存中的映射(map)或字典(dictionary)的查询,以及对列表(list)的修改。
- Ephemeral: 所有存储的工件(artifacts)都…… 丢失的;遗失的 当应用程序进程终止时,数据不会在应用程序重新启动后仍然保留。
- 使用场景:
- 非常适合用于本地开发和测试,因为在这些场景中并不需要数据持久化(即数据不会被保存到长期存储介质中)。
- 适用于那些持续时间较短的演示场景,或者那些在应用程序的单次运行过程中,相关数据仅具有临时性的情况。
-
实例化(Instantiation):
import ( "google.golang.org/adk/v2/artifact" ) // Simply instantiate the service artifactService := artifact.InMemoryService() log.Printf("InMemoryArtifactService (Go) instantiated: %T", artifactService) // Use the service in your runner // r, _ := runner.New(runner.Config{ // Agent: agent, // AppName: "my_app", // SessionService: sessionService, // ArtifactService: artifactService, // })import com.google.adk.artifacts.BaseArtifactService; import com.google.adk.artifacts.InMemoryArtifactService; public class InMemoryServiceSetup { public static void main(String[] args) { // Simply instantiate the class BaseArtifactService inMemoryServiceJava = new InMemoryArtifactService(); System.out.println("InMemoryArtifactService (Java) instantiated: " + inMemoryServiceJava.getClass().getName()); // This instance would then be provided to your Runner. // Runner runner = new Runner( // /* other services */, // inMemoryServiceJava // ); } }GcsArtifactService¶
-
存储机制: 该系统利用 Google Cloud Storage (GCS) 来存储持久化的工件(artifacts)。每个工件版本都会作为独立的对象(blob)存储在指定的 GCS 存储桶中。
- 对象命名规范: 它使用分层路径结构来生成 GCS 对象名称(即数据块的名称)。
- 主要特点:
- 持久性(Persistence): 存储在 GCS(Google Cloud Storage)中的文件数据会在应用程序重启或部署过程中保持不变。
- 可扩展性: 充分利用 Google Cloud Storage 的可扩展性和可靠性。
- 版本控制: 每个版本都会被明确地存储为一个独立的 GCS 对象。在 Python 中,
save_artifact分配下一个版本号,版本号从……开始递增。0与其覆盖现有的对象,不如采用这种方式。 - 所需权限: 应用程序环境需要适当的凭据(例如“应用程序默认凭据”)以及 IAM 权限,才能从指定的 GCS 存储桶中读取数据并向其中写入数据。
- 使用场景:
- 需要持久化存储相关资源的生产环境。
- 在以下场景中,需要将工件(artifacts)共享到不同的应用程序实例或服务中(这些应用程序或服务可以访问同一个 GCS 存储桶):
- 需要长期存储和检索用户数据或会话数据的应用程序。
-
实例化(Instantiation):
from google.adk.artifacts import GcsArtifactService # Specify the GCS bucket name gcs_bucket_name_py = "your-gcs-bucket-for-adk-artifacts" # Replace with your bucket name try: gcs_service_py = GcsArtifactService(bucket_name=gcs_bucket_name_py) print(f"Python GcsArtifactService initialized for bucket: {gcs_bucket_name_py}") # Ensure your environment has credentials to access this bucket. # e.g., via Application Default Credentials (ADC) # Then pass it to the Runner # runner = Runner(..., artifact_service=gcs_service_py) except Exception as e: # Catch potential errors during GCS client initialization (e.g., auth issues) print(f"Error initializing Python GcsArtifactService: {e}") # Handle the error appropriately - maybe fall back to InMemory or raiseimport {GcsArtifactService} from '@google/adk'; // Specify the GCS bucket name. const gcsBucketName = 'your-gcs-bucket-for-adk-artifacts'; try { const gcsService = new GcsArtifactService(gcsBucketName); console.log(`TypeScript GcsArtifactService initialized for bucket: ${gcsBucketName}`); // Ensure your environment has credentials to access this bucket. // e.g., via Application Default Credentials (ADC). // Then pass it to the Runner. // const runner = new Runner({..., artifactService: gcsService}); } catch (e: any) { // Catch potential errors during GCS client initialization (e.g., auth issues). console.error(`Error initializing TypeScript GcsArtifactService: ${e.message}`); }import com.google.adk.artifacts.BaseArtifactService; import com.google.adk.artifacts.GcsArtifactService; import com.google.cloud.storage.Storage; import com.google.cloud.storage.StorageOptions; public class GcsServiceSetup { public static void main(String[] args) { // Specify the GCS bucket name String gcsBucketNameJava = "your-gcs-bucket-for-adk-artifacts"; // Replace with your bucket name try { // Initialize the GCS Storage client. // This will use Application Default Credentials by default. // Ensure the environment is configured correctly (e.g., GOOGLE_APPLICATION_CREDENTIALS). Storage storageClient = StorageOptions.getDefaultInstance().getService(); // Instantiate the GcsArtifactService BaseArtifactService gcsServiceJava = new GcsArtifactService(gcsBucketNameJava, storageClient); System.out.println( "Java GcsArtifactService initialized for bucket: " + gcsBucketNameJava); // This instance would then be provided to your Runner. // Runner runner = new Runner( // /* other services */, // gcsServiceJava // ); } catch (Exception e) { // Catch potential errors during GCS client initialization (e.g., auth, permissions) System.err.println("Error initializing Java GcsArtifactService: " + e.getMessage()); e.printStackTrace(); // Handle the error appropriately } } }fun gcsServiceExample() { val gcsBucketName = "your-gcs-bucket-for-adk-artifacts" try { // Initialize the GCS Storage client (usually uses Application Default Credentials) val storage = com.google.cloud.storage.StorageOptions.getDefaultInstance().service val gcsService = GcsArtifactService(bucketName = gcsBucketName, storageClient = storage) println("Kotlin GcsArtifactService initialized for bucket: $gcsBucketName") } catch (e: Exception) { println("Error initializing Kotlin GcsArtifactService: ${e.message}") } }选择合适的方法/工具……
ArtifactService具体的实现方式取决于您的应用程序在数据持久性、可扩展性以及运行环境方面的需求。
最佳实践¶
为了有效地使用这些工件(artifacts),并确保其长期的可维护性:
- 选择合适的服务: 使用
InMemoryArtifactService适用于快速原型设计、测试,以及那些不需要数据持久化的场景。请使用该工具。GcsArtifactService(或实现您自己的解决方案)BaseArtifactService(适用于其他后端系统)专为需要数据持久性和可扩展性的生产环境设计。 - 有意义的文件名: 请使用清晰、具有描述性的文件名,并包含相关的文件扩展名。
.pdf,.png,.wav)帮助人们理解内容,即使这些内容本身……(此处“even though the”后缺少具体的描述或解释。)mime_type这决定了程序化的处理方式;同时需要为临时生成的文件与持久性存储的文件(即那些需要长期保留的文件)制定统一的命名规则。 - 请指定正确的 MIME 类型: 始终提供准确的信息。
mime_type在创建……的时候types.Partforsave_artifact这对于那些后续需要使用这些数据的应用程序或工具来说至关重要。load_artifact用于解释……bytes请正确地传输数据。在可能的情况下,使用标准的 IANA MIME 类型。 - 理解版本控制(Understand Versioning): 请记住……
load_artifact()在没有具体说明的情况下……version该参数用于检索(retrieve)相关数据。 latest 版本号:如果您的逻辑依赖于某个特定历史版本的工件(artifact),请在加载该工件时务必提供相应的整数版本号。 - **使用命名空间(Use Namespacing)**
user:)这是故意为之的: **仅使用以下内容:** (请在此处填写实际需要使用的信息,例如具体的API标识符或占位符内容。)"user:"当数据确实属于用户,并且应该在其所有会话中都可访问时,文件名前应加上该前缀。对于仅与特定对话或会话相关的数据,则应使用不带前缀的普通文件名。 - 错误处理:
- 始终要检查某个……(此处“an”应为“a”或“the”,具体取决于上下文)是否……
artifact_service实际上,在调用上下文(context)相关方法之前,相关配置就已经完成了。save_artifact,load_artifact,list_artifacts)– 他们会提出一个(请求或问题)。ValueError如果该服务(service)是……None. - 检查返回值。
load_artifact因为情况就是如此(即:事情会按照预定的方式发展)。None如果该工件(artifact)或版本(version)不存在,请不要认为系统总会返回相应的结果。Part. - 请准备好处理来自底层存储服务的异常情况,尤其是在以下情况下:
GcsArtifactService(e.g.,google.api_core.exceptions.Forbidden由于许可问题,NotFound如果该桶不存在,可能会导致网络错误。
- 始终要检查某个……(此处“an”应为“a”或“the”,具体取决于上下文)是否……
- 尺寸方面的考虑: 这些工具适用于常见的文件大小;不过对于体积极大的文件(尤其是在使用云存储服务时),请注意可能产生的成本及性能影响。
InMemoryArtifactService如果存储大量大型数据文件,这些数据可能会占用大量内存。请考虑:对于非常大的数据,是否可以通过直接使用 Google Cloud Storage(GCS)的链接或其他专门的存储解决方案来处理这些数据,而不是将整个字节数组存储在内存中。 - 清理策略(Cleanup Strategy): 对于需要持久存储的数据(例如:用户信息、配置文件等),可以使用以下方法:
GcsArtifactService这些“工件”(artifacts)会一直保留在系统中,直到被明确删除为止。如果这些工件代表的是临时数据,或者它们的生命周期很短,那么就需要制定相应的清理策略。这可能包括以下措施:- 正在对该桶应用 GCS(Google Cloud Storage)的生命周期策略。
- 开发特定的工具或管理功能,这些工具/功能会利用(某些资源或技术)。
artifact_service.delete_artifact`method`(注意:`delete` 方法会被删除/移除) 不;并非 (为确保安全性,这些信息是通过上下文对象(context objects)来暴露的。) - 需要时,要仔细管理文件名,以便能够根据特定模式来删除文件。