adk-typescript
Version:
TypeScript port of Google's Agent Development Kit (ADK)
195 lines (194 loc) • 7.27 kB
JavaScript
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.APIHubToolset = void 0;
const yaml = __importStar(require("js-yaml"));
const clients_1 = require("./clients");
const openapi_tool_1 = require("../openapi-tool");
const common_1 = require("../openapi-tool/common/common");
/**
* APIHubToolset generates tools from a given API Hub resource.
*
* Examples:
*
* ```typescript
* const apihubToolset = new APIHubToolset({
* apihubResourceName: "projects/test-project/locations/us-central1/apis/test-api",
* serviceAccountJson: "...",
* });
*
* // Get all available tools
* const agent = new LlmAgent({ tools: apihubToolset.getTools() });
*
* // Get a specific tool
* const agent = new LlmAgent({
* tools: [
* ...
* apihubToolset.getTool('my_tool'),
* ]
* });
* ```
*
* **apihubResourceName** is the resource name from API Hub. It must include
* API name, and can optionally include API version and spec name.
* - If apihubResourceName includes a spec resource name, the content of that
* spec will be used for generating the tools.
* - If apihubResourceName includes only an api or a version name, the
* first spec of the first version of that API will be used.
*/
class APIHubToolset {
/**
* Initializes the APIHubToolset with the given parameters.
*
* Examples:
* ```typescript
* const apihubToolset = new APIHubToolset({
* apihubResourceName: "projects/test-project/locations/us-central1/apis/test-api",
* serviceAccountJson: "...",
* });
*
* // Get all available tools
* const agent = new LlmAgent({ tools: apihubToolset.getTools() });
*
* // Get a specific tool
* const agent = new LlmAgent({
* tools: [
* ...
* apihubToolset.getTool('my_tool'),
* ]
* });
* ```
*
* @param params Configuration parameters
* @param params.apihubResourceName The resource name of the API in API Hub. Example: `projects/test-project/locations/us-central1/apis/test-api`.
* @param params.accessToken Google Access token. Generate with gcloud cli `gcloud auth print-access-token`. Used for fetching API Specs from API Hub.
* @param params.serviceAccountJson The service account config as a json string. Required if not using default service credential. Used for creating the API Hub client and fetching API Specs from API Hub.
* @param params.apihubClient Optional custom API Hub client.
* @param params.name Name of the toolset. Optional.
* @param params.description Description of the toolset. Optional.
* @param params.authScheme Auth scheme that applies to all the tool in the toolset.
* @param params.authCredential Auth credential that applies to all the tool in the toolset.
* @param params.lazyLoadSpec If true, the spec will be loaded lazily when needed. Otherwise, the spec will be loaded immediately and the tools will be generated during initialization.
*/
constructor(params) {
this.generatedTools = {};
this.name = params.name || '';
this.description = params.description || '';
this.apihubResourceName = params.apihubResourceName;
this.lazyLoadSpec = params.lazyLoadSpec || false;
this.apihubClient = params.apihubClient || new clients_1.APIHubClient({
accessToken: params.accessToken,
serviceAccountJson: params.serviceAccountJson,
});
this.authScheme = params.authScheme;
this.authCredential = params.authCredential;
if (!this.lazyLoadSpec) {
this.prepareTools();
}
}
/**
* Retrieves a specific tool by its name.
*
* Example:
* ```typescript
* const apihubTool = apihubToolset.getTool('my_tool');
* ```
*
* @param name The name of the tool to retrieve.
* @returns The tool with the given name, or undefined if no such tool exists.
*/
getTool(name) {
if (!this.areToolsReady()) {
this.prepareTools();
}
return this.generatedTools[name];
}
/**
* Retrieves all available tools.
*
* @returns A list of all available RestApiTool objects.
*/
getTools() {
if (!this.areToolsReady()) {
this.prepareTools();
}
return Object.values(this.generatedTools);
}
/**
* Checks if tools are ready for use
*
* @returns True if tools are ready, false otherwise
* @private
*/
areToolsReady() {
return !this.lazyLoadSpec || Object.keys(this.generatedTools).length > 0;
}
/**
* Fetches the spec from API Hub and generates the tools.
*
* @private
*/
async prepareTools() {
// For each API, get the first version and the first spec of that version.
const spec = await this.apihubClient.getSpecContent(this.apihubResourceName);
this.generatedTools = {};
const tools = await this.parseSpecToTools(spec);
for (const tool of tools) {
this.generatedTools[tool.name] = tool;
}
}
/**
* Parses the spec string to a list of RestApiTool
*
* @param specStr The spec string to parse
* @returns A list of RestApiTool objects
* @private
*/
async parseSpecToTools(specStr) {
const specDict = yaml.load(specStr);
if (!specDict) {
return [];
}
this.name = this.name || (0, common_1.toSnakeCase)(specDict.info?.title || 'unnamed');
this.description = this.description || specDict.info?.description || '';
const toolset = new openapi_tool_1.OpenAPIToolset({
specDict,
authCredential: this.authCredential,
authScheme: this.authScheme,
});
return toolset.getTools();
}
}
exports.APIHubToolset = APIHubToolset;