Agent mit mehreren Tools
Erfahren Sie, wie Sie einen Agent erstellen, der mehrere Tools verwendet.
Ein Support-Agent mit einem RAG-Tool und mehreren Funktionstools
Dieses Beispiel zeigt einen Agent, der mit einer Wissensdatenbank (mit AgenticRagTool) und einer Sammlung von benutzerdefinierten Funktionstools (mit Toolkit) ausgestattet ist.
Erstellen Sie zunächst eine Wissensdatenbank für das RAG-Tool. Siehe Knowledge Base erstellen. Erstellen Sie für die Datenquelle eine Object Storage-Datei. Kopieren Sie dann die OCID der Wissensdatenbank, und fügen Sie sie in ein Notizbuch ein.
Python
product_support_agent.py
from oci.addons.adk import Agent, AgentClient
from oci.addons.adk.tool.prebuilt import AgenticRagTool
from custom_function_tools import AccountToolkit
def main():
# Assuming the resources were already provisioned
agent_endpoint_id = "ocid1.genaiagentendpoint..."
knowledge_base_id = "ocid1.genaiagentknowledgebase..."
client = AgentClient(
auth_type="api_key",
profile="DEFAULT",
region="us-chicago-1"
)
instructions = """
You are customer support agent.
Use RAG tool to answer product questions.
Use function tools to fetch user and org info by id.
Only orgs of Enterprise plan can use Responses API.
"""
agent = Agent(
client=client,
agent_endpoint_id=agent_endpoint_id,
instructions=instructions,
tools=[
AgenticRagTool(knowledge_base_ids=[knowledge_base_id]),
AccountToolkit()
]
)
agent.setup()
# This is a context your existing code is best at producing (e.g., fetching the authenticated user id)
client_provided_context = "[Context: The logged in user ID is: user_123] "
# Handle the first user turn of the conversation
input = "What is the Responses API?"
input = client_provided_context + " " + input
response = agent.run(input)
response.pretty_print()
# Handle the second user turn of the conversation
input = "Is my user account eligible for the Responses API?"
input = client_provided_context + " " + input
response = agent.run(input, session_id=response.session_id)
response.pretty_print()
if __name__ == "__main__":
main()
Java
ProductSupportAgent.java
import com.oracle.bmc.ConfigFileReader;
import com.oracle.bmc.adk.agent.Agent;
import com.oracle.bmc.adk.agent.RunOptions;
import com.oracle.bmc.adk.client.AgentClient;
import com.oracle.bmc.adk.tools.prebuilt.AgenticRagTool;
import com.oracle.bmc.adk.run.RunResponse;
import com.oracle.bmc.auth.BasicAuthenticationDetailsProvider;
import com.oracle.bmc.auth.SessionTokenAuthenticationDetailsProvider;
import java.util.Arrays;
public class ProductSupportAgent {
public static void main(String[] args) throws Exception {
final String configLocation = "~/.oci/config";
final String configProfile = "DEFAULT";
final String agentEndpointId = "ocid1.genaiagentendpoint.oc1.us-chicago-1...";
final String knowledgeBaseId ="ocid1.genaiagentknowledgebaseppe.oc1.us-chicago-1...";
BasicAuthenticationDetailsProvider authProvider =
new SessionTokenAuthenticationDetailsProvider(
ConfigFileReader.parse(configLocation, configProfile));
AgentClient agentClient = AgentClient.builder()
.authProvider(authProvider)
.region("us-chicago-1")
.build();
final String instructions =
"You are customer support agent. Use KB tool to answer product questions. Use tools to fetch user and org info by id. Only orgs of Enterprise plan can use Responses API.";
Agent agent = Agent.builder()
.client(agentClient)
.agentEndpointId(agentEndpointId)
.instructions(instructions)
.tools(
Arrays.asList(
new AccountToolkit(),
AgenticRagTool.builder().knowledgeBaseIds(Arrays.asList(knowledgeBaseId))))
.build();
agent.setup();
final String clientProvidedContext = "[Context: The logged in user ID is: user_123]";
// Handle the first user turn of the conversation
String input = "What is the Responses API?";
input = clientProvidedContext + " " + input;
final Integer maxStep = 3;
RunOptions runOptions = RunOptions.builder().maxSteps(maxStep).build();
RunResponse response = agent.run(input, runOptions);
response.prettyPrint();
// Handle the second user turn of the conversation
input = "Is my user account eligible for the Responses API?";
input = clientProvidedContext + " " + input;
runOptions.setSessionId(response.getSessionId());
response = agent.run(input, runOptions);
response.prettyPrint();
}
}
Info: Dieses Beispiel zeigt auch die Verarbeitung von Multiturn-Unterhaltungen mit session_id, um den Kontext zwischen den Turns beizubehalten. Erfahren Sie mehr über das Beispiel Multi-Turn-Konversationsverarbeitung.
Der Agent verwendet eine benutzerdefinierte AccountToolkit. Sie können Ihre eigene benutzerdefinierte Toolkit-Klasse erstellen, indem Sie oci.addons.adk, die Klasse Toolkit, übernehmen.
Mit einer Toolkit-Klasse können Sie verwandte Tools in einer einzelnen Klasse organisieren.
Sie können dasselbe Toolkit in verschiedenen Agents wiederverwenden. Sie können auch einen Status innerhalb der Instanz der Klasse Toolkit beibehalten. Der ADK ruft die Instanzmethode auf, sodass Ihr Status für die Methoden mit dem Decorator-Element @tool verfügbar ist.
Python
custom_function_tools.py
from typing import Dict, Any
from oci.addons.adk import Toolkit, tool
class AccountToolkit(Toolkit):
@tool
def get_user_info(self, user_id: str) -> Dict[str, Any]:
"""Get information about a user by user_id
Args:
user_id (str): The user ID to get information about
Returns:
Dict[str, Any]: A dictionary containing the user information
"""
# Here is a mock implementation
return {
"user_id": user_id,
"account_id": "acc_111",
"name": "John Doe",
"email": "john.doe@example.com",
"org_id": "org_222",
}
@tool
def get_org_info(self, org_id: str) -> Dict[str, Any]:
"""Get information about an organization by org_id
Args:
org_id (str): The organization ID to get information about
Returns:
Dict[str, Any]: A dictionary containing the organization information
"""
# Here is a mock implementation
return {
"org_id": org_id,
"name": "Acme Inc",
"admin_email": "admin@acme.com",
"plan": "Enterprise",
}
Java
AccountToolkit.java
package demos.singleTurnMultiTools.accountToolkitAgent;
import com.oracle.bmc.adk.tools.Param;
import com.oracle.bmc.adk.tools.Tool;
import com.oracle.bmc.adk.tools.Toolkit;
import java.util.HashMap;
import java.util.Map;
public class AccountToolkit extends Toolkit {
@Tool(name = "getUserInfo", description = "Get user info")
public static Map<String, String> getUserInfo(
@Param(description = "The user id.") String userId) {
Map<String, String> userData = new HashMap<>();
if (userId.equals("user_123")) {
userData.put("user_id", userId);
userData.put("account_id", "acc_111");
userData.put("name", "John Doe");
userData.put("email", "john.doe@example.com");
userData.put("org_id", "org_222");
} else {
userData.put("user_id", userId);
userData.put("account_id", "acc_111");
userData.put("name", "Jane Doe");
userData.put("email", "jane.doe@example.com");
userData.put("org_id", "org_333");
}
return userData;
}
@Tool(name = "getOrgInfo", description = "Get org info")
public static Map<String, String> getOrgInfo(@Param(description = "The org id.") String orgId) {
Map<String, String> orgData = new HashMap<>();
orgData.put("orgId", orgId);
orgData.put("name", "Acme Inc");
orgData.put("adminEmail", "admin@acme.com");
orgData.put("plan", "Enterprise");
return orgData;
}
}