Merge adk module (Agent Development Kit, MCP, A2A, Studio, Garden, AP2)
This commit is contained in:
@@ -0,0 +1,185 @@
|
||||
# Agent Development Kit (ADK) in C++ - Specification
|
||||
|
||||
Owned directory: `src/google/adk/`. Namespace `molo::google::adk`. Depends on
|
||||
the Google foundation (`LanguageModel`, `GenerateRequest`, `GoogleClient`,
|
||||
`valid_segment`) and `molo::clients`. It does not depend on the models,
|
||||
sessions or runtime modules: it ships its own `DirectModel`, session and
|
||||
memory seams.
|
||||
|
||||
Google's ADK is an open-source framework (Python, TypeScript, Go, Java).
|
||||
This module is a C++ implementation of its concepts, not a port of its API.
|
||||
|
||||
## 1. Module map
|
||||
|
||||
| File | Concern |
|
||||
|---|---|
|
||||
| `caps.h` | Static ceilings (`AdkCaps`) |
|
||||
| `error.h` | `AdkError` (codes: invalid_argument, budget, tool, protocol, upstream) |
|
||||
| `tool.h/.cpp` | `Tool` interface, `FunctionTool` (lambda + JSON schema, argument validation), `exit_loop` |
|
||||
| `session.h/.cpp` | `SessionService` / `MemoryService` interfaces + bounded in-memory defaults |
|
||||
| `agent.h/.cpp` | `BaseAgent`, `Agent` (LLM agent, tools, sub-agents, transfer), `SequentialAgent`, `ParallelAgent`, `LoopAgent`, `Budget`, `RunContext` |
|
||||
| `runner.h/.cpp` | `Runner` (one turn, hard caps, sessions), `load_memory` tool |
|
||||
| `direct_model.h/.cpp` | `DirectModel : LanguageModel` over `GoogleClient`; the declared-call table |
|
||||
| `remote_http.h/.cpp` | Bounded HTTP helper for MCP / A2A |
|
||||
| `mcp.h/.cpp` | MCP client over streamable HTTP; remote tools become ADK tools |
|
||||
| `a2a.h/.cpp` | A2A client: agent card, SendMessage, GetTask; remote agent as a tool |
|
||||
| `studio.h/.cpp` | Agent Studio style export / import (`AgentDefinition`, `ToolRegistry`) |
|
||||
| `garden.h/.cpp` | Agent Garden template catalog (local) |
|
||||
| `ap2.h/.cpp` | AP2 mandate types and validation (local) |
|
||||
| `trigger.h/.cpp` | Batch and event-driven trigger interfaces + dispatcher |
|
||||
| `tools/check_discovery.py` | Discovery check for the declared Google calls |
|
||||
|
||||
## 2. Static caps (see caps.h)
|
||||
|
||||
| Knob | Value |
|
||||
|---|---|
|
||||
| Model calls per turn | 12 |
|
||||
| Tool calls per turn | 24 |
|
||||
| Wall clock per turn | 60 s (checked before each model and tool call; a call in flight is bounded by the HTTP client timeout) |
|
||||
| Function calls in one model reply | 8 |
|
||||
| Agent transfers per turn | 4 |
|
||||
| Sub-agents per agent / graph depth | 16 / 6 |
|
||||
| Tools per agent | 32 |
|
||||
| Loop iterations / parallel branches | 10 / 8 |
|
||||
| User input | 8000 characters |
|
||||
| Tool result | 32768 bytes (larger becomes an error response) |
|
||||
| History sent to the model | 40 contents |
|
||||
| Sessions in memory / events per session | 1000 / 200 (oldest evicted) |
|
||||
| Session state keys / bytes per value | 64 / 8192 |
|
||||
| Memory entries / results per search | 1000 / 10 |
|
||||
| MCP pages / tools; HTTP body | 10 / 128; 1 MiB |
|
||||
| A2A text | 8000 characters |
|
||||
| Trigger queue / batch per dispatch | 1000 / 50 |
|
||||
| Cached thought signatures | 512 |
|
||||
|
||||
`RunLimits` may lower the first three, never raise them (validated).
|
||||
|
||||
## 3. Contracts
|
||||
|
||||
- Agents and tool names match `[A-Za-z_][A-Za-z0-9_]*`, 1..64. Session, user
|
||||
and trigger ids use `valid_segment`. All checked before any model call.
|
||||
- Runner loop (`Agent::run`): build request (instruction rendered with
|
||||
`{key}` state substitution, history, input, tool declarations, plus
|
||||
`transfer_to_agent` when the agent has sub-agents or a parent), call the
|
||||
model, execute function calls, send function responses, repeat until a
|
||||
text answer. Tool failures and unknown tools return `{"error": ...}` to the
|
||||
model; budget errors are never swallowed.
|
||||
- A cap hit does not throw: `RunResult.stop_reason` is one of `completed`,
|
||||
`max_steps`, `max_tool_calls`, `timeout`, `max_transfers`,
|
||||
`max_calls_per_step`, and the events so far are saved. Model errors
|
||||
(`GoogleError`) propagate and leave the session unchanged.
|
||||
- Workflow agents: Sequential (same input to each, data flows through
|
||||
`output_key` state), Parallel (one thread per branch, model must be
|
||||
thread safe, state and events merge in declaration order), Loop (until
|
||||
`exit_loop` or `max_iterations`). Routing is LLM transfer between a
|
||||
parent and its sub-agents.
|
||||
- Agent Studio definition: ADK Agent Config fields (`agent_class`, `name`,
|
||||
`model`, `description`, `instruction`, `tools: [{name}]`, `sub_agents`)
|
||||
plus `output_key` and `max_iterations`. Sub-agents are inlined; a
|
||||
`config_path` reference is rejected. Definitions name tools, never carry
|
||||
code; import resolves names through a `ToolRegistry`.
|
||||
- `DirectModel` request body is `GenerateRequest::to_json()`. Gemini 3
|
||||
rejects a replayed `functionCall` part without its `thoughtSignature`; the
|
||||
shared `Part` type has no such field, so `DirectModel` caches signatures by
|
||||
function name plus args and restores them on replay (foundation gap).
|
||||
- Triggers are local interfaces; Agent Runtime's BigQuery / Pub/Sub
|
||||
triggers belong to the runtime module.
|
||||
|
||||
## 4. Declared Google calls
|
||||
|
||||
One table, `kDirectCalls` in `direct_model.h`:
|
||||
|
||||
| Discovery service / version | rpc id | Method | Path |
|
||||
|---|---|---|---|
|
||||
| generativelanguage v1beta | models.generateContent | POST | `v1beta/models/{m}:generateContent` |
|
||||
| generativelanguage v1beta | models.streamGenerateContent | POST | `v1beta/models/{m}:streamGenerateContent` (`?alt=sse`) |
|
||||
| aiplatform v1 | publishers.models.generateContent | POST | `v1/publishers/{p}/models/{m}:generateContent` |
|
||||
| aiplatform v1 | publishers.models.streamGenerateContent | POST | `v1/publishers/{p}/models/{m}:streamGenerateContent` |
|
||||
|
||||
Request fields emitted: `contents`, `systemInstruction`, `tools`, `toolConfig`,
|
||||
`generationConfig`, `safetySettings`; Part field `thoughtSignature`.
|
||||
The ADK makes no other Google call. MCP and A2A are not Google APIs.
|
||||
|
||||
## 5. Verified against discovery
|
||||
|
||||
`python3 -I src/google/adk/tools/check_discovery.py` fetches the Discovery
|
||||
documents and fails when a declared method id, verb, flat path, request field
|
||||
or Part field is absent. Run 2026-10-24: PASS for all four rows and all
|
||||
fields (generativelanguage v1beta, aiplatform v1).
|
||||
Not in discovery by nature: MCP, A2A, AP2 (no Google REST resource).
|
||||
|
||||
## 6. Verified live (2026-10-24, express key, no cloud resource touched)
|
||||
|
||||
`MOLO_LIVE_NET=1 GOOGLE_API_KEY=... build/google_test` (tests `adk_live.*`;
|
||||
loud SKIP otherwise):
|
||||
|
||||
- `DirectModel` + `Runner` + `FunctionTool` against the real model over
|
||||
`aiplatform.googleapis.com/v1/publishers/google/models/gemini-3.5-flash:generateContent`
|
||||
(thinkingBudget 0, maxOutputTokens 200): the model called `get_weather`,
|
||||
received the function response, and answered using it (2 steps, 1 tool
|
||||
call, HTTP 200). This run first failed with 400 INVALID_ARGUMENT
|
||||
"missing a thought_signature"; the signature cache fixed it.
|
||||
- Multi-agent transfer: router agent called `transfer_to_agent`, the
|
||||
`math_helper` sub-agent answered; `RunResult.author` was `math_helper`. The
|
||||
arithmetic result is the model's and is not asserted (one run said 142 for
|
||||
12 x 12).
|
||||
- MCP: initialize, `tools/list` against the public unauthenticated
|
||||
`https://mcp.deepwiki.com/mcp` (replies as `text/event-stream`), tools
|
||||
mapped to ADK tools. `tools/call` was not run live.
|
||||
- Project-scoped path and OAuth-only calls: not exercised (no OAuth token
|
||||
here); the ADK does not need them.
|
||||
|
||||
## 7. Sources
|
||||
|
||||
- docs.cloud.google.com/gemini-enterprise-agent-platform/build/adk (overview;
|
||||
names ADK languages, workflow vs agent-coordinated orchestration)
|
||||
- .../build/agent-garden (library of prebuilt samples on GitHub; RAG named)
|
||||
- .../agent-studio/overview (prompt and model workspace; no export schema)
|
||||
- adk.dev/agents/config/ (Agent Config YAML: agent_class, model, name,
|
||||
description, instruction, tools, sub_agents with config_path)
|
||||
- modelcontextprotocol.io/specification/2025-06-18/server/tools (tools/list,
|
||||
tools/call, inputSchema, content, isError, nextCursor)
|
||||
- a2a-protocol.org/latest/specification/ (AgentCard fields, SendMessage,
|
||||
GetTask, Task, Message, Part, TaskState, `/.well-known/agent-card.json`)
|
||||
- ap2-protocol.org specification summary via search (Intent, Cart, Payment
|
||||
mandates)
|
||||
- Discovery documents: generativelanguage.googleapis.com and
|
||||
aiplatform.googleapis.com (`$discovery/rest`), ai.google.dev thought
|
||||
signatures page (named in the live 400 error).
|
||||
|
||||
## 8. Unverified
|
||||
|
||||
- A2A JSON-RPC wire strings: the fetched 1.0 spec text shows operation names
|
||||
`SendMessage` / `GetTask` and `ROLE_USER` / `TASK_STATE_*`; vendor docs
|
||||
show 1.0 binding using those PascalCase methods and 0.3 using `message/send`
|
||||
and `tasks/get`. Both dialects are implemented and selectable; the 1.0
|
||||
JSON-RPC result wrapping (`{task}` / `{message}`) is parsed tolerantly. No
|
||||
public A2A endpoint was found to test; A2A is spec-verified only, with
|
||||
scripted peers in tests.
|
||||
- MCP `tools/call` and the initialize handshake against servers that require
|
||||
`Mcp-Session-Id` (header handling follows the spec text, untested live).
|
||||
MCP inputSchema is passed to Gemini unchanged; Gemini may reject JSON Schema
|
||||
keywords outside its OpenAPI subset.
|
||||
- ADK config: `output_key` and `max_iterations` field names, and tool entries
|
||||
as `{name}` only (no `args`), were not confirmed on the config page.
|
||||
- Agent Garden: no template schema or API is published; the four templates
|
||||
(code modernization, financial analysis, economic research, invoice
|
||||
processing) and their instructions are local. The Garden page names none of
|
||||
those four.
|
||||
- AP2: field names of all three mandates are local; only the mandate roles
|
||||
were read. No signing or verification exists.
|
||||
- Agent Studio export / import: the overview page describes no export format;
|
||||
the format here is the ADK Agent Config subset.
|
||||
|
||||
## 9. Gaps
|
||||
|
||||
- `Part` lacks `thoughtSignature` (foundation, `gemini_types.h`); worked
|
||||
around in `DirectModel`. A custom `LanguageModel` that replays calls must
|
||||
do the same.
|
||||
- YAML input is not parsed (JSON only); YAML is emitted.
|
||||
- Streaming is exposed by `DirectModel::stream` but the runner loop uses
|
||||
`generate`.
|
||||
- Parallel branches need a thread-safe `LanguageModel`; `DirectModel` is.
|
||||
- No OAuth refresh, no persistence beyond memory (sessions module owns that).
|
||||
- MCP: no resources, prompts or SSE server push; A2A: no streaming, push
|
||||
notifications or cancel.
|
||||
@@ -0,0 +1,221 @@
|
||||
#include "google/adk/a2a.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
|
||||
#include "google/adk/caps.h"
|
||||
#include "google/adk/error.h"
|
||||
|
||||
namespace molo::google::adk {
|
||||
|
||||
using clients::body::Json;
|
||||
|
||||
namespace {
|
||||
|
||||
std::string str(const Json& o, const char* key) {
|
||||
const Json* v = o.is_object() ? o.find(key) : nullptr;
|
||||
return v && v->is_string() ? v->as_string() : "";
|
||||
}
|
||||
|
||||
std::string parts_text(const Json& holder) {
|
||||
std::string out;
|
||||
const Json* parts = holder.is_object() ? holder.find("parts") : nullptr;
|
||||
if (!parts || !parts->is_array()) return out;
|
||||
for (const Json& p : parts->as_array()) {
|
||||
std::string t = str(p, "text");
|
||||
if (t.empty()) continue;
|
||||
if (!out.empty()) out += "\n";
|
||||
out += t;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string normalize_state(std::string s) {
|
||||
if (s.rfind("TASK_STATE_", 0) == 0) s.erase(0, 11);
|
||||
for (char& c : s) c = c == '_' ? '-' : static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
|
||||
return s;
|
||||
}
|
||||
|
||||
class A2aTool : public Tool {
|
||||
public:
|
||||
A2aTool(std::shared_ptr<A2aClient> client, std::string name, std::string description)
|
||||
: client_(std::move(client)), name_(std::move(name)), description_(std::move(description)) {}
|
||||
const std::string& name() const override { return name_; }
|
||||
FunctionDeclaration declaration() const override {
|
||||
Json text = Json::object();
|
||||
text.set("type", Json("string"));
|
||||
Json props = Json::object();
|
||||
props.set("text", text);
|
||||
Json req = Json::array();
|
||||
req.push(Json("text"));
|
||||
Json schema = Json::object();
|
||||
schema.set("type", Json("object"));
|
||||
schema.set("properties", props);
|
||||
schema.set("required", req);
|
||||
FunctionDeclaration d;
|
||||
d.name = name_;
|
||||
d.description = description_;
|
||||
d.parameters = schema;
|
||||
return d;
|
||||
}
|
||||
Json call(const Json& args, ToolContext&) override {
|
||||
const Json* t = args.find("text");
|
||||
if (!t || !t->is_string()) throw AdkError::invalid("text is required");
|
||||
A2aTask task = client_->send_message(t->as_string());
|
||||
if (task.state == "failed" || task.state == "rejected" || task.state == "canceled")
|
||||
throw AdkError("tool", "remote agent " + task.state);
|
||||
Json out = Json::object();
|
||||
out.set("state", Json(task.state));
|
||||
out.set("text", Json(task.text));
|
||||
out.set("task_id", Json(task.id));
|
||||
return out;
|
||||
}
|
||||
|
||||
private:
|
||||
std::shared_ptr<A2aClient> client_;
|
||||
std::string name_;
|
||||
std::string description_;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
bool A2aTask::terminal() const {
|
||||
return state == "completed" || state == "failed" || state == "canceled" ||
|
||||
state == "rejected" || state == "message";
|
||||
}
|
||||
|
||||
A2aClient::A2aClient(std::shared_ptr<RemoteHttp> http, std::string base_url,
|
||||
A2aDialect dialect)
|
||||
: http_(std::move(http)), base_url_(std::move(base_url)), dialect_(dialect) {
|
||||
if (!http_) throw AdkError::invalid("A2aClient needs an http helper");
|
||||
if (!RemoteHttp::valid_url(base_url_)) throw AdkError::invalid("invalid A2A url");
|
||||
while (!base_url_.empty() && base_url_.back() == '/') base_url_.pop_back();
|
||||
endpoint_ = base_url_;
|
||||
}
|
||||
|
||||
A2aCard A2aClient::fetch_card() {
|
||||
RemoteReply reply = http_->get(base_url_ + card_path());
|
||||
Json doc;
|
||||
try {
|
||||
doc = Json::parse(reply.body);
|
||||
} catch (const std::exception& e) {
|
||||
throw AdkError("protocol", std::string("unreadable agent card: ") + e.what());
|
||||
}
|
||||
if (!doc.is_object() || str(doc, "name").empty())
|
||||
throw AdkError("protocol", "agent card has no name");
|
||||
A2aCard card;
|
||||
card.raw = doc;
|
||||
card.name = str(doc, "name");
|
||||
card.description = str(doc, "description");
|
||||
card.version = str(doc, "version");
|
||||
card.endpoint = str(doc, "url");
|
||||
if (const Json* si = doc.find("supportedInterfaces"); si && si->is_array())
|
||||
for (const Json& i : si->as_array())
|
||||
if (!str(i, "url").empty()) {
|
||||
card.endpoint = str(i, "url");
|
||||
break;
|
||||
}
|
||||
if (const Json* caps = doc.find("capabilities"); caps && caps->is_object())
|
||||
if (const Json* s = caps->find("streaming"); s && s->is_bool()) card.streaming = s->as_bool();
|
||||
if (const Json* sk = doc.find("skills"); sk && sk->is_array())
|
||||
for (const Json& s : sk->as_array())
|
||||
card.skills.push_back({str(s, "id"), str(s, "name"), str(s, "description")});
|
||||
if (!card.endpoint.empty()) {
|
||||
if (!RemoteHttp::valid_url(card.endpoint))
|
||||
throw AdkError("protocol", "agent card endpoint is not an http(s) url");
|
||||
endpoint_ = card.endpoint;
|
||||
}
|
||||
return card;
|
||||
}
|
||||
|
||||
Json A2aClient::rpc(const std::string& method, Json params) {
|
||||
Json req = Json::object();
|
||||
req.set("jsonrpc", Json("2.0"));
|
||||
req.set("id", Json(next_id_++));
|
||||
req.set("method", Json(method));
|
||||
req.set("params", std::move(params));
|
||||
RemoteReply reply = http_->post_json(endpoint_, req);
|
||||
Json doc;
|
||||
try {
|
||||
doc = Json::parse(reply.body);
|
||||
} catch (const std::exception& e) {
|
||||
throw AdkError("protocol", std::string("unreadable A2A reply: ") + e.what());
|
||||
}
|
||||
if (!doc.is_object()) throw AdkError("protocol", "A2A reply is not an object");
|
||||
if (const Json* err = doc.find("error"); err && err->is_object())
|
||||
throw AdkError("protocol", "A2A error: " + str(*err, "message"));
|
||||
const Json* result = doc.find("result");
|
||||
if (!result || !result->is_object()) throw AdkError("protocol", "A2A reply has no result");
|
||||
return *result;
|
||||
}
|
||||
|
||||
A2aTask A2aClient::parse_task(const Json& wrapped) const {
|
||||
const Json* result = &wrapped;
|
||||
if (const Json* t = wrapped.find("task"); t && t->is_object()) result = t;
|
||||
else if (const Json* m = wrapped.find("message"); m && m->is_object()) result = m;
|
||||
A2aTask task;
|
||||
task.raw = *result;
|
||||
task.context_id = str(*result, "contextId");
|
||||
if (result->has("status")) {
|
||||
task.id = str(*result, "id");
|
||||
const Json& status = *result->find("status");
|
||||
task.state = normalize_state(str(status, "state"));
|
||||
if (const Json* arts = result->find("artifacts"); arts && arts->is_array())
|
||||
for (const Json& a : arts->as_array()) {
|
||||
std::string t = parts_text(a);
|
||||
if (t.empty()) continue;
|
||||
if (!task.text.empty()) task.text += "\n";
|
||||
task.text += t;
|
||||
}
|
||||
if (task.text.empty())
|
||||
if (const Json* m = status.find("message")) task.text = parts_text(*m);
|
||||
} else if (result->has("parts")) {
|
||||
task.id = str(*result, "taskId");
|
||||
task.state = "message";
|
||||
task.text = parts_text(*result);
|
||||
} else {
|
||||
throw AdkError("protocol", "A2A result is neither a task nor a message");
|
||||
}
|
||||
if (task.text.size() > AdkCaps::kMaxA2aTextChars) task.text.resize(AdkCaps::kMaxA2aTextChars);
|
||||
return task;
|
||||
}
|
||||
|
||||
A2aTask A2aClient::send_message(const std::string& text, const std::string& context_id) {
|
||||
if (text.empty()) throw AdkError::invalid("empty message");
|
||||
if (text.size() > AdkCaps::kMaxA2aTextChars)
|
||||
throw AdkError::invalid("message over " + std::to_string(AdkCaps::kMaxA2aTextChars) +
|
||||
" characters");
|
||||
bool v1 = dialect_ == A2aDialect::kV1;
|
||||
Json part = Json::object();
|
||||
part.set("text", Json(text));
|
||||
if (!v1) part.set("kind", Json("text"));
|
||||
Json parts = Json::array();
|
||||
parts.push(part);
|
||||
Json message = Json::object();
|
||||
message.set("messageId", Json("adk-" + std::to_string(next_id_)));
|
||||
message.set("role", Json(v1 ? "ROLE_USER" : "user"));
|
||||
message.set("parts", parts);
|
||||
if (!v1) message.set("kind", Json("message"));
|
||||
if (!context_id.empty()) message.set("contextId", Json(context_id));
|
||||
Json params = Json::object();
|
||||
params.set("message", message);
|
||||
return parse_task(rpc(v1 ? "SendMessage" : "message/send", params));
|
||||
}
|
||||
|
||||
A2aTask A2aClient::get_task(const std::string& task_id) {
|
||||
if (task_id.empty() || task_id.size() > 256) throw AdkError::invalid("invalid task id");
|
||||
Json params = Json::object();
|
||||
params.set("id", Json(task_id));
|
||||
Json result = rpc(dialect_ == A2aDialect::kV1 ? "GetTask" : "tasks/get", params);
|
||||
A2aTask task = parse_task(result);
|
||||
if (task.state == "message") throw AdkError("protocol", "GetTask returned a message");
|
||||
return task;
|
||||
}
|
||||
|
||||
std::shared_ptr<Tool> A2aClient::as_tool(const std::string& name,
|
||||
const std::string& description) {
|
||||
if (!valid_identifier(name)) throw AdkError::invalid("invalid tool name");
|
||||
return std::make_shared<A2aTool>(shared_from_this(), name, description);
|
||||
}
|
||||
|
||||
} // namespace molo::google::adk
|
||||
@@ -0,0 +1,77 @@
|
||||
#pragma once
|
||||
|
||||
// A2A (Agent2Agent) client over JSON-RPC: fetch the agent card from
|
||||
// /.well-known/agent-card.json, send a message, get a task. The spec has two
|
||||
// wire dialects in the wild: 1.0 (PascalCase methods SendMessage / GetTask,
|
||||
// ROLE_USER, TASK_STATE_* strings, no "kind") and 0.3 (message/send,
|
||||
// tasks/get, "user", "kind":"text"). The dialect is explicit, default 1.0.
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "clients/body/json.h"
|
||||
#include "google/adk/remote_http.h"
|
||||
#include "google/adk/tool.h"
|
||||
|
||||
namespace molo::google::adk {
|
||||
|
||||
enum class A2aDialect { kV1, kV03 };
|
||||
|
||||
struct A2aSkill {
|
||||
std::string id;
|
||||
std::string name;
|
||||
std::string description;
|
||||
};
|
||||
|
||||
struct A2aCard {
|
||||
std::string name;
|
||||
std::string description;
|
||||
std::string version;
|
||||
std::string endpoint; // JSON-RPC URL: supportedInterfaces[0].url or url
|
||||
bool streaming = false;
|
||||
std::vector<A2aSkill> skills;
|
||||
clients::body::Json raw;
|
||||
};
|
||||
|
||||
struct A2aTask {
|
||||
std::string id;
|
||||
std::string context_id;
|
||||
// Normalized lowercase with dashes: submitted, working, completed,
|
||||
// failed, canceled, rejected, input-required, auth-required; "message"
|
||||
// when the peer answered with a plain message.
|
||||
std::string state;
|
||||
std::string text; // Artifact text, else status message text, capped
|
||||
clients::body::Json raw;
|
||||
bool terminal() const;
|
||||
};
|
||||
|
||||
class A2aClient : public std::enable_shared_from_this<A2aClient> {
|
||||
public:
|
||||
A2aClient(std::shared_ptr<RemoteHttp> http, std::string base_url,
|
||||
A2aDialect dialect = A2aDialect::kV1);
|
||||
|
||||
A2aCard fetch_card();
|
||||
A2aTask send_message(const std::string& text, const std::string& context_id = "");
|
||||
A2aTask get_task(const std::string& task_id);
|
||||
|
||||
// A remote agent as an ADK tool taking {"text": string}. The client must
|
||||
// be owned by a shared_ptr.
|
||||
std::shared_ptr<Tool> as_tool(const std::string& name,
|
||||
const std::string& description);
|
||||
|
||||
static const char* card_path() { return "/.well-known/agent-card.json"; }
|
||||
const std::string& endpoint() const { return endpoint_; }
|
||||
|
||||
private:
|
||||
clients::body::Json rpc(const std::string& method, clients::body::Json params);
|
||||
A2aTask parse_task(const clients::body::Json& result) const;
|
||||
|
||||
std::shared_ptr<RemoteHttp> http_;
|
||||
std::string base_url_;
|
||||
std::string endpoint_;
|
||||
A2aDialect dialect_;
|
||||
int next_id_ = 1;
|
||||
};
|
||||
|
||||
} // namespace molo::google::adk
|
||||
@@ -0,0 +1,337 @@
|
||||
#include "google/adk/agent.h"
|
||||
|
||||
#include <future>
|
||||
|
||||
#include "google/adk/caps.h"
|
||||
#include "google/adk/error.h"
|
||||
|
||||
namespace molo::google::adk {
|
||||
|
||||
using clients::body::Json;
|
||||
|
||||
namespace {
|
||||
|
||||
struct DepthGuard {
|
||||
explicit DepthGuard(RunContext& c) : ctx(c) {
|
||||
if (ctx.depth >= AdkCaps::kMaxAgentDepth)
|
||||
throw AdkError::invalid("agent graph deeper than the depth cap");
|
||||
++ctx.depth;
|
||||
}
|
||||
~DepthGuard() { --ctx.depth; }
|
||||
RunContext& ctx;
|
||||
};
|
||||
|
||||
Json as_object(Json v) {
|
||||
if (v.is_object()) return v;
|
||||
Json o = Json::object();
|
||||
o.set("result", std::move(v));
|
||||
return o;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// ---- Budget ---------------------------------------------------------------
|
||||
|
||||
Budget::Budget(int max_steps, int max_tool_calls, int wall_clock_ms)
|
||||
: max_steps_(max_steps),
|
||||
max_tools_(max_tool_calls),
|
||||
deadline_(std::chrono::steady_clock::now() +
|
||||
std::chrono::milliseconds(wall_clock_ms)) {}
|
||||
|
||||
void Budget::check_time() const {
|
||||
if (std::chrono::steady_clock::now() > deadline_)
|
||||
throw AdkError("budget", "timeout");
|
||||
}
|
||||
|
||||
void Budget::charge_step() {
|
||||
check_time();
|
||||
if (steps_.fetch_add(1) >= max_steps_) throw AdkError("budget", "max_steps");
|
||||
}
|
||||
|
||||
void Budget::charge_tool() {
|
||||
check_time();
|
||||
if (tools_.fetch_add(1) >= max_tools_)
|
||||
throw AdkError("budget", "max_tool_calls");
|
||||
}
|
||||
|
||||
// ---- RunContext -----------------------------------------------------------
|
||||
|
||||
RunContext RunContext::fork() const {
|
||||
RunContext r{model, budget};
|
||||
r.state = state;
|
||||
r.history = history;
|
||||
r.depth = depth;
|
||||
r.transfers = transfers;
|
||||
return r;
|
||||
}
|
||||
|
||||
void RunContext::merge(RunContext& branch) {
|
||||
for (auto& e : branch.events) events.push_back(std::move(e));
|
||||
if (branch.state.is_object())
|
||||
for (const auto& [k, v] : branch.state.as_object()) state.set(k, v);
|
||||
if (branch.escalate) escalate = true;
|
||||
}
|
||||
|
||||
// ---- BaseAgent ------------------------------------------------------------
|
||||
|
||||
BaseAgent::BaseAgent(std::string name, std::string description)
|
||||
: name_(std::move(name)), description_(std::move(description)) {
|
||||
if (!valid_identifier(name_))
|
||||
throw AdkError::invalid("agent name must match [A-Za-z_][A-Za-z0-9_]*");
|
||||
}
|
||||
|
||||
void BaseAgent::add_sub_agent(std::shared_ptr<BaseAgent> agent) {
|
||||
if (!agent) throw AdkError::invalid("null sub-agent");
|
||||
if (subs_.size() >= AdkCaps::kMaxSubAgents)
|
||||
throw AdkError::invalid("sub-agent count over the cap");
|
||||
if (agent->parent_) throw AdkError::invalid("agent already has a parent");
|
||||
for (const auto& s : subs_)
|
||||
if (s->name() == agent->name())
|
||||
throw AdkError::invalid("duplicate sub-agent name: " + agent->name());
|
||||
agent->parent_ = this;
|
||||
subs_.push_back(std::move(agent));
|
||||
}
|
||||
|
||||
BaseAgent* BaseAgent::find(const std::string& name) {
|
||||
if (name_ == name) return this;
|
||||
for (auto& s : subs_)
|
||||
if (BaseAgent* hit = s->find(name)) return hit;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// ---- Agent ----------------------------------------------------------------
|
||||
|
||||
Agent::Agent(Config config)
|
||||
: BaseAgent(config.name, config.description), config_(std::move(config)) {
|
||||
if (config_.instruction.size() > AdkCaps::kMaxInstructionBytes)
|
||||
throw AdkError::invalid("instruction over the byte cap");
|
||||
if (config_.tools.size() > AdkCaps::kMaxToolsPerAgent)
|
||||
throw AdkError::invalid("tool count over the cap");
|
||||
for (const auto& t : config_.tools) {
|
||||
if (!t) throw AdkError::invalid("null tool");
|
||||
if (t->name() == transfer_tool_name())
|
||||
throw AdkError::invalid("tool name is reserved: transfer_to_agent");
|
||||
}
|
||||
}
|
||||
|
||||
Tool* Agent::find_tool(const std::string& name) const {
|
||||
for (const auto& t : config_.tools)
|
||||
if (t->name() == name) return t.get();
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::string Agent::render_instruction(const std::string& text, const Json& state) {
|
||||
std::string out;
|
||||
for (std::size_t i = 0; i < text.size();) {
|
||||
if (text[i] == '{') {
|
||||
std::size_t end = text.find('}', i);
|
||||
if (end != std::string::npos) {
|
||||
std::string key = text.substr(i + 1, end - i - 1);
|
||||
if (valid_identifier(key) && state.is_object()) {
|
||||
if (const Json* v = state.find(key)) {
|
||||
out += v->is_string() ? v->as_string() : v->dump();
|
||||
i = end + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out += text[i++];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
FunctionDeclaration Agent::transfer_declaration() const {
|
||||
Json names = Json::array();
|
||||
std::string help;
|
||||
auto add = [&](const BaseAgent& a) {
|
||||
names.push(Json(a.name()));
|
||||
help += " " + a.name() + (a.description().empty() ? "" : " (" + a.description() + ");");
|
||||
};
|
||||
for (const auto& s : subs_) add(*s);
|
||||
if (parent_) add(*parent_);
|
||||
Json agent_name = Json::object();
|
||||
agent_name.set("type", Json("string"));
|
||||
agent_name.set("enum", names);
|
||||
Json props = Json::object();
|
||||
props.set("agent_name", agent_name);
|
||||
Json req = Json::array();
|
||||
req.push(Json("agent_name"));
|
||||
Json schema = Json::object();
|
||||
schema.set("type", Json("object"));
|
||||
schema.set("properties", props);
|
||||
schema.set("required", req);
|
||||
FunctionDeclaration d;
|
||||
d.name = transfer_tool_name();
|
||||
d.description = "Hand the conversation to another agent. Targets:" + help;
|
||||
d.parameters = schema;
|
||||
return d;
|
||||
}
|
||||
|
||||
Content Agent::transfer(RunContext& ctx, const Content& input, const Json& args) {
|
||||
const Json* n = args.find("agent_name");
|
||||
BaseAgent* target = nullptr;
|
||||
if (n && n->is_string()) {
|
||||
for (const auto& s : subs_)
|
||||
if (s->name() == n->as_string()) target = s.get();
|
||||
if (!target && parent_ && parent_->name() == n->as_string()) target = parent_;
|
||||
}
|
||||
if (!target) throw AdkError("tool", "unknown transfer target");
|
||||
if (++ctx.transfers > AdkCaps::kMaxTransfers)
|
||||
throw AdkError("budget", "max_transfers");
|
||||
return target->run(ctx, input);
|
||||
}
|
||||
|
||||
Content Agent::run(RunContext& ctx, const Content& input) {
|
||||
DepthGuard depth(ctx);
|
||||
GenerateRequest req;
|
||||
req.model = config_.model;
|
||||
req.config = config_.generate;
|
||||
std::string instruction = render_instruction(config_.instruction, ctx.state);
|
||||
if (!instruction.empty()) {
|
||||
Content sys;
|
||||
sys.parts.push_back(Part::of_text(instruction));
|
||||
req.system = sys;
|
||||
}
|
||||
req.contents = ctx.history;
|
||||
req.contents.push_back(input);
|
||||
|
||||
molo::google::Tool decl;
|
||||
for (const auto& t : config_.tools) decl.functions.push_back(t->declaration());
|
||||
bool can_transfer = config_.allow_transfer && (!subs_.empty() || parent_);
|
||||
if (can_transfer) decl.functions.push_back(transfer_declaration());
|
||||
if (!decl.functions.empty()) req.tools.push_back(decl);
|
||||
|
||||
for (;;) {
|
||||
ctx.budget.charge_step();
|
||||
GenerateResponse resp = ctx.model.generate(req);
|
||||
std::vector<FunctionCall> calls = resp.function_calls();
|
||||
|
||||
if (calls.empty()) {
|
||||
std::string text = resp.text();
|
||||
Content out = Content::model(text);
|
||||
ctx.events.push_back({name_, out, true});
|
||||
if (!config_.output_key.empty()) ctx.state.set(config_.output_key, Json(text));
|
||||
return out;
|
||||
}
|
||||
if (calls.size() > static_cast<std::size_t>(AdkCaps::kMaxCallsPerStep))
|
||||
throw AdkError("budget", "max_calls_per_step");
|
||||
|
||||
Content model_turn = resp.candidates.front().content;
|
||||
model_turn.role = "model";
|
||||
req.contents.push_back(model_turn);
|
||||
ctx.events.push_back({name_, model_turn, false});
|
||||
|
||||
Content replies;
|
||||
replies.role = "user";
|
||||
for (const FunctionCall& call : calls) {
|
||||
if (can_transfer && call.name == transfer_tool_name()) {
|
||||
try {
|
||||
return transfer(ctx, input, call.args);
|
||||
} catch (const AdkError& e) {
|
||||
if (e.code() == "budget") throw;
|
||||
Json err = Json::object();
|
||||
err.set("error", Json(e.message()));
|
||||
replies.parts.push_back(Part::of_response({call.name, err, call.id}));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
ctx.budget.charge_tool();
|
||||
Json result;
|
||||
Tool* tool = find_tool(call.name);
|
||||
if (!tool) {
|
||||
result = Json::object();
|
||||
result.set("error", Json("unknown tool: " + call.name));
|
||||
} else {
|
||||
try {
|
||||
bool escalate = false;
|
||||
ToolContext tc{ctx.state, name_, escalate};
|
||||
result = as_object(tool->call(call.args, tc));
|
||||
if (escalate) ctx.escalate = true;
|
||||
} catch (const AdkError& e) {
|
||||
if (e.code() == "budget") throw;
|
||||
result = Json::object();
|
||||
result.set("error", Json(e.message()));
|
||||
} catch (const std::exception& e) {
|
||||
result = Json::object();
|
||||
result.set("error", Json(std::string(e.what())));
|
||||
}
|
||||
if (result.dump().size() > AdkCaps::kMaxToolResultBytes) {
|
||||
result = Json::object();
|
||||
result.set("error", Json("tool result over " +
|
||||
std::to_string(AdkCaps::kMaxToolResultBytes) +
|
||||
" bytes"));
|
||||
}
|
||||
}
|
||||
replies.parts.push_back(Part::of_response({call.name, result, call.id}));
|
||||
}
|
||||
ctx.events.push_back({name_, replies, false});
|
||||
req.contents.push_back(replies);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Workflow agents ------------------------------------------------------
|
||||
|
||||
Content SequentialAgent::run(RunContext& ctx, const Content& input) {
|
||||
DepthGuard depth(ctx);
|
||||
Content last = Content::model("");
|
||||
for (const auto& s : subs_) last = s->run(ctx, input);
|
||||
return last;
|
||||
}
|
||||
|
||||
Content ParallelAgent::run(RunContext& ctx, const Content& input) {
|
||||
DepthGuard depth(ctx);
|
||||
if (subs_.size() > AdkCaps::kMaxParallelBranches)
|
||||
throw AdkError::invalid("parallel branches over the cap");
|
||||
std::vector<RunContext> branches;
|
||||
branches.reserve(subs_.size());
|
||||
for (std::size_t i = 0; i < subs_.size(); ++i) branches.push_back(ctx.fork());
|
||||
std::vector<std::future<Content>> futures;
|
||||
for (std::size_t i = 0; i < subs_.size(); ++i)
|
||||
futures.push_back(std::async(std::launch::async, [&, i] {
|
||||
return subs_[i]->run(branches[i], input);
|
||||
}));
|
||||
std::vector<Content> outs(subs_.size());
|
||||
std::exception_ptr first;
|
||||
for (std::size_t i = 0; i < futures.size(); ++i) {
|
||||
try {
|
||||
outs[i] = futures[i].get();
|
||||
} catch (...) {
|
||||
if (!first) first = std::current_exception();
|
||||
}
|
||||
}
|
||||
if (first) std::rethrow_exception(first);
|
||||
std::string text;
|
||||
for (std::size_t i = 0; i < subs_.size(); ++i) {
|
||||
ctx.merge(branches[i]);
|
||||
if (!text.empty()) text += "\n\n";
|
||||
text += subs_[i]->name() + ": " + outs[i].text();
|
||||
}
|
||||
return Content::model(text);
|
||||
}
|
||||
|
||||
LoopAgent::LoopAgent(std::string name, std::string description, int max_iterations)
|
||||
: BaseAgent(std::move(name), std::move(description)),
|
||||
max_iterations_(max_iterations) {
|
||||
if (max_iterations_ < 1 || max_iterations_ > AdkCaps::kMaxLoopIterations)
|
||||
throw AdkError::invalid("max_iterations outside 1.." +
|
||||
std::to_string(AdkCaps::kMaxLoopIterations));
|
||||
}
|
||||
|
||||
Content LoopAgent::run(RunContext& ctx, const Content& input) {
|
||||
DepthGuard depth(ctx);
|
||||
Content last = Content::model("");
|
||||
for (int i = 0; i < max_iterations_; ++i) {
|
||||
for (const auto& s : subs_) {
|
||||
last = s->run(ctx, input);
|
||||
if (ctx.escalate) break;
|
||||
}
|
||||
if (ctx.escalate) {
|
||||
ctx.escalate = false; // Consumed by this loop, not by an outer one.
|
||||
break;
|
||||
}
|
||||
}
|
||||
return last;
|
||||
}
|
||||
|
||||
} // namespace molo::google::adk
|
||||
@@ -0,0 +1,156 @@
|
||||
#pragma once
|
||||
|
||||
// Agents of the ADK. BaseAgent is the tree node; Agent is the LLM agent
|
||||
// (instruction, model, tools, sub-agents, transfer); SequentialAgent,
|
||||
// ParallelAgent and LoopAgent are workflow agents that run their
|
||||
// sub-agents without a model of their own.
|
||||
//
|
||||
// Agents share data through session state: an Agent with output_key stores
|
||||
// its final text under that key, and instructions may reference state with
|
||||
// {key}. Parent pointers are raw: the parent owns its children, so a child
|
||||
// must not outlive its parent.
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "clients/body/json.h"
|
||||
#include "google/adk/session.h"
|
||||
#include "google/adk/tool.h"
|
||||
#include "google/gemini_types.h"
|
||||
|
||||
namespace molo::google::adk {
|
||||
|
||||
// Per-turn budget shared by the whole agent graph, parallel branches
|
||||
// included. Throws AdkError("budget", reason) with reason one of
|
||||
// max_steps, max_tool_calls, timeout. The wall clock is checked before every
|
||||
// model call and tool call; it cannot interrupt a call in flight (the HTTP
|
||||
// client timeout bounds that).
|
||||
class Budget {
|
||||
public:
|
||||
Budget(int max_steps, int max_tool_calls, int wall_clock_ms);
|
||||
void charge_step();
|
||||
void charge_tool();
|
||||
void check_time() const;
|
||||
int steps() const { return steps_.load(); }
|
||||
int tool_calls() const { return tools_.load(); }
|
||||
|
||||
private:
|
||||
int max_steps_;
|
||||
int max_tools_;
|
||||
std::chrono::steady_clock::time_point deadline_;
|
||||
std::atomic<int> steps_{0};
|
||||
std::atomic<int> tools_{0};
|
||||
};
|
||||
|
||||
struct RunContext {
|
||||
RunContext(LanguageModel& m, Budget& b) : model(m), budget(b) {}
|
||||
LanguageModel& model;
|
||||
Budget& budget;
|
||||
clients::body::Json state = clients::body::Json::object();
|
||||
std::vector<Event> events; // Appended during this turn.
|
||||
std::vector<Content> history; // Prior turns (text only).
|
||||
int depth = 0;
|
||||
int transfers = 0;
|
||||
bool escalate = false; // Set by exit_loop.
|
||||
|
||||
// A copy with empty events and the same budget, for a parallel branch.
|
||||
RunContext fork() const;
|
||||
// Appends the branch's events and copies its state keys over ours.
|
||||
void merge(RunContext& branch);
|
||||
};
|
||||
|
||||
class BaseAgent {
|
||||
public:
|
||||
BaseAgent(std::string name, std::string description);
|
||||
virtual ~BaseAgent() = default;
|
||||
|
||||
const std::string& name() const { return name_; }
|
||||
const std::string& description() const { return description_; }
|
||||
const std::vector<std::shared_ptr<BaseAgent>>& sub_agents() const { return subs_; }
|
||||
BaseAgent* parent() const { return parent_; }
|
||||
|
||||
// Names must be unique among siblings; at most kMaxSubAgents.
|
||||
void add_sub_agent(std::shared_ptr<BaseAgent> agent);
|
||||
// Depth-first search of this node and its descendants.
|
||||
BaseAgent* find(const std::string& name);
|
||||
|
||||
virtual std::string kind() const = 0;
|
||||
virtual Content run(RunContext& context, const Content& input) = 0;
|
||||
|
||||
protected:
|
||||
std::string name_;
|
||||
std::string description_;
|
||||
std::vector<std::shared_ptr<BaseAgent>> subs_;
|
||||
BaseAgent* parent_ = nullptr;
|
||||
};
|
||||
|
||||
class Agent : public BaseAgent {
|
||||
public:
|
||||
struct Config {
|
||||
std::string name;
|
||||
std::string description;
|
||||
std::string model; // e.g. "gemini-2.5-flash"
|
||||
std::string instruction;
|
||||
std::vector<std::shared_ptr<Tool>> tools;
|
||||
std::string output_key; // Empty: do not write state.
|
||||
GenerateConfig generate;
|
||||
bool allow_transfer = true; // Expose transfer_to_agent when linked.
|
||||
};
|
||||
explicit Agent(Config config);
|
||||
|
||||
const Config& config() const { return config_; }
|
||||
std::string kind() const override { return "LlmAgent"; }
|
||||
Content run(RunContext& context, const Content& input) override;
|
||||
|
||||
// Name of the built-in transfer function.
|
||||
static const char* transfer_tool_name() { return "transfer_to_agent"; }
|
||||
// {key} substitution from state (strings raw, others as JSON); unknown
|
||||
// keys stay literal.
|
||||
static std::string render_instruction(const std::string& text,
|
||||
const clients::body::Json& state);
|
||||
|
||||
private:
|
||||
Tool* find_tool(const std::string& name) const;
|
||||
FunctionDeclaration transfer_declaration() const;
|
||||
Content transfer(RunContext& context, const Content& input,
|
||||
const clients::body::Json& args);
|
||||
|
||||
Config config_;
|
||||
};
|
||||
|
||||
class SequentialAgent : public BaseAgent {
|
||||
public:
|
||||
using BaseAgent::BaseAgent;
|
||||
std::string kind() const override { return "SequentialAgent"; }
|
||||
// Every sub-agent sees the original input; they pass data through state
|
||||
// (output_key). The result is the last sub-agent's answer.
|
||||
Content run(RunContext& context, const Content& input) override;
|
||||
};
|
||||
|
||||
class ParallelAgent : public BaseAgent {
|
||||
public:
|
||||
using BaseAgent::BaseAgent;
|
||||
std::string kind() const override { return "ParallelAgent"; }
|
||||
// One thread per branch (at most kMaxParallelBranches). The model must be
|
||||
// safe to call concurrently. Events and state merge in declaration order.
|
||||
// Result: "name: text" blocks joined by blank lines.
|
||||
Content run(RunContext& context, const Content& input) override;
|
||||
};
|
||||
|
||||
class LoopAgent : public BaseAgent {
|
||||
public:
|
||||
LoopAgent(std::string name, std::string description, int max_iterations);
|
||||
int max_iterations() const { return max_iterations_; }
|
||||
std::string kind() const override { return "LoopAgent"; }
|
||||
// Runs the sub-agents in order, up to max_iterations times, stopping when
|
||||
// a tool sets escalate (exit_loop).
|
||||
Content run(RunContext& context, const Content& input) override;
|
||||
|
||||
private:
|
||||
int max_iterations_;
|
||||
};
|
||||
|
||||
} // namespace molo::google::adk
|
||||
@@ -0,0 +1,172 @@
|
||||
#include "google/adk/ap2.h"
|
||||
|
||||
#include "google/adk/error.h"
|
||||
#include "google/resource.h"
|
||||
|
||||
namespace molo::google::adk::ap2 {
|
||||
|
||||
using clients::body::Json;
|
||||
|
||||
namespace {
|
||||
|
||||
void need_id(const std::string& id, const char* what) {
|
||||
if (!valid_segment(id)) throw AdkError::invalid(std::string("invalid ") + what);
|
||||
}
|
||||
|
||||
void need_currency(const std::string& c) {
|
||||
if (c.size() != 3) throw AdkError::invalid("currency must be 3 uppercase letters");
|
||||
for (char ch : c)
|
||||
if (ch < 'A' || ch > 'Z') throw AdkError::invalid("currency must be 3 uppercase letters");
|
||||
}
|
||||
|
||||
std::string str(const Json& o, const char* key) {
|
||||
const Json* v = o.is_object() ? o.find(key) : nullptr;
|
||||
return v && v->is_string() ? v->as_string() : "";
|
||||
}
|
||||
long num(const Json& o, const char* key) {
|
||||
const Json* v = o.is_object() ? o.find(key) : nullptr;
|
||||
return v && v->is_number() ? v->as_int() : 0;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void IntentMandate::validate() const {
|
||||
need_id(id, "intent id");
|
||||
if (description.empty() || description.size() > 1000)
|
||||
throw AdkError::invalid("intent description must be 1..1000 characters");
|
||||
if (merchants.size() > 50) throw AdkError::invalid("over 50 merchants");
|
||||
if (max_amount_minor < 1) throw AdkError::invalid("max_amount_minor must be positive");
|
||||
need_currency(currency);
|
||||
}
|
||||
|
||||
Json IntentMandate::to_json() const {
|
||||
Json o = Json::object();
|
||||
o.set("id", Json(id));
|
||||
o.set("description", Json(description));
|
||||
Json m = Json::array();
|
||||
for (const auto& s : merchants) m.push(Json(s));
|
||||
o.set("merchants", m);
|
||||
o.set("max_amount_minor", Json(max_amount_minor));
|
||||
o.set("currency", Json(currency));
|
||||
o.set("expires_at", Json(expires_at));
|
||||
o.set("signature", Json(signature));
|
||||
return o;
|
||||
}
|
||||
|
||||
IntentMandate IntentMandate::from_json(const Json& d) {
|
||||
IntentMandate m;
|
||||
m.id = str(d, "id");
|
||||
m.description = str(d, "description");
|
||||
if (const Json* a = d.find("merchants"); a && a->is_array())
|
||||
for (const Json& s : a->as_array())
|
||||
if (s.is_string()) m.merchants.push_back(s.as_string());
|
||||
m.max_amount_minor = num(d, "max_amount_minor");
|
||||
m.currency = str(d, "currency");
|
||||
m.expires_at = str(d, "expires_at");
|
||||
m.signature = str(d, "signature");
|
||||
return m;
|
||||
}
|
||||
|
||||
void CartMandate::validate() const {
|
||||
need_id(id, "cart id");
|
||||
need_id(intent_id, "intent id");
|
||||
if (merchant.empty() || merchant.size() > 200) throw AdkError::invalid("invalid merchant");
|
||||
if (items.empty() || items.size() > 50) throw AdkError::invalid("cart needs 1..50 items");
|
||||
need_currency(currency);
|
||||
long sum = 0;
|
||||
for (const CartItem& i : items) {
|
||||
if (i.sku.empty() || i.sku.size() > 128) throw AdkError::invalid("invalid sku");
|
||||
if (i.quantity < 1 || i.quantity > 1000) throw AdkError::invalid("quantity outside 1..1000");
|
||||
if (i.unit_amount_minor < 0) throw AdkError::invalid("negative unit amount");
|
||||
sum += static_cast<long>(i.quantity) * i.unit_amount_minor;
|
||||
}
|
||||
if (sum != total_minor) throw AdkError::invalid("total_minor does not equal the item sum");
|
||||
}
|
||||
|
||||
void CartMandate::validate_against(const IntentMandate& intent) const {
|
||||
validate();
|
||||
if (intent_id != intent.id) throw AdkError::invalid("cart belongs to another intent");
|
||||
if (currency != intent.currency) throw AdkError::invalid("currency differs from the intent");
|
||||
if (total_minor > intent.max_amount_minor) throw AdkError::invalid("cart total exceeds the intent cap");
|
||||
if (!intent.merchants.empty()) {
|
||||
bool ok = false;
|
||||
for (const auto& m : intent.merchants) ok = ok || m == merchant;
|
||||
if (!ok) throw AdkError::invalid("merchant not allowed by the intent");
|
||||
}
|
||||
}
|
||||
|
||||
Json CartMandate::to_json() const {
|
||||
Json o = Json::object();
|
||||
o.set("id", Json(id));
|
||||
o.set("intent_id", Json(intent_id));
|
||||
o.set("merchant", Json(merchant));
|
||||
Json arr = Json::array();
|
||||
for (const CartItem& i : items) {
|
||||
Json it = Json::object();
|
||||
it.set("sku", Json(i.sku));
|
||||
it.set("label", Json(i.label));
|
||||
it.set("quantity", Json(i.quantity));
|
||||
it.set("unit_amount_minor", Json(i.unit_amount_minor));
|
||||
arr.push(it);
|
||||
}
|
||||
o.set("items", arr);
|
||||
o.set("total_minor", Json(total_minor));
|
||||
o.set("currency", Json(currency));
|
||||
o.set("signature", Json(signature));
|
||||
return o;
|
||||
}
|
||||
|
||||
CartMandate CartMandate::from_json(const Json& d) {
|
||||
CartMandate m;
|
||||
m.id = str(d, "id");
|
||||
m.intent_id = str(d, "intent_id");
|
||||
m.merchant = str(d, "merchant");
|
||||
if (const Json* a = d.find("items"); a && a->is_array())
|
||||
for (const Json& i : a->as_array())
|
||||
m.items.push_back({str(i, "sku"), str(i, "label"), static_cast<int>(num(i, "quantity")),
|
||||
num(i, "unit_amount_minor")});
|
||||
m.total_minor = num(d, "total_minor");
|
||||
m.currency = str(d, "currency");
|
||||
m.signature = str(d, "signature");
|
||||
return m;
|
||||
}
|
||||
|
||||
void PaymentMandate::validate() const {
|
||||
need_id(id, "payment id");
|
||||
need_id(cart_id, "cart id");
|
||||
if (payment_method_token.empty() || payment_method_token.size() > 512)
|
||||
throw AdkError::invalid("payment_method_token must be 1..512 characters");
|
||||
if (amount_minor < 1) throw AdkError::invalid("amount_minor must be positive");
|
||||
need_currency(currency);
|
||||
}
|
||||
|
||||
void PaymentMandate::validate_against(const CartMandate& cart) const {
|
||||
validate();
|
||||
if (cart_id != cart.id) throw AdkError::invalid("payment belongs to another cart");
|
||||
if (currency != cart.currency) throw AdkError::invalid("currency differs from the cart");
|
||||
if (amount_minor != cart.total_minor) throw AdkError::invalid("amount differs from the cart total");
|
||||
}
|
||||
|
||||
Json PaymentMandate::to_json() const {
|
||||
Json o = Json::object();
|
||||
o.set("id", Json(id));
|
||||
o.set("cart_id", Json(cart_id));
|
||||
o.set("payment_method_token", Json(payment_method_token));
|
||||
o.set("amount_minor", Json(amount_minor));
|
||||
o.set("currency", Json(currency));
|
||||
o.set("signature", Json(signature));
|
||||
return o;
|
||||
}
|
||||
|
||||
PaymentMandate PaymentMandate::from_json(const Json& d) {
|
||||
PaymentMandate m;
|
||||
m.id = str(d, "id");
|
||||
m.cart_id = str(d, "cart_id");
|
||||
m.payment_method_token = str(d, "payment_method_token");
|
||||
m.amount_minor = num(d, "amount_minor");
|
||||
m.currency = str(d, "currency");
|
||||
m.signature = str(d, "signature");
|
||||
return m;
|
||||
}
|
||||
|
||||
} // namespace molo::google::adk::ap2
|
||||
@@ -0,0 +1,69 @@
|
||||
#pragma once
|
||||
|
||||
// Agent Payments Protocol (AP2) message types: IntentMandate, CartMandate,
|
||||
// PaymentMandate. LOCAL types: only the three mandate names and their roles
|
||||
// were read (ap2-protocol.org spec summary); field names are this module's
|
||||
// own and are listed under Unverified in SPEC.md. No signing, no payment
|
||||
// network calls: `signature` is an opaque string the caller supplies.
|
||||
// Amounts are integer minor units (cents) to avoid floating point money.
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "clients/body/json.h"
|
||||
|
||||
namespace molo::google::adk::ap2 {
|
||||
|
||||
struct IntentMandate {
|
||||
std::string id;
|
||||
std::string description; // What the user wants the agent to buy
|
||||
std::vector<std::string> merchants; // Allowed merchants, empty: any
|
||||
long max_amount_minor = 0;
|
||||
std::string currency; // ISO 4217, three uppercase letters
|
||||
std::string expires_at; // RFC 3339 timestamp, as given
|
||||
std::string signature;
|
||||
|
||||
void validate() const; // Throws AdkError (invalid_argument)
|
||||
clients::body::Json to_json() const;
|
||||
static IntentMandate from_json(const clients::body::Json& doc);
|
||||
};
|
||||
|
||||
struct CartItem {
|
||||
std::string sku;
|
||||
std::string label;
|
||||
int quantity = 1;
|
||||
long unit_amount_minor = 0;
|
||||
};
|
||||
|
||||
struct CartMandate {
|
||||
std::string id;
|
||||
std::string intent_id;
|
||||
std::string merchant;
|
||||
std::vector<CartItem> items;
|
||||
long total_minor = 0;
|
||||
std::string currency;
|
||||
std::string signature;
|
||||
|
||||
// Items 1..50, quantities 1..1000, and total equals the item sum.
|
||||
void validate() const;
|
||||
// Also checks the cart against its intent (currency, merchant, cap).
|
||||
void validate_against(const IntentMandate& intent) const;
|
||||
clients::body::Json to_json() const;
|
||||
static CartMandate from_json(const clients::body::Json& doc);
|
||||
};
|
||||
|
||||
struct PaymentMandate {
|
||||
std::string id;
|
||||
std::string cart_id;
|
||||
std::string payment_method_token; // Opaque token, never a card number
|
||||
long amount_minor = 0;
|
||||
std::string currency;
|
||||
std::string signature;
|
||||
|
||||
void validate() const;
|
||||
void validate_against(const CartMandate& cart) const;
|
||||
clients::body::Json to_json() const;
|
||||
static PaymentMandate from_json(const clients::body::Json& doc);
|
||||
};
|
||||
|
||||
} // namespace molo::google::adk::ap2
|
||||
@@ -0,0 +1,53 @@
|
||||
#pragma once
|
||||
|
||||
// Static ceilings for the Agent Development Kit. Never autotuned. Every
|
||||
// loop, list, size and wait in this module is bounded by one of these.
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
namespace molo::google::adk {
|
||||
|
||||
struct AdkCaps {
|
||||
// Runner budget per turn (whole agent graph, parallel branches included).
|
||||
static constexpr int kMaxSteps = 12; // model calls
|
||||
static constexpr int kMaxToolCalls = 24; // tool invocations
|
||||
static constexpr int kMaxWallClockMs = 60000; // checked between steps
|
||||
static constexpr int kMaxCallsPerStep = 8; // function calls in one reply
|
||||
static constexpr int kMaxTransfers = 4; // agent transfers per turn
|
||||
|
||||
// Graph shape.
|
||||
static constexpr std::size_t kMaxSubAgents = 16;
|
||||
static constexpr int kMaxAgentDepth = 6;
|
||||
static constexpr std::size_t kMaxToolsPerAgent = 32;
|
||||
static constexpr int kMaxLoopIterations = 10;
|
||||
static constexpr std::size_t kMaxParallelBranches = 8;
|
||||
static constexpr std::size_t kMaxNameChars = 64;
|
||||
static constexpr std::size_t kMaxInstructionBytes = 16384;
|
||||
|
||||
// Sizes.
|
||||
static constexpr std::size_t kMaxInputChars = 8000;
|
||||
static constexpr std::size_t kMaxToolResultBytes = 32768;
|
||||
static constexpr std::size_t kMaxHistoryContents = 40;
|
||||
static constexpr std::size_t kMaxHttpBodyBytes = 1024u * 1024u;
|
||||
static constexpr std::size_t kMaxDefinitionBytes = 64u * 1024u;
|
||||
|
||||
// Sessions and memory (in-memory defaults).
|
||||
static constexpr std::size_t kMaxSessions = 1000;
|
||||
static constexpr std::size_t kMaxEventsPerSession = 200;
|
||||
static constexpr std::size_t kMaxStateKeys = 64;
|
||||
static constexpr std::size_t kMaxStateValueBytes = 8192;
|
||||
static constexpr std::size_t kMaxMemoryEntries = 1000;
|
||||
static constexpr std::size_t kMaxMemoryResults = 10;
|
||||
|
||||
// Protocol clients.
|
||||
static constexpr int kMaxMcpPages = 10;
|
||||
static constexpr std::size_t kMaxMcpTools = 128;
|
||||
static constexpr std::size_t kMaxA2aTextChars = 8000;
|
||||
static constexpr std::size_t kMaxThoughtSignatures = 512; // DirectModel cache
|
||||
|
||||
// Triggers.
|
||||
static constexpr std::size_t kMaxTriggerBatch = 50;
|
||||
static constexpr std::size_t kMaxTriggerQueue = 1000;
|
||||
};
|
||||
|
||||
} // namespace molo::google::adk
|
||||
@@ -0,0 +1,97 @@
|
||||
#include "google/adk/direct_model.h"
|
||||
|
||||
#include "google/adk/caps.h"
|
||||
#include "google/resource.h"
|
||||
|
||||
namespace molo::google::adk {
|
||||
|
||||
using clients::body::Json;
|
||||
|
||||
DirectModel::DirectModel(std::shared_ptr<GoogleClient> client,
|
||||
std::string default_model, ServiceEndpoint endpoint)
|
||||
: client_(std::move(client)),
|
||||
default_model_(std::move(default_model)),
|
||||
endpoint_(std::move(endpoint)) {
|
||||
if (!client_) throw GoogleError::invalid("DirectModel needs a client");
|
||||
if (!valid_segment(default_model_))
|
||||
throw GoogleError::invalid("invalid default model id");
|
||||
}
|
||||
|
||||
std::string DirectModel::model_path(const GenerateRequest& request) const {
|
||||
const std::string& m = request.model.empty() ? default_model_ : request.model;
|
||||
if (!valid_segment(m)) throw GoogleError::invalid("invalid model id");
|
||||
return "/models/" + m;
|
||||
}
|
||||
|
||||
namespace {
|
||||
std::string call_key(const Json& call) {
|
||||
const Json* n = call.find("name");
|
||||
const Json* a = call.find("args");
|
||||
return (n && n->is_string() ? n->as_string() : "") + "\n" +
|
||||
(a ? a->dump() : "{}");
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void DirectModel::remember_signatures(const Json& response) {
|
||||
const Json* cands = response.find("candidates");
|
||||
if (!cands || !cands->is_array()) return;
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
for (const Json& c : cands->as_array()) {
|
||||
const Json* content = c.find("content");
|
||||
const Json* parts = content ? content->find("parts") : nullptr;
|
||||
if (!parts || !parts->is_array()) continue;
|
||||
for (const Json& p : parts->as_array()) {
|
||||
const Json* call = p.find("functionCall");
|
||||
const Json* sig = p.find("thoughtSignature");
|
||||
if (!call || !sig || !sig->is_string()) continue;
|
||||
std::string key = call_key(*call);
|
||||
if (!signatures_.count(key)) signature_order_.push_back(key);
|
||||
signatures_[key] = sig->as_string();
|
||||
while (signature_order_.size() > AdkCaps::kMaxThoughtSignatures) {
|
||||
signatures_.erase(signature_order_.front());
|
||||
signature_order_.pop_front();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Json DirectModel::restore_signatures(Json body) {
|
||||
Json* contents = body.is_object() && body.has("contents")
|
||||
? &body.as_object().find("contents")->second
|
||||
: nullptr;
|
||||
if (!contents || !contents->is_array()) return body;
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
for (Json& content : contents->as_array()) {
|
||||
if (!content.is_object() || !content.as_object().count("parts")) continue;
|
||||
Json& parts = content.as_object().find("parts")->second;
|
||||
if (!parts.is_array()) continue;
|
||||
for (Json& p : parts.as_array()) {
|
||||
if (!p.is_object() || p.has("thoughtSignature")) continue;
|
||||
auto call = p.as_object().find("functionCall");
|
||||
if (call == p.as_object().end()) continue;
|
||||
auto sig = signatures_.find(call_key(call->second));
|
||||
if (sig != signatures_.end()) p.set("thoughtSignature", Json(sig->second));
|
||||
}
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
GenerateResponse DirectModel::generate(const GenerateRequest& request) {
|
||||
std::string path = model_path(request) + ":generateContent";
|
||||
Json raw = client_->post_json(endpoint_, path, restore_signatures(request.to_json()));
|
||||
remember_signatures(raw);
|
||||
return GenerateResponse::from_json(raw);
|
||||
}
|
||||
|
||||
void DirectModel::stream(
|
||||
const GenerateRequest& request,
|
||||
const std::function<bool(const GenerateResponse&)>& on_chunk) {
|
||||
client_->stream_json(
|
||||
endpoint_, model_path(request) + ":streamGenerateContent?alt=sse",
|
||||
restore_signatures(request.to_json()), [&](const Json& event) {
|
||||
remember_signatures(event);
|
||||
return on_chunk(GenerateResponse::from_json(event));
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace molo::google::adk
|
||||
@@ -0,0 +1,74 @@
|
||||
#pragma once
|
||||
|
||||
// DirectModel: a private LanguageModel over GoogleClient so the ADK needs no
|
||||
// other agent-platform module. POST models/{m}:generateContent and
|
||||
// :streamGenerateContent?alt=sse against one ServiceEndpoint (default: the
|
||||
// Gemini API; pass endpoints::vertex_generative() for express keys).
|
||||
|
||||
#include <deque>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
|
||||
#include "google/client.h"
|
||||
#include "google/gemini_types.h"
|
||||
|
||||
namespace molo::google::adk {
|
||||
|
||||
// Every Google call this module makes, in one table. tools/check_discovery.py
|
||||
// parses the rows between the markers and fails when Google's Discovery
|
||||
// document lacks the method, the HTTP verb or the flat path, or when a
|
||||
// request field name is missing from the request schema.
|
||||
struct DirectCall {
|
||||
const char* service; // Discovery service host prefix
|
||||
const char* version; // Discovery version
|
||||
const char* rpc; // Discovery method id
|
||||
const char* http; // HTTP verb
|
||||
const char* flat_path; // Discovery flatPath template (path after the host)
|
||||
};
|
||||
// DISCOVERY-TABLE-BEGIN
|
||||
inline constexpr DirectCall kDirectCalls[] = {
|
||||
{"generativelanguage", "v1beta", "models.generateContent", "POST", "v1beta/models/{modelsId}:generateContent"},
|
||||
{"generativelanguage", "v1beta", "models.streamGenerateContent", "POST", "v1beta/models/{modelsId}:streamGenerateContent"},
|
||||
{"aiplatform", "v1", "publishers.models.generateContent", "POST", "v1/publishers/{publishersId}/models/{modelsId}:generateContent"},
|
||||
{"aiplatform", "v1", "publishers.models.streamGenerateContent", "POST", "v1/publishers/{publishersId}/models/{modelsId}:streamGenerateContent"},
|
||||
};
|
||||
// Top-level request fields GenerateRequest::to_json may emit; each must exist
|
||||
// in both request schemas above.
|
||||
inline constexpr const char* kDirectRequestFields[] = {
|
||||
"contents", "systemInstruction", "tools", "toolConfig", "generationConfig", "safetySettings",
|
||||
};
|
||||
inline constexpr const char* kDirectPartFields[] = {"thoughtSignature"}; // on Part
|
||||
// DISCOVERY-TABLE-END
|
||||
|
||||
class DirectModel : public LanguageModel {
|
||||
public:
|
||||
// default_model is used when a request names no model.
|
||||
DirectModel(std::shared_ptr<GoogleClient> client, std::string default_model,
|
||||
ServiceEndpoint endpoint = endpoints::generative());
|
||||
|
||||
GenerateResponse generate(const GenerateRequest& request) override;
|
||||
void stream(const GenerateRequest& request,
|
||||
const std::function<bool(const GenerateResponse&)>& on_chunk) override;
|
||||
|
||||
private:
|
||||
std::string model_path(const GenerateRequest& request) const;
|
||||
// Gemini 3 rejects a replayed functionCall part that lacks the
|
||||
// thoughtSignature it was issued with, and the shared Part type does not
|
||||
// carry that field (foundation gap). We keep the signature of every
|
||||
// functionCall we receive, keyed by name plus args, and put it back on the
|
||||
// matching part when the call is replayed. Bounded FIFO.
|
||||
void remember_signatures(const clients::body::Json& response);
|
||||
clients::body::Json restore_signatures(clients::body::Json body);
|
||||
|
||||
std::mutex mutex_;
|
||||
std::map<std::string, std::string> signatures_;
|
||||
std::deque<std::string> signature_order_;
|
||||
|
||||
std::shared_ptr<GoogleClient> client_;
|
||||
std::string default_model_;
|
||||
ServiceEndpoint endpoint_;
|
||||
};
|
||||
|
||||
} // namespace molo::google::adk
|
||||
@@ -0,0 +1,33 @@
|
||||
#pragma once
|
||||
|
||||
// One error type for the ADK. `code` is machine readable:
|
||||
// invalid_argument bad input, rejected before any work
|
||||
// budget a runner cap was hit (steps, tool calls, wall clock)
|
||||
// tool a tool failed
|
||||
// protocol a remote MCP / A2A peer answered something unusable
|
||||
// upstream a remote peer answered a non-2xx status
|
||||
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
namespace molo::google::adk {
|
||||
|
||||
class AdkError : public std::runtime_error {
|
||||
public:
|
||||
AdkError(std::string code, const std::string& message)
|
||||
: std::runtime_error("molo::google::adk: " + code + ": " + message),
|
||||
code_(std::move(code)),
|
||||
message_(message) {}
|
||||
const std::string& code() const noexcept { return code_; }
|
||||
const std::string& message() const noexcept { return message_; }
|
||||
static AdkError invalid(const std::string& m) { return {"invalid_argument", m}; }
|
||||
|
||||
private:
|
||||
std::string code_;
|
||||
std::string message_;
|
||||
};
|
||||
|
||||
// Agent and tool names: [A-Za-z_][A-Za-z0-9_]*, 1..64 chars.
|
||||
bool valid_identifier(const std::string& name);
|
||||
|
||||
} // namespace molo::google::adk
|
||||
@@ -0,0 +1,110 @@
|
||||
#include "google/adk/garden.h"
|
||||
|
||||
#include "google/adk/error.h"
|
||||
|
||||
namespace molo::google::adk {
|
||||
|
||||
using clients::body::Json;
|
||||
|
||||
namespace {
|
||||
|
||||
GardenTemplate make(const std::string& id, const std::string& title,
|
||||
const std::string& description, const std::string& instruction,
|
||||
std::vector<std::string> tools) {
|
||||
Json def = Json::object();
|
||||
def.set("agent_class", Json("LlmAgent"));
|
||||
def.set("name", Json(id));
|
||||
def.set("description", Json(description));
|
||||
def.set("model", Json("gemini-2.5-flash"));
|
||||
def.set("instruction", Json(instruction));
|
||||
Json t = Json::array();
|
||||
for (const auto& n : tools) {
|
||||
Json item = Json::object();
|
||||
item.set("name", Json(n));
|
||||
t.push(item);
|
||||
}
|
||||
def.set("tools", t);
|
||||
return {id, title, description, def, std::move(tools)};
|
||||
}
|
||||
|
||||
std::vector<GardenTemplate> build() {
|
||||
return {
|
||||
make("code_modernization", "Code modernization",
|
||||
"Reviews legacy code and proposes a staged migration.",
|
||||
"You modernize legacy code. Read the code the user supplies, list the "
|
||||
"outdated constructs, propose a staged migration with the smallest safe "
|
||||
"step first, and show the changed code. Never claim a test passed unless "
|
||||
"a tool ran it.",
|
||||
{"read_source", "run_tests"}),
|
||||
make("financial_analysis", "Financial analysis",
|
||||
"Analyses figures the user provides and explains the result.",
|
||||
"You are a financial analyst. Use only numbers the user or a tool "
|
||||
"provided. Show the formula for every ratio, state assumptions, and flag "
|
||||
"missing data instead of estimating it.",
|
||||
{"calculate"}),
|
||||
make("economic_research", "Economic research",
|
||||
"Summarizes economic questions with sources named.",
|
||||
"You research economic questions. Separate established data from "
|
||||
"interpretation, name the source of every figure, and say plainly when "
|
||||
"no source was supplied.",
|
||||
{"search_documents"}),
|
||||
make("invoice_processing", "Invoice processing",
|
||||
"Extracts structured fields from invoice text.",
|
||||
"You process invoices. Extract supplier, invoice number, date, currency, "
|
||||
"line items and totals as JSON. Check that line items sum to the total "
|
||||
"and report any mismatch. Never invent a field that is not in the text.",
|
||||
{"validate_invoice"}),
|
||||
};
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
const std::vector<GardenTemplate>& AgentGarden::templates() {
|
||||
static const std::vector<GardenTemplate> all = build();
|
||||
return all;
|
||||
}
|
||||
|
||||
const GardenTemplate* AgentGarden::find(const std::string& id) {
|
||||
for (const auto& t : templates())
|
||||
if (t.id == id) return &t;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::shared_ptr<BaseAgent> AgentGarden::instantiate(
|
||||
const std::string& id, const ToolRegistry& registry,
|
||||
std::vector<std::string>* missing_tools) {
|
||||
const GardenTemplate* t = find(id);
|
||||
if (!t) throw AdkError::invalid("unknown garden template: " + id);
|
||||
Json def = t->definition;
|
||||
Json kept = Json::array();
|
||||
for (const Json& item : def.find("tools")->as_array()) {
|
||||
const std::string& n = item.find("name")->as_string();
|
||||
if (registry.find(n)) {
|
||||
kept.push(item);
|
||||
} else if (missing_tools) {
|
||||
missing_tools->push_back(n);
|
||||
}
|
||||
}
|
||||
def.set("tools", kept);
|
||||
return AgentDefinition::from_json(def, registry);
|
||||
}
|
||||
|
||||
Json AgentGarden::catalog_json() {
|
||||
Json arr = Json::array();
|
||||
for (const auto& t : templates()) {
|
||||
Json o = Json::object();
|
||||
o.set("id", Json(t.id));
|
||||
o.set("title", Json(t.title));
|
||||
o.set("description", Json(t.description));
|
||||
Json tools = Json::array();
|
||||
for (const auto& n : t.suggested_tools) tools.push(Json(n));
|
||||
o.set("suggested_tools", tools);
|
||||
arr.push(o);
|
||||
}
|
||||
Json out = Json::object();
|
||||
out.set("templates", arr);
|
||||
out.set("source", Json("local"));
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace molo::google::adk
|
||||
@@ -0,0 +1,40 @@
|
||||
#pragma once
|
||||
|
||||
// Agent Garden catalog: a LOCAL template list for the four use cases named
|
||||
// in the platform announcement (code modernization, financial analysis,
|
||||
// economic research, invoice processing). Google's Agent Garden page
|
||||
// describes a sample library on GitHub; it publishes no API and no template
|
||||
// schema, so the instructions and tool names here are this module's own.
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "clients/body/json.h"
|
||||
#include "google/adk/agent.h"
|
||||
#include "google/adk/studio.h"
|
||||
|
||||
namespace molo::google::adk {
|
||||
|
||||
struct GardenTemplate {
|
||||
std::string id; // [a-z_]+
|
||||
std::string title;
|
||||
std::string description;
|
||||
clients::body::Json definition; // AgentDefinition document (tools by name)
|
||||
std::vector<std::string> suggested_tools; // Names a host should register
|
||||
};
|
||||
|
||||
class AgentGarden {
|
||||
public:
|
||||
static const std::vector<GardenTemplate>& templates();
|
||||
static const GardenTemplate* find(const std::string& id);
|
||||
// Builds the agent; tools named by the template that the registry lacks
|
||||
// are skipped (reported in missing_tools when non-null), so a template
|
||||
// works without host tools as a plain instruction-only agent.
|
||||
static std::shared_ptr<BaseAgent> instantiate(
|
||||
const std::string& id, const ToolRegistry& registry,
|
||||
std::vector<std::string>* missing_tools = nullptr);
|
||||
static clients::body::Json catalog_json();
|
||||
};
|
||||
|
||||
} // namespace molo::google::adk
|
||||
@@ -0,0 +1,197 @@
|
||||
#include "google/adk/mcp.h"
|
||||
|
||||
#include "google/adk/caps.h"
|
||||
#include "google/adk/error.h"
|
||||
|
||||
namespace molo::google::adk {
|
||||
|
||||
using clients::body::Json;
|
||||
|
||||
namespace {
|
||||
|
||||
std::string str(const Json& o, const char* key) {
|
||||
const Json* v = o.find(key);
|
||||
return v && v->is_string() ? v->as_string() : "";
|
||||
}
|
||||
|
||||
std::string sanitize(const std::string& name) {
|
||||
std::string out;
|
||||
for (char c : name) {
|
||||
bool ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
|
||||
(c >= '0' && c <= '9') || c == '_';
|
||||
out += ok ? c : '_';
|
||||
}
|
||||
if (!out.empty() && out[0] >= '0' && out[0] <= '9') out = "_" + out;
|
||||
if (out.size() > AdkCaps::kMaxNameChars) out.resize(AdkCaps::kMaxNameChars);
|
||||
return out;
|
||||
}
|
||||
|
||||
// Finds the JSON-RPC response with `id` in an SSE body.
|
||||
Json parse_sse(const std::string& body, int id) {
|
||||
std::size_t pos = 0;
|
||||
while (pos < body.size()) {
|
||||
std::size_t end = body.find('\n', pos);
|
||||
if (end == std::string::npos) end = body.size();
|
||||
std::string line = body.substr(pos, end - pos);
|
||||
pos = end + 1;
|
||||
if (!line.empty() && line.back() == '\r') line.pop_back();
|
||||
if (line.rfind("data:", 0) != 0) continue;
|
||||
std::string data = line.substr(5);
|
||||
if (!data.empty() && data[0] == ' ') data.erase(0, 1);
|
||||
try {
|
||||
Json doc = Json::parse(data);
|
||||
const Json* got = doc.find("id");
|
||||
if (got && got->is_number() && got->as_int() == id) return doc;
|
||||
} catch (const std::exception&) {
|
||||
continue; // Not JSON: keep scanning.
|
||||
}
|
||||
}
|
||||
throw AdkError("protocol", "no JSON-RPC response in the event stream");
|
||||
}
|
||||
|
||||
class McpTool : public Tool {
|
||||
public:
|
||||
McpTool(std::shared_ptr<McpClient> client, McpToolInfo info)
|
||||
: client_(std::move(client)),
|
||||
info_(std::move(info)),
|
||||
exposed_(sanitize(info_.name)) {}
|
||||
const std::string& name() const override { return exposed_; }
|
||||
FunctionDeclaration declaration() const override {
|
||||
FunctionDeclaration d;
|
||||
d.name = exposed_;
|
||||
d.description = info_.description.empty() ? info_.title : info_.description;
|
||||
d.parameters = info_.input_schema;
|
||||
return d;
|
||||
}
|
||||
Json call(const Json& args, ToolContext&) override {
|
||||
FunctionTool::validate(info_.input_schema, args);
|
||||
McpResult r = client_->call_tool(info_.name, args);
|
||||
if (r.is_error) throw AdkError("tool", r.text);
|
||||
Json out = Json::object();
|
||||
out.set("text", Json(r.text));
|
||||
if (!r.structured.is_null()) out.set("structured", r.structured);
|
||||
return out;
|
||||
}
|
||||
|
||||
private:
|
||||
std::shared_ptr<McpClient> client_;
|
||||
McpToolInfo info_;
|
||||
std::string exposed_;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
McpClient::McpClient(std::shared_ptr<RemoteHttp> http, std::string url)
|
||||
: http_(std::move(http)), url_(std::move(url)) {
|
||||
if (!http_) throw AdkError::invalid("McpClient needs an http helper");
|
||||
if (!RemoteHttp::valid_url(url_)) throw AdkError::invalid("invalid MCP url");
|
||||
}
|
||||
|
||||
std::map<std::string, std::string> McpClient::request_headers() const {
|
||||
std::map<std::string, std::string> h{
|
||||
{"Accept", "application/json, text/event-stream"}};
|
||||
if (initialized_) h["MCP-Protocol-Version"] = kProtocolVersion;
|
||||
if (!session_id_.empty()) h["Mcp-Session-Id"] = session_id_;
|
||||
return h;
|
||||
}
|
||||
|
||||
Json McpClient::rpc(const std::string& method, Json params) {
|
||||
int id = next_id_++;
|
||||
Json req = Json::object();
|
||||
req.set("jsonrpc", Json("2.0"));
|
||||
req.set("id", Json(id));
|
||||
req.set("method", Json(method));
|
||||
req.set("params", std::move(params));
|
||||
RemoteReply reply = http_->post_json(url_, req, request_headers());
|
||||
if (auto sid = reply.headers.get("Mcp-Session-Id")) session_id_ = *sid;
|
||||
Json doc;
|
||||
try {
|
||||
std::string ct = reply.headers.get_or("Content-Type", "");
|
||||
doc = ct.find("text/event-stream") != std::string::npos
|
||||
? parse_sse(reply.body, id)
|
||||
: Json::parse(reply.body);
|
||||
} catch (const AdkError&) {
|
||||
throw;
|
||||
} catch (const std::exception& e) {
|
||||
throw AdkError("protocol", std::string("unreadable MCP reply: ") + e.what());
|
||||
}
|
||||
if (!doc.is_object()) throw AdkError("protocol", "MCP reply is not an object");
|
||||
if (const Json* err = doc.find("error"); err && err->is_object())
|
||||
throw AdkError("protocol", "MCP error " +
|
||||
(err->has("code") ? std::to_string(err->find("code")->as_int())
|
||||
: std::string("?")) +
|
||||
": " + str(*err, "message"));
|
||||
const Json* result = doc.find("result");
|
||||
if (!result || !result->is_object()) throw AdkError("protocol", "MCP reply has no result");
|
||||
return *result;
|
||||
}
|
||||
|
||||
void McpClient::notify(const std::string& method) {
|
||||
Json req = Json::object();
|
||||
req.set("jsonrpc", Json("2.0"));
|
||||
req.set("method", Json(method));
|
||||
http_->post_json(url_, req, request_headers());
|
||||
}
|
||||
|
||||
void McpClient::initialize() {
|
||||
Json client = Json::object();
|
||||
client.set("name", Json("moloapp-adk"));
|
||||
client.set("version", Json("1"));
|
||||
Json params = Json::object();
|
||||
params.set("protocolVersion", Json(kProtocolVersion));
|
||||
params.set("capabilities", Json::object());
|
||||
params.set("clientInfo", client);
|
||||
rpc("initialize", params);
|
||||
initialized_ = true;
|
||||
notify("notifications/initialized");
|
||||
}
|
||||
|
||||
std::vector<McpToolInfo> McpClient::list_tools() {
|
||||
std::vector<McpToolInfo> out;
|
||||
std::string cursor;
|
||||
for (int page = 0; page < AdkCaps::kMaxMcpPages; ++page) {
|
||||
Json params = Json::object();
|
||||
if (!cursor.empty()) params.set("cursor", Json(cursor));
|
||||
Json result = rpc("tools/list", params);
|
||||
const Json* tools = result.find("tools");
|
||||
if (!tools || !tools->is_array()) throw AdkError("protocol", "tools/list has no tools array");
|
||||
for (const Json& t : tools->as_array()) {
|
||||
if (!t.is_object() || str(t, "name").empty()) continue;
|
||||
if (out.size() >= AdkCaps::kMaxMcpTools) return out;
|
||||
McpToolInfo info{str(t, "name"), str(t, "title"), str(t, "description"), Json()};
|
||||
if (const Json* s = t.find("inputSchema")) info.input_schema = *s;
|
||||
out.push_back(std::move(info));
|
||||
}
|
||||
cursor = str(result, "nextCursor");
|
||||
if (cursor.empty()) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
McpResult McpClient::call_tool(const std::string& name, const Json& args) {
|
||||
if (name.empty()) throw AdkError::invalid("empty tool name");
|
||||
Json params = Json::object();
|
||||
params.set("name", Json(name));
|
||||
params.set("arguments", args.is_object() ? args : Json::object());
|
||||
Json result = rpc("tools/call", params);
|
||||
McpResult r;
|
||||
if (const Json* c = result.find("content"); c && c->is_array())
|
||||
for (const Json& item : c->as_array())
|
||||
if (item.is_object() && str(item, "type") == "text") {
|
||||
if (!r.text.empty()) r.text += "\n";
|
||||
r.text += str(item, "text");
|
||||
}
|
||||
if (const Json* s = result.find("structuredContent")) r.structured = *s;
|
||||
if (const Json* e = result.find("isError"); e && e->is_bool()) r.is_error = e->as_bool();
|
||||
return r;
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<Tool>> McpClient::tools() {
|
||||
std::vector<std::shared_ptr<Tool>> out;
|
||||
auto self = shared_from_this();
|
||||
for (McpToolInfo& info : list_tools())
|
||||
out.push_back(std::make_shared<McpTool>(self, std::move(info)));
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace molo::google::adk
|
||||
@@ -0,0 +1,62 @@
|
||||
#pragma once
|
||||
|
||||
// MCP (Model Context Protocol) client over streamable HTTP: JSON-RPC 2.0
|
||||
// POSTs to one endpoint URL, replies as application/json or as a
|
||||
// text/event-stream carrying the JSON-RPC response. Remote tools become ADK
|
||||
// tools through McpClient::tools().
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "clients/body/json.h"
|
||||
#include "google/adk/remote_http.h"
|
||||
#include "google/adk/tool.h"
|
||||
|
||||
namespace molo::google::adk {
|
||||
|
||||
struct McpToolInfo {
|
||||
std::string name;
|
||||
std::string title;
|
||||
std::string description;
|
||||
clients::body::Json input_schema; // JSON Schema, passed to Gemini as is
|
||||
};
|
||||
|
||||
struct McpResult {
|
||||
std::string text; // Text content items joined by newlines
|
||||
clients::body::Json structured; // structuredContent, null when absent
|
||||
bool is_error = false;
|
||||
};
|
||||
|
||||
class McpClient : public std::enable_shared_from_this<McpClient> {
|
||||
public:
|
||||
static constexpr const char* kProtocolVersion = "2025-06-18";
|
||||
|
||||
McpClient(std::shared_ptr<RemoteHttp> http, std::string url);
|
||||
|
||||
// initialize + notifications/initialized. Keeps Mcp-Session-Id if sent.
|
||||
void initialize();
|
||||
// tools/list, following nextCursor for at most kMaxMcpPages pages and
|
||||
// kMaxMcpTools tools.
|
||||
std::vector<McpToolInfo> list_tools();
|
||||
McpResult call_tool(const std::string& name, const clients::body::Json& args);
|
||||
// list_tools() wrapped as ADK tools. Exposed names are sanitized to
|
||||
// [A-Za-z0-9_]; a tool whose result has isError becomes a tool error.
|
||||
std::vector<std::shared_ptr<Tool>> tools();
|
||||
|
||||
const std::string& url() const { return url_; }
|
||||
const std::string& session_id() const { return session_id_; }
|
||||
|
||||
private:
|
||||
clients::body::Json rpc(const std::string& method, clients::body::Json params);
|
||||
void notify(const std::string& method);
|
||||
std::map<std::string, std::string> request_headers() const;
|
||||
|
||||
std::shared_ptr<RemoteHttp> http_;
|
||||
std::string url_;
|
||||
std::string session_id_;
|
||||
bool initialized_ = false;
|
||||
int next_id_ = 1;
|
||||
};
|
||||
|
||||
} // namespace molo::google::adk
|
||||
@@ -0,0 +1,55 @@
|
||||
#include "google/adk/remote_http.h"
|
||||
|
||||
#include "google/adk/caps.h"
|
||||
#include "google/adk/error.h"
|
||||
|
||||
namespace molo::google::adk {
|
||||
|
||||
RemoteHttp::RemoteHttp(std::shared_ptr<clients::Client> http,
|
||||
std::map<std::string, std::string> headers)
|
||||
: http_(std::move(http)), headers_(std::move(headers)) {
|
||||
if (!http_) throw AdkError::invalid("RemoteHttp needs a client");
|
||||
}
|
||||
|
||||
bool RemoteHttp::valid_url(const std::string& url) {
|
||||
bool scheme = url.rfind("http://", 0) == 0 || url.rfind("https://", 0) == 0;
|
||||
if (!scheme || url.size() > 2048) return false;
|
||||
for (char c : url)
|
||||
if (c <= ' ' || c == 0x7f) return false;
|
||||
return url.size() > url.find("//") + 2; // A host must follow the scheme.
|
||||
}
|
||||
|
||||
RemoteReply RemoteHttp::finish(const std::string& url, clients::ClientRequest req) {
|
||||
for (const auto& [k, v] : headers_) req.header(k, v);
|
||||
clients::ClientResponse res;
|
||||
try {
|
||||
res = http_->send_blocking(std::move(req));
|
||||
} catch (const std::exception& e) {
|
||||
throw AdkError("upstream", "request failed: " + std::string(e.what()));
|
||||
}
|
||||
if (!res.is_success())
|
||||
throw AdkError("upstream", "HTTP " + std::to_string(res.status()) + " from " + url);
|
||||
if (res.body().size() > AdkCaps::kMaxHttpBodyBytes)
|
||||
throw AdkError("protocol", "response over the body cap");
|
||||
return {res.status(), res.headers(), res.body()};
|
||||
}
|
||||
|
||||
RemoteReply RemoteHttp::post_json(const std::string& url,
|
||||
const clients::body::Json& body,
|
||||
const std::map<std::string, std::string>& extra) {
|
||||
if (!valid_url(url)) throw AdkError::invalid("invalid url");
|
||||
clients::ClientRequest req = clients::ClientRequest::post(url);
|
||||
req.json(body);
|
||||
for (const auto& [k, v] : extra) req.header(k, v);
|
||||
return finish(url, std::move(req));
|
||||
}
|
||||
|
||||
RemoteReply RemoteHttp::get(const std::string& url,
|
||||
const std::map<std::string, std::string>& extra) {
|
||||
if (!valid_url(url)) throw AdkError::invalid("invalid url");
|
||||
clients::ClientRequest req = clients::ClientRequest::get(url);
|
||||
for (const auto& [k, v] : extra) req.header(k, v);
|
||||
return finish(url, std::move(req));
|
||||
}
|
||||
|
||||
} // namespace molo::google::adk
|
||||
@@ -0,0 +1,45 @@
|
||||
#pragma once
|
||||
|
||||
// Thin bounded HTTP helper for the MCP and A2A clients: absolute http(s)
|
||||
// URLs only, response body capped, non-2xx and transport failures mapped to
|
||||
// AdkError ("upstream"). Runs over any clients::Client (MockTransport in
|
||||
// tests).
|
||||
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "clients/body/json.h"
|
||||
#include "clients/client.h"
|
||||
|
||||
namespace molo::google::adk {
|
||||
|
||||
struct RemoteReply {
|
||||
int status = 0;
|
||||
clients::HeaderMap headers;
|
||||
std::string body;
|
||||
};
|
||||
|
||||
class RemoteHttp {
|
||||
public:
|
||||
// headers are sent on every request (e.g. Authorization). They are never
|
||||
// echoed into errors.
|
||||
explicit RemoteHttp(std::shared_ptr<clients::Client> http,
|
||||
std::map<std::string, std::string> headers = {});
|
||||
|
||||
RemoteReply post_json(const std::string& url, const clients::body::Json& body,
|
||||
const std::map<std::string, std::string>& extra = {});
|
||||
RemoteReply get(const std::string& url,
|
||||
const std::map<std::string, std::string>& extra = {});
|
||||
|
||||
// True for an absolute http:// or https:// URL without whitespace.
|
||||
static bool valid_url(const std::string& url);
|
||||
|
||||
private:
|
||||
RemoteReply finish(const std::string& url, clients::ClientRequest request);
|
||||
|
||||
std::shared_ptr<clients::Client> http_;
|
||||
std::map<std::string, std::string> headers_;
|
||||
};
|
||||
|
||||
} // namespace molo::google::adk
|
||||
@@ -0,0 +1,149 @@
|
||||
#include "google/adk/runner.h"
|
||||
|
||||
#include "google/adk/caps.h"
|
||||
#include "google/adk/error.h"
|
||||
#include "google/resource.h"
|
||||
|
||||
namespace molo::google::adk {
|
||||
|
||||
using clients::body::Json;
|
||||
|
||||
void RunLimits::validate() const {
|
||||
auto check = [](int v, int cap, const char* what) {
|
||||
if (v < 1 || v > cap)
|
||||
throw AdkError::invalid(std::string(what) + " outside 1.." + std::to_string(cap));
|
||||
};
|
||||
check(max_steps, AdkCaps::kMaxSteps, "max_steps");
|
||||
check(max_tool_calls, AdkCaps::kMaxToolCalls, "max_tool_calls");
|
||||
check(wall_clock_ms, AdkCaps::kMaxWallClockMs, "wall_clock_ms");
|
||||
}
|
||||
|
||||
Json RunResult::to_json() const {
|
||||
Json o = Json::object();
|
||||
o.set("text", Json(text));
|
||||
o.set("author", Json(author));
|
||||
o.set("stop_reason", Json(stop_reason));
|
||||
o.set("steps", Json(steps));
|
||||
o.set("tool_calls", Json(tool_calls));
|
||||
Json ev = Json::array();
|
||||
for (const Event& e : events) ev.push(e.to_json());
|
||||
o.set("events", ev);
|
||||
o.set("state", state);
|
||||
return o;
|
||||
}
|
||||
|
||||
Runner::Runner(std::shared_ptr<LanguageModel> model,
|
||||
std::shared_ptr<SessionService> sessions,
|
||||
std::shared_ptr<MemoryService> memory, RunLimits limits)
|
||||
: model_(std::move(model)),
|
||||
sessions_(std::move(sessions)),
|
||||
memory_(std::move(memory)),
|
||||
limits_(limits) {
|
||||
if (!model_) throw AdkError::invalid("runner needs a model");
|
||||
if (!sessions_) throw AdkError::invalid("runner needs a session service");
|
||||
limits_.validate();
|
||||
}
|
||||
|
||||
RunResult Runner::run(const std::shared_ptr<BaseAgent>& root,
|
||||
const std::string& session_id,
|
||||
const std::string& user_text, const std::string& user_id) {
|
||||
if (!root) throw AdkError::invalid("no agent");
|
||||
if (user_text.empty()) throw AdkError::invalid("empty input");
|
||||
if (user_text.size() > AdkCaps::kMaxInputChars)
|
||||
throw AdkError::invalid("input over " + std::to_string(AdkCaps::kMaxInputChars) +
|
||||
" characters");
|
||||
Session session;
|
||||
if (auto existing = sessions_->get(session_id)) {
|
||||
session = *existing;
|
||||
} else {
|
||||
session = sessions_->create(session_id, user_id);
|
||||
}
|
||||
|
||||
Budget budget(limits_.max_steps, limits_.max_tool_calls, limits_.wall_clock_ms);
|
||||
RunContext ctx{*model_, budget};
|
||||
ctx.state = session.state;
|
||||
// History: user turns and final answers, newest kMaxHistoryContents.
|
||||
for (const Event& e : session.events) {
|
||||
if (e.author == "user") {
|
||||
ctx.history.push_back(e.content);
|
||||
} else if (e.final) {
|
||||
Content c = e.content;
|
||||
c.role = "model";
|
||||
ctx.history.push_back(std::move(c));
|
||||
}
|
||||
}
|
||||
if (ctx.history.size() > AdkCaps::kMaxHistoryContents)
|
||||
ctx.history.erase(ctx.history.begin(),
|
||||
ctx.history.end() - AdkCaps::kMaxHistoryContents);
|
||||
|
||||
Content input = Content::user(user_text);
|
||||
Event user_event{"user", input, false};
|
||||
|
||||
RunResult result;
|
||||
try {
|
||||
Content out = root->run(ctx, input);
|
||||
result.text = out.text();
|
||||
// The author is the agent that wrote the last final event.
|
||||
for (auto it = ctx.events.rbegin(); it != ctx.events.rend(); ++it)
|
||||
if (it->final) {
|
||||
result.author = it->author;
|
||||
break;
|
||||
}
|
||||
} catch (const AdkError& e) {
|
||||
if (e.code() != "budget") throw;
|
||||
result.stop_reason = e.message();
|
||||
}
|
||||
result.steps = budget.steps() > limits_.max_steps ? limits_.max_steps : budget.steps();
|
||||
result.tool_calls = budget.tool_calls() > limits_.max_tool_calls
|
||||
? limits_.max_tool_calls
|
||||
: budget.tool_calls();
|
||||
result.events.push_back(user_event);
|
||||
for (Event& e : ctx.events) result.events.push_back(std::move(e));
|
||||
|
||||
session.state = ctx.state;
|
||||
for (const Event& e : result.events) session.events.push_back(e);
|
||||
sessions_->save(session);
|
||||
result.state = ctx.state;
|
||||
return result;
|
||||
}
|
||||
|
||||
void Runner::remember(const std::string& session_id) {
|
||||
if (!memory_) throw AdkError::invalid("no memory service configured");
|
||||
auto s = sessions_->get(session_id);
|
||||
if (!s) throw AdkError::invalid("unknown session: " + session_id);
|
||||
memory_->add_session(*s);
|
||||
}
|
||||
|
||||
std::shared_ptr<Tool> make_load_memory_tool(std::shared_ptr<MemoryService> memory,
|
||||
std::string user_id) {
|
||||
Json query = Json::object();
|
||||
query.set("type", Json("string"));
|
||||
Json props = Json::object();
|
||||
props.set("query", query);
|
||||
Json req = Json::array();
|
||||
req.push(Json("query"));
|
||||
Json schema = Json::object();
|
||||
schema.set("type", Json("object"));
|
||||
schema.set("properties", props);
|
||||
schema.set("required", req);
|
||||
return std::make_shared<FunctionTool>(
|
||||
"load_memory", "Search long-term memory for past conversation snippets.",
|
||||
schema,
|
||||
[memory = std::move(memory), user_id = std::move(user_id)](
|
||||
const Json& args, ToolContext&) {
|
||||
Json out = Json::object();
|
||||
Json items = Json::array();
|
||||
for (const MemoryEntry& m :
|
||||
memory->search(user_id, args.find("query")->as_string(),
|
||||
AdkCaps::kMaxMemoryResults)) {
|
||||
Json item = Json::object();
|
||||
item.set("author", Json(m.author));
|
||||
item.set("text", Json(m.text));
|
||||
items.push(item);
|
||||
}
|
||||
out.set("memories", items);
|
||||
return out;
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace molo::google::adk
|
||||
@@ -0,0 +1,67 @@
|
||||
#pragma once
|
||||
|
||||
// Runner: executes one user turn against an agent tree over a
|
||||
// LanguageModel (function calling loop lives in Agent::run). Hard caps per
|
||||
// turn: model calls, tool calls, wall clock (AdkCaps). A cap hit does not
|
||||
// throw: the result carries stop_reason and whatever events were produced.
|
||||
// Model errors (GoogleError) propagate and the session is left unchanged.
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "google/adk/agent.h"
|
||||
#include "google/adk/caps.h"
|
||||
#include "google/adk/session.h"
|
||||
|
||||
namespace molo::google::adk {
|
||||
|
||||
struct RunLimits {
|
||||
int max_steps = AdkCaps::kMaxSteps;
|
||||
int max_tool_calls = AdkCaps::kMaxToolCalls;
|
||||
int wall_clock_ms = AdkCaps::kMaxWallClockMs;
|
||||
// Throws AdkError (invalid_argument) when any value is below 1 or above its cap.
|
||||
void validate() const;
|
||||
};
|
||||
|
||||
struct RunResult {
|
||||
std::string text;
|
||||
std::string author; // Agent that produced the final answer.
|
||||
// completed | max_steps | max_tool_calls | timeout | max_transfers |
|
||||
// max_calls_per_step
|
||||
std::string stop_reason = "completed";
|
||||
int steps = 0;
|
||||
int tool_calls = 0;
|
||||
std::vector<Event> events; // This turn only, user event first.
|
||||
clients::body::Json state; // Session state after the turn.
|
||||
clients::body::Json to_json() const;
|
||||
};
|
||||
|
||||
class Runner {
|
||||
public:
|
||||
Runner(std::shared_ptr<LanguageModel> model,
|
||||
std::shared_ptr<SessionService> sessions,
|
||||
std::shared_ptr<MemoryService> memory = nullptr, RunLimits limits = {});
|
||||
|
||||
// Creates the session on first use. Validates ids and text (1..kMaxInputChars).
|
||||
RunResult run(const std::shared_ptr<BaseAgent>& root,
|
||||
const std::string& session_id, const std::string& user_text,
|
||||
const std::string& user_id = "user");
|
||||
|
||||
// Copies the session into the memory service (explicit, never implicit).
|
||||
void remember(const std::string& session_id);
|
||||
|
||||
const RunLimits& limits() const { return limits_; }
|
||||
|
||||
private:
|
||||
std::shared_ptr<LanguageModel> model_;
|
||||
std::shared_ptr<SessionService> sessions_;
|
||||
std::shared_ptr<MemoryService> memory_;
|
||||
RunLimits limits_;
|
||||
};
|
||||
|
||||
// Tool that searches the memory service for one user ("load_memory").
|
||||
std::shared_ptr<Tool> make_load_memory_tool(std::shared_ptr<MemoryService> memory,
|
||||
std::string user_id);
|
||||
|
||||
} // namespace molo::google::adk
|
||||
@@ -0,0 +1,130 @@
|
||||
#include "google/adk/session.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <set>
|
||||
|
||||
#include "google/adk/caps.h"
|
||||
#include "google/adk/error.h"
|
||||
#include "google/resource.h"
|
||||
|
||||
namespace molo::google::adk {
|
||||
|
||||
using clients::body::Json;
|
||||
|
||||
Json Event::to_json() const {
|
||||
Json o = Json::object();
|
||||
o.set("author", Json(author));
|
||||
o.set("content", content.to_json());
|
||||
o.set("final", Json(final));
|
||||
return o;
|
||||
}
|
||||
|
||||
Session InMemorySessionService::create(const std::string& id,
|
||||
const std::string& user_id) {
|
||||
if (!valid_segment(id)) throw AdkError::invalid("invalid session id");
|
||||
if (!valid_segment(user_id)) throw AdkError::invalid("invalid user id");
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (sessions_.count(id)) throw AdkError::invalid("session exists: " + id);
|
||||
while (sessions_.size() >= AdkCaps::kMaxSessions && !order_.empty()) {
|
||||
sessions_.erase(order_.front());
|
||||
order_.erase(order_.begin());
|
||||
}
|
||||
Session s;
|
||||
s.id = id;
|
||||
s.user_id = user_id;
|
||||
sessions_[id] = s;
|
||||
order_.push_back(id);
|
||||
return s;
|
||||
}
|
||||
|
||||
std::optional<Session> InMemorySessionService::get(const std::string& id) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
auto it = sessions_.find(id);
|
||||
if (it == sessions_.end()) return std::nullopt;
|
||||
return it->second;
|
||||
}
|
||||
|
||||
void InMemorySessionService::save(const Session& session) {
|
||||
if (!session.state.is_object()) throw AdkError::invalid("state must be an object");
|
||||
if (session.state.as_object().size() > AdkCaps::kMaxStateKeys)
|
||||
throw AdkError::invalid("session state over key cap");
|
||||
for (const auto& [k, v] : session.state.as_object())
|
||||
if (v.dump().size() > AdkCaps::kMaxStateValueBytes)
|
||||
throw AdkError::invalid("session state value over byte cap: " + k);
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
auto it = sessions_.find(session.id);
|
||||
if (it == sessions_.end()) throw AdkError::invalid("unknown session: " + session.id);
|
||||
it->second = session;
|
||||
auto& ev = it->second.events;
|
||||
if (ev.size() > AdkCaps::kMaxEventsPerSession)
|
||||
ev.erase(ev.begin(), ev.begin() + (ev.size() - AdkCaps::kMaxEventsPerSession));
|
||||
}
|
||||
|
||||
bool InMemorySessionService::remove(const std::string& id) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
order_.erase(std::remove(order_.begin(), order_.end(), id), order_.end());
|
||||
return sessions_.erase(id) > 0;
|
||||
}
|
||||
|
||||
std::size_t InMemorySessionService::size() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return sessions_.size();
|
||||
}
|
||||
|
||||
namespace {
|
||||
std::set<std::string> words(const std::string& text) {
|
||||
std::set<std::string> out;
|
||||
std::string cur;
|
||||
for (char ch : text) {
|
||||
if (std::isalnum(static_cast<unsigned char>(ch))) {
|
||||
cur += static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));
|
||||
} else {
|
||||
if (cur.size() > 2) out.insert(cur);
|
||||
cur.clear();
|
||||
}
|
||||
}
|
||||
if (cur.size() > 2) out.insert(cur);
|
||||
return out;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void InMemoryMemoryService::add_session(const Session& session) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
for (const Event& e : session.events) {
|
||||
if (!(e.author == "user" || e.final)) continue;
|
||||
std::string text = e.content.text();
|
||||
if (text.empty()) continue;
|
||||
entries_.push_back({session.user_id, session.id, e.author, text});
|
||||
}
|
||||
if (entries_.size() > AdkCaps::kMaxMemoryEntries)
|
||||
entries_.erase(entries_.begin(),
|
||||
entries_.begin() + (entries_.size() - AdkCaps::kMaxMemoryEntries));
|
||||
}
|
||||
|
||||
std::vector<MemoryEntry> InMemoryMemoryService::search(
|
||||
const std::string& user_id, const std::string& query, std::size_t limit) {
|
||||
limit = std::min(limit, AdkCaps::kMaxMemoryResults);
|
||||
std::set<std::string> q = words(query);
|
||||
std::vector<std::pair<std::size_t, const MemoryEntry*>> scored;
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
for (const MemoryEntry& e : entries_) {
|
||||
if (e.user_id != user_id) continue;
|
||||
std::size_t score = 0;
|
||||
for (const std::string& w : words(e.text)) score += q.count(w);
|
||||
if (score > 0) scored.push_back({score, &e});
|
||||
}
|
||||
std::stable_sort(scored.begin(), scored.end(),
|
||||
[](const auto& a, const auto& b) { return a.first > b.first; });
|
||||
std::vector<MemoryEntry> out;
|
||||
for (std::size_t i = 0; i < scored.size() && i < limit; ++i)
|
||||
out.push_back(*scored[i].second);
|
||||
return out;
|
||||
}
|
||||
|
||||
std::size_t InMemoryMemoryService::size() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return entries_.size();
|
||||
}
|
||||
|
||||
} // namespace molo::google::adk
|
||||
@@ -0,0 +1,91 @@
|
||||
#pragma once
|
||||
|
||||
// Session and memory seams of the ADK, with bounded in-memory defaults.
|
||||
// These are local interfaces: the ADK does not depend on the sessions
|
||||
// module (Agent Sessions / Memory Bank); an adapter over that module can
|
||||
// implement the same interfaces later.
|
||||
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "clients/body/json.h"
|
||||
#include "google/gemini_types.h"
|
||||
|
||||
namespace molo::google::adk {
|
||||
|
||||
struct Event {
|
||||
std::string author; // "user" or an agent name
|
||||
Content content;
|
||||
bool final = false; // A final answer of an agent (kept in history)
|
||||
clients::body::Json to_json() const;
|
||||
};
|
||||
|
||||
struct Session {
|
||||
std::string id;
|
||||
std::string user_id;
|
||||
clients::body::Json state = clients::body::Json::object();
|
||||
std::vector<Event> events;
|
||||
};
|
||||
|
||||
class SessionService {
|
||||
public:
|
||||
virtual ~SessionService() = default;
|
||||
virtual Session create(const std::string& id, const std::string& user_id) = 0;
|
||||
virtual std::optional<Session> get(const std::string& id) = 0;
|
||||
virtual void save(const Session& session) = 0;
|
||||
virtual bool remove(const std::string& id) = 0;
|
||||
};
|
||||
|
||||
// Bounded: kMaxSessions (oldest created evicted), kMaxEventsPerSession
|
||||
// (oldest dropped), kMaxStateKeys and kMaxStateValueBytes on save.
|
||||
class InMemorySessionService : public SessionService {
|
||||
public:
|
||||
Session create(const std::string& id, const std::string& user_id) override;
|
||||
std::optional<Session> get(const std::string& id) override;
|
||||
void save(const Session& session) override;
|
||||
bool remove(const std::string& id) override;
|
||||
std::size_t size() const;
|
||||
|
||||
private:
|
||||
mutable std::mutex mutex_;
|
||||
std::map<std::string, Session> sessions_;
|
||||
std::vector<std::string> order_; // creation order for eviction
|
||||
};
|
||||
|
||||
struct MemoryEntry {
|
||||
std::string user_id;
|
||||
std::string session_id;
|
||||
std::string author;
|
||||
std::string text;
|
||||
};
|
||||
|
||||
class MemoryService {
|
||||
public:
|
||||
virtual ~MemoryService() = default;
|
||||
// Stores the text of the session's user and final agent events.
|
||||
virtual void add_session(const Session& session) = 0;
|
||||
virtual std::vector<MemoryEntry> search(const std::string& user_id,
|
||||
const std::string& query,
|
||||
std::size_t limit) = 0;
|
||||
};
|
||||
|
||||
// Keyword overlap ranking, no embeddings. Bounded by kMaxMemoryEntries
|
||||
// (oldest dropped) and kMaxMemoryResults per search.
|
||||
class InMemoryMemoryService : public MemoryService {
|
||||
public:
|
||||
void add_session(const Session& session) override;
|
||||
std::vector<MemoryEntry> search(const std::string& user_id,
|
||||
const std::string& query,
|
||||
std::size_t limit) override;
|
||||
std::size_t size() const;
|
||||
|
||||
private:
|
||||
mutable std::mutex mutex_;
|
||||
std::vector<MemoryEntry> entries_;
|
||||
};
|
||||
|
||||
} // namespace molo::google::adk
|
||||
@@ -0,0 +1,147 @@
|
||||
#include "google/adk/studio.h"
|
||||
|
||||
#include "google/adk/caps.h"
|
||||
#include "google/adk/error.h"
|
||||
|
||||
namespace molo::google::adk {
|
||||
|
||||
using clients::body::Json;
|
||||
|
||||
ToolRegistry::ToolRegistry() { add(make_exit_loop_tool()); }
|
||||
|
||||
void ToolRegistry::add(std::shared_ptr<Tool> tool) {
|
||||
if (!tool) throw AdkError::invalid("null tool");
|
||||
tools_[tool->name()] = std::move(tool);
|
||||
}
|
||||
|
||||
std::shared_ptr<Tool> ToolRegistry::find(const std::string& name) const {
|
||||
auto it = tools_.find(name);
|
||||
return it == tools_.end() ? nullptr : it->second;
|
||||
}
|
||||
|
||||
std::vector<std::string> ToolRegistry::names() const {
|
||||
std::vector<std::string> out;
|
||||
for (const auto& [k, v] : tools_) out.push_back(k);
|
||||
return out;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
std::string str(const Json& o, const char* key) {
|
||||
const Json* v = o.find(key);
|
||||
if (!v) return "";
|
||||
if (!v->is_string()) throw AdkError::invalid(std::string(key) + " must be a string");
|
||||
return v->as_string();
|
||||
}
|
||||
|
||||
std::shared_ptr<BaseAgent> build(const Json& doc, const ToolRegistry& registry,
|
||||
int depth, int& count) {
|
||||
if (depth > AdkCaps::kMaxAgentDepth) throw AdkError::invalid("definition deeper than the depth cap");
|
||||
if (++count > 64) throw AdkError::invalid("definition has over 64 agents");
|
||||
if (!doc.is_object()) throw AdkError::invalid("agent definition must be an object");
|
||||
std::string cls = str(doc, "agent_class");
|
||||
if (cls.empty()) cls = "LlmAgent";
|
||||
std::string name = str(doc, "name");
|
||||
std::string description = str(doc, "description");
|
||||
|
||||
std::shared_ptr<BaseAgent> agent;
|
||||
if (cls == "LlmAgent" || cls == "Agent") {
|
||||
Agent::Config cfg;
|
||||
cfg.name = name;
|
||||
cfg.description = description;
|
||||
cfg.model = str(doc, "model");
|
||||
cfg.instruction = str(doc, "instruction");
|
||||
cfg.output_key = str(doc, "output_key");
|
||||
if (const Json* tools = doc.find("tools")) {
|
||||
if (!tools->is_array()) throw AdkError::invalid("tools must be an array");
|
||||
for (const Json& t : tools->as_array()) {
|
||||
std::string tn = t.is_string() ? t.as_string() : str(t, "name");
|
||||
auto tool = registry.find(tn);
|
||||
if (!tool) throw AdkError::invalid("unknown tool: " + tn);
|
||||
cfg.tools.push_back(tool);
|
||||
}
|
||||
}
|
||||
agent = std::make_shared<Agent>(std::move(cfg));
|
||||
} else if (cls == "SequentialAgent") {
|
||||
agent = std::make_shared<SequentialAgent>(name, description);
|
||||
} else if (cls == "ParallelAgent") {
|
||||
agent = std::make_shared<ParallelAgent>(name, description);
|
||||
} else if (cls == "LoopAgent") {
|
||||
int iters = 3;
|
||||
if (const Json* m = doc.find("max_iterations")) {
|
||||
if (!m->is_number()) throw AdkError::invalid("max_iterations must be a number");
|
||||
iters = static_cast<int>(m->as_int());
|
||||
}
|
||||
agent = std::make_shared<LoopAgent>(name, description, iters);
|
||||
} else {
|
||||
throw AdkError::invalid("unsupported agent_class: " + cls);
|
||||
}
|
||||
|
||||
if (const Json* subs = doc.find("sub_agents")) {
|
||||
if (!subs->is_array()) throw AdkError::invalid("sub_agents must be an array");
|
||||
for (const Json& s : subs->as_array()) {
|
||||
if (s.is_object() && s.has("config_path") && !s.has("name"))
|
||||
throw AdkError::invalid("config_path references are not supported, inline the sub-agent");
|
||||
agent->add_sub_agent(build(s, registry, depth + 1, count));
|
||||
}
|
||||
}
|
||||
return agent;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Json AgentDefinition::to_json(const BaseAgent& agent) {
|
||||
Json o = Json::object();
|
||||
o.set("agent_class", Json(agent.kind()));
|
||||
o.set("name", Json(agent.name()));
|
||||
if (!agent.description().empty()) o.set("description", Json(agent.description()));
|
||||
if (const auto* a = dynamic_cast<const Agent*>(&agent)) {
|
||||
const Agent::Config& c = a->config();
|
||||
if (!c.model.empty()) o.set("model", Json(c.model));
|
||||
if (!c.instruction.empty()) o.set("instruction", Json(c.instruction));
|
||||
if (!c.output_key.empty()) o.set("output_key", Json(c.output_key));
|
||||
if (!c.tools.empty()) {
|
||||
Json tools = Json::array();
|
||||
for (const auto& t : c.tools) {
|
||||
Json item = Json::object();
|
||||
item.set("name", Json(t->name()));
|
||||
tools.push(item);
|
||||
}
|
||||
o.set("tools", tools);
|
||||
}
|
||||
} else if (const auto* l = dynamic_cast<const LoopAgent*>(&agent)) {
|
||||
o.set("max_iterations", Json(l->max_iterations()));
|
||||
}
|
||||
if (!agent.sub_agents().empty()) {
|
||||
Json subs = Json::array();
|
||||
for (const auto& s : agent.sub_agents()) subs.push(to_json(*s));
|
||||
o.set("sub_agents", subs);
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
std::string AgentDefinition::to_yaml(const BaseAgent& agent) {
|
||||
return clients::body::yaml_dump(to_json(agent));
|
||||
}
|
||||
|
||||
std::shared_ptr<BaseAgent> AgentDefinition::from_json(const Json& doc,
|
||||
const ToolRegistry& registry) {
|
||||
int count = 0;
|
||||
return build(doc, registry, 1, count);
|
||||
}
|
||||
|
||||
std::shared_ptr<BaseAgent> AgentDefinition::from_text(const std::string& text,
|
||||
const ToolRegistry& registry) {
|
||||
if (text.size() > AdkCaps::kMaxDefinitionBytes)
|
||||
throw AdkError::invalid("definition over " + std::to_string(AdkCaps::kMaxDefinitionBytes) +
|
||||
" bytes");
|
||||
Json doc;
|
||||
try {
|
||||
doc = Json::parse(text);
|
||||
} catch (const std::exception& e) {
|
||||
throw AdkError::invalid(std::string("definition is not valid JSON: ") + e.what());
|
||||
}
|
||||
return from_json(doc, registry);
|
||||
}
|
||||
|
||||
} // namespace molo::google::adk
|
||||
@@ -0,0 +1,45 @@
|
||||
#pragma once
|
||||
|
||||
// Agent Studio export / import of an agent definition. The format follows
|
||||
// ADK's Agent Config (agent_class, name, model, description, instruction,
|
||||
// tools [{name}], sub_agents) with two local rules: sub_agents are inlined
|
||||
// objects (config_path references are rejected loudly) and workflow agents
|
||||
// carry max_iterations. A definition names tools; behavior comes from the
|
||||
// ToolRegistry at import time, so a definition never contains code.
|
||||
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "clients/body/json.h"
|
||||
#include "google/adk/agent.h"
|
||||
|
||||
namespace molo::google::adk {
|
||||
|
||||
class ToolRegistry {
|
||||
public:
|
||||
ToolRegistry(); // Pre-registers exit_loop.
|
||||
void add(std::shared_ptr<Tool> tool); // Replaces a tool of the same name.
|
||||
std::shared_ptr<Tool> find(const std::string& name) const;
|
||||
std::vector<std::string> names() const;
|
||||
std::size_t size() const { return tools_.size(); }
|
||||
|
||||
private:
|
||||
std::map<std::string, std::shared_ptr<Tool>> tools_;
|
||||
};
|
||||
|
||||
class AgentDefinition {
|
||||
public:
|
||||
static clients::body::Json to_json(const BaseAgent& agent);
|
||||
// Block-style YAML of the same document (clients::body::yaml_dump).
|
||||
static std::string to_yaml(const BaseAgent& agent);
|
||||
|
||||
// Validates class, names, tool names, counts, depth before building.
|
||||
static std::shared_ptr<BaseAgent> from_json(const clients::body::Json& doc,
|
||||
const ToolRegistry& registry);
|
||||
// Parses JSON text (at most kMaxDefinitionBytes) then from_json.
|
||||
static std::shared_ptr<BaseAgent> from_text(const std::string& text,
|
||||
const ToolRegistry& registry);
|
||||
};
|
||||
|
||||
} // namespace molo::google::adk
|
||||
@@ -0,0 +1,89 @@
|
||||
#include "google/adk/tool.h"
|
||||
|
||||
#include "google/adk/caps.h"
|
||||
#include "google/adk/error.h"
|
||||
|
||||
namespace molo::google::adk {
|
||||
|
||||
using clients::body::Json;
|
||||
|
||||
bool valid_identifier(const std::string& name) {
|
||||
if (name.empty() || name.size() > AdkCaps::kMaxNameChars) return false;
|
||||
for (std::size_t i = 0; i < name.size(); ++i) {
|
||||
char c = name[i];
|
||||
bool alpha = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_';
|
||||
bool digit = c >= '0' && c <= '9';
|
||||
if (!(alpha || (digit && i > 0))) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
FunctionTool::FunctionTool(std::string name, std::string description,
|
||||
Json schema, Fn fn)
|
||||
: name_(std::move(name)),
|
||||
description_(std::move(description)),
|
||||
schema_(std::move(schema)),
|
||||
fn_(std::move(fn)) {
|
||||
if (!valid_identifier(name_))
|
||||
throw AdkError::invalid("tool name must match [A-Za-z_][A-Za-z0-9_]*");
|
||||
if (!fn_) throw AdkError::invalid("tool function is empty");
|
||||
if (!schema_.is_null() && !schema_.is_object())
|
||||
throw AdkError::invalid("tool schema must be an object or null");
|
||||
}
|
||||
|
||||
FunctionDeclaration FunctionTool::declaration() const {
|
||||
FunctionDeclaration d;
|
||||
d.name = name_;
|
||||
d.description = description_;
|
||||
d.parameters = schema_;
|
||||
return d;
|
||||
}
|
||||
|
||||
namespace {
|
||||
bool type_matches(const std::string& type, const Json& v) {
|
||||
if (type == "string") return v.is_string();
|
||||
if (type == "number") return v.is_number();
|
||||
if (type == "integer")
|
||||
return v.is_number() && v.as_number() == static_cast<double>(v.as_int());
|
||||
if (type == "boolean") return v.is_bool();
|
||||
if (type == "object") return v.is_object();
|
||||
if (type == "array") return v.is_array();
|
||||
return true; // Unknown type names are not enforced.
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void FunctionTool::validate(const Json& schema, const Json& args) {
|
||||
if (schema.is_null()) return;
|
||||
if (!args.is_object()) throw AdkError::invalid("arguments must be an object");
|
||||
if (const Json* req = schema.find("required"); req && req->is_array())
|
||||
for (const Json& k : req->as_array())
|
||||
if (k.is_string() && !args.has(k.as_string()))
|
||||
throw AdkError::invalid("missing required argument: " + k.as_string());
|
||||
const Json* props = schema.find("properties");
|
||||
if (!props || !props->is_object()) return;
|
||||
for (const auto& [key, def] : props->as_object()) {
|
||||
const Json* v = args.find(key);
|
||||
if (!v) continue;
|
||||
const Json* t = def.find("type");
|
||||
if (t && t->is_string() && !type_matches(t->as_string(), *v))
|
||||
throw AdkError::invalid("argument " + key + " must be " + t->as_string());
|
||||
}
|
||||
}
|
||||
|
||||
Json FunctionTool::call(const Json& args, ToolContext& context) {
|
||||
validate(schema_, args);
|
||||
return fn_(args, context);
|
||||
}
|
||||
|
||||
std::shared_ptr<Tool> make_exit_loop_tool() {
|
||||
return std::make_shared<FunctionTool>(
|
||||
"exit_loop", "Call when the task is done to stop the surrounding loop.",
|
||||
Json(), [](const Json&, ToolContext& ctx) {
|
||||
ctx.escalate = true;
|
||||
Json out = Json::object();
|
||||
out.set("ok", Json(true));
|
||||
return out;
|
||||
});
|
||||
}
|
||||
|
||||
} // namespace molo::google::adk
|
||||
@@ -0,0 +1,62 @@
|
||||
#pragma once
|
||||
|
||||
// Tool seam of the ADK. A Tool has a Gemini function declaration and a
|
||||
// call(). FunctionTool builds one from a lambda plus a JSON schema and
|
||||
// validates arguments (required keys, basic types) before the lambda runs.
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "clients/body/json.h"
|
||||
#include "google/gemini_types.h"
|
||||
|
||||
namespace molo::google::adk {
|
||||
|
||||
// What a tool may touch during one call.
|
||||
struct ToolContext {
|
||||
clients::body::Json& state; // Session state (object), shared per turn.
|
||||
std::string agent; // Name of the calling agent.
|
||||
bool& escalate; // Set true to end the enclosing LoopAgent.
|
||||
};
|
||||
|
||||
class Tool {
|
||||
public:
|
||||
virtual ~Tool() = default;
|
||||
virtual const std::string& name() const = 0;
|
||||
virtual FunctionDeclaration declaration() const = 0;
|
||||
// Throws AdkError on failure; the agent turns that into a function
|
||||
// response {"error": "..."} so the model can recover.
|
||||
virtual clients::body::Json call(const clients::body::Json& args,
|
||||
ToolContext& context) = 0;
|
||||
};
|
||||
|
||||
class FunctionTool : public Tool {
|
||||
public:
|
||||
using Fn = std::function<clients::body::Json(const clients::body::Json& args,
|
||||
ToolContext& context)>;
|
||||
// schema: OpenAPI-subset object schema, or null for no parameters.
|
||||
FunctionTool(std::string name, std::string description,
|
||||
clients::body::Json schema, Fn fn);
|
||||
|
||||
const std::string& name() const override { return name_; }
|
||||
FunctionDeclaration declaration() const override;
|
||||
clients::body::Json call(const clients::body::Json& args,
|
||||
ToolContext& context) override;
|
||||
|
||||
// Checks required keys and the primitive type of declared properties
|
||||
// (string, number, integer, boolean, object, array). Throws AdkError.
|
||||
static void validate(const clients::body::Json& schema,
|
||||
const clients::body::Json& args);
|
||||
|
||||
private:
|
||||
std::string name_;
|
||||
std::string description_;
|
||||
clients::body::Json schema_;
|
||||
Fn fn_;
|
||||
};
|
||||
|
||||
// Built-in: ends the enclosing LoopAgent ("exit_loop").
|
||||
std::shared_ptr<Tool> make_exit_loop_tool();
|
||||
|
||||
} // namespace molo::google::adk
|
||||
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fails when a Google call declared in direct_model.h is not in Discovery.
|
||||
|
||||
Reads the table between DISCOVERY-TABLE-BEGIN / END in direct_model.h, fetches
|
||||
https://<service>.googleapis.com/$discovery/rest?version=<v> (no auth), and
|
||||
checks: method id exists, HTTP verb matches, flatPath matches, and every
|
||||
declared request field exists in the method's request schema.
|
||||
Usage: python3 -I src/google/adk/tools/check_discovery.py
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
HEADER = os.path.join(os.path.dirname(__file__), "..", "direct_model.h")
|
||||
|
||||
|
||||
def parse_table():
|
||||
text = open(HEADER).read()
|
||||
block = text.split("DISCOVERY-TABLE-BEGIN")[1].split("DISCOVERY-TABLE-END")[0]
|
||||
calls = re.findall(r'\{"(\w+)", "(\w+)", "([\w.]+)", "(\w+)", "([^"]+)"\}', block)
|
||||
req = block.split("kDirectRequestFields")[1].split("};")[0]
|
||||
part = block.split("kDirectPartFields")[1].split("};")[0]
|
||||
return calls, re.findall(r'"(\w+)"', req), re.findall(r'"(\w+)"', part)
|
||||
|
||||
|
||||
def methods(doc):
|
||||
out = {}
|
||||
|
||||
def walk(res, path):
|
||||
for k, v in res.get("resources", {}).items():
|
||||
walk(v, path + [k])
|
||||
for k, m in res.get("methods", {}).items():
|
||||
out[".".join(path + [k])] = m
|
||||
|
||||
walk(doc, [])
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
calls, fields, part_fields = parse_table()
|
||||
if not calls or not fields or not part_fields:
|
||||
print("FAIL: empty declared table")
|
||||
return 1
|
||||
cache, failures = {}, 0
|
||||
for service, version, rpc, http, flat in calls:
|
||||
key = (service, version)
|
||||
if key not in cache:
|
||||
url = f"https://{service}.googleapis.com/$discovery/rest?version={version}"
|
||||
with urllib.request.urlopen(url, timeout=60) as r:
|
||||
doc = json.load(r)
|
||||
cache[key] = (doc, methods(doc))
|
||||
doc, table = cache[key]
|
||||
m = table.get(rpc)
|
||||
if not m:
|
||||
print(f"FAIL {service} {version}: no method {rpc}")
|
||||
failures += 1
|
||||
continue
|
||||
if m["httpMethod"] != http or m.get("flatPath") != flat:
|
||||
print(f"FAIL {rpc}: discovery says {m['httpMethod']} {m.get('flatPath')}")
|
||||
failures += 1
|
||||
continue
|
||||
schema = doc["schemas"][m["request"]["$ref"]]["properties"]
|
||||
for f in fields:
|
||||
if f not in schema:
|
||||
print(f"FAIL {rpc}: request schema has no field {f}")
|
||||
failures += 1
|
||||
part = [v for k, v in doc["schemas"].items() if k.endswith("Part") and "properties" in v]
|
||||
for f in part_fields:
|
||||
if not any(f in v["properties"] for v in part):
|
||||
print(f"FAIL {service} {version}: Part schema has no field {f}")
|
||||
failures += 1
|
||||
print(f"ok {service} {version} {rpc} {http} {flat}")
|
||||
print("PASS" if not failures else f"{failures} failure(s)")
|
||||
return 1 if failures else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,75 @@
|
||||
#include "google/adk/trigger.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include "google/adk/caps.h"
|
||||
#include "google/adk/error.h"
|
||||
|
||||
namespace molo::google::adk {
|
||||
|
||||
namespace {
|
||||
std::vector<TriggerEvent> take(std::deque<TriggerEvent>& q, std::size_t n) {
|
||||
std::vector<TriggerEvent> out;
|
||||
while (!q.empty() && out.size() < n) {
|
||||
out.push_back(std::move(q.front()));
|
||||
q.pop_front();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
bool QueueTrigger::push(TriggerEvent event) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (queue_.size() >= AdkCaps::kMaxTriggerQueue) {
|
||||
++dropped_;
|
||||
return false;
|
||||
}
|
||||
queue_.push_back(std::move(event));
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<TriggerEvent> QueueTrigger::poll(std::size_t max_events) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return take(queue_, max_events);
|
||||
}
|
||||
|
||||
std::size_t QueueTrigger::dropped() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return dropped_;
|
||||
}
|
||||
|
||||
std::size_t QueueTrigger::pending() const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return queue_.size();
|
||||
}
|
||||
|
||||
BatchTrigger::BatchTrigger(std::vector<TriggerEvent> events) {
|
||||
if (events.size() > AdkCaps::kMaxTriggerQueue)
|
||||
throw AdkError::invalid("batch over the trigger queue cap");
|
||||
for (auto& e : events) queue_.push_back(std::move(e));
|
||||
}
|
||||
|
||||
std::vector<TriggerEvent> BatchTrigger::poll(std::size_t max_events) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
return take(queue_, max_events);
|
||||
}
|
||||
|
||||
std::vector<DispatchOutcome> TriggerDispatcher::dispatch(Trigger& trigger,
|
||||
std::size_t max_events) {
|
||||
max_events = std::min(max_events, AdkCaps::kMaxTriggerBatch);
|
||||
std::vector<DispatchOutcome> out;
|
||||
for (TriggerEvent& e : trigger.poll(max_events)) {
|
||||
DispatchOutcome o;
|
||||
o.event_id = e.id;
|
||||
try {
|
||||
o.result = runner_->run(agent_, e.id, e.payload, "trigger");
|
||||
o.ok = true;
|
||||
} catch (const std::exception& ex) {
|
||||
o.error = ex.what();
|
||||
}
|
||||
out.push_back(std::move(o));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace molo::google::adk
|
||||
@@ -0,0 +1,76 @@
|
||||
#pragma once
|
||||
|
||||
// Batch and event-driven triggers as plain local interfaces. The Agent
|
||||
// Runtime triggers (BigQuery, Pub/Sub) belong to the runtime module; this
|
||||
// seam only says "something produced work for an agent". A Trigger yields
|
||||
// events; TriggerDispatcher runs one agent turn per event with hard caps.
|
||||
|
||||
#include <deque>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "google/adk/runner.h"
|
||||
|
||||
namespace molo::google::adk {
|
||||
|
||||
struct TriggerEvent {
|
||||
std::string id; // Used as the session id: [A-Za-z0-9._-], 1..128
|
||||
std::string payload; // Becomes the user message
|
||||
};
|
||||
|
||||
class Trigger {
|
||||
public:
|
||||
virtual ~Trigger() = default;
|
||||
// Returns at most max_events pending events and removes them.
|
||||
virtual std::vector<TriggerEvent> poll(std::size_t max_events) = 0;
|
||||
};
|
||||
|
||||
// Event-driven: a producer pushes, the dispatcher polls. Bounded queue;
|
||||
// push returns false (and counts a drop) when full.
|
||||
class QueueTrigger : public Trigger {
|
||||
public:
|
||||
bool push(TriggerEvent event);
|
||||
std::vector<TriggerEvent> poll(std::size_t max_events) override;
|
||||
std::size_t dropped() const;
|
||||
std::size_t pending() const;
|
||||
|
||||
private:
|
||||
mutable std::mutex mutex_;
|
||||
std::deque<TriggerEvent> queue_;
|
||||
std::size_t dropped_ = 0;
|
||||
};
|
||||
|
||||
// Batch: a fixed list of inputs handed out in slices.
|
||||
class BatchTrigger : public Trigger {
|
||||
public:
|
||||
explicit BatchTrigger(std::vector<TriggerEvent> events);
|
||||
std::vector<TriggerEvent> poll(std::size_t max_events) override;
|
||||
|
||||
private:
|
||||
std::mutex mutex_;
|
||||
std::deque<TriggerEvent> queue_;
|
||||
};
|
||||
|
||||
struct DispatchOutcome {
|
||||
std::string event_id;
|
||||
bool ok = false;
|
||||
std::string error; // Set when !ok
|
||||
RunResult result;
|
||||
};
|
||||
|
||||
class TriggerDispatcher {
|
||||
public:
|
||||
TriggerDispatcher(std::shared_ptr<Runner> runner, std::shared_ptr<BaseAgent> agent)
|
||||
: runner_(std::move(runner)), agent_(std::move(agent)) {}
|
||||
// One poll of at most max_events (capped at kMaxTriggerBatch). A failing
|
||||
// event is reported in its outcome and does not stop the rest.
|
||||
std::vector<DispatchOutcome> dispatch(Trigger& trigger, std::size_t max_events);
|
||||
|
||||
private:
|
||||
std::shared_ptr<Runner> runner_;
|
||||
std::shared_ptr<BaseAgent> agent_;
|
||||
};
|
||||
|
||||
} // namespace molo::google::adk
|
||||
Reference in New Issue
Block a user