-
Notifications
You must be signed in to change notification settings - Fork 712
Expand file tree
/
Copy pathagent.py
More file actions
205 lines (172 loc) · 7 KB
/
Copy pathagent.py
File metadata and controls
205 lines (172 loc) · 7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Layer 1 API for Antigravity SDK."""
import contextlib
import logging
from typing import cast
from google.antigravity import types
from google.antigravity.connections import connection as connection_module
from google.antigravity.conversation import conversation
from google.antigravity.hooks import hook_runner
from google.antigravity.hooks import policy
from google.antigravity.tools import tool_context
from google.antigravity.tools import tool_runner
from google.antigravity.triggers import trigger_runner
__all__ = ["Agent"]
class Agent:
"""High-level Agent API for simplified interaction."""
def __init__(self, config: connection_module.AgentConfig):
"""Initializes the Agent.
Args:
config: Declarative agent configuration.
"""
self._config = config.model_copy(deep=True)
if self._config.response_schema:
# The response_schema is validated/stringified in AgentConfig.
self._config.capabilities.finish_tool_schema_json = cast(
str, self._config.response_schema
)
self._strategy = None
self._conversation = None
self._tool_runner = None
self._hook_runner = None
self._trigger_runner = None
# Use the original config (not self._config) for hooks and triggers:
# model_copy(deep=True) creates new objects, breaking reference equality
# for user-provided hooks/triggers. The list() snapshot prevents the
# caller from mutating our copy, while preserving object identity.
self._pending_hooks = list(config.hooks)
self._pending_triggers = list(config.triggers)
self._exit_stack = contextlib.AsyncExitStack()
async def __aenter__(self) -> "Agent":
"""Starts the agent session.
Returns:
The started Agent instance.
"""
logging.info("Starting Agent session")
try:
self._hook_runner = hook_runner.HookRunner()
# Register pending hooks
for hook in self._pending_hooks:
self._hook_runner.register_hook(hook)
self._pending_hooks.clear()
# Apply policies
active_policies = list(self._config.policies)
cfg = self._config.capabilities
read_only_tools = set(types.BuiltinTools.read_only())
# enabled_tools and disabled_tools are mutually exclusive
# (enforced by CapabilitiesConfig validation).
if cfg.enabled_tools is not None:
active_tools = set(cfg.enabled_tools)
elif cfg.disabled_tools is not None:
active_tools = set(types.BuiltinTools) - set(cfg.disabled_tools)
else:
active_tools = set(types.BuiltinTools)
has_write_tools = bool(active_tools - read_only_tools)
has_mcp_servers = bool(self._config.mcp_servers)
has_tool_decide_hook = bool(self._hook_runner.pre_tool_call_decide_hooks)
if (
(has_write_tools or has_mcp_servers)
and not active_policies
and not has_tool_decide_hook
):
raise ValueError(
"Write tools or MCP servers are enabled without a safety policy. "
"Add policies=[policy.allow_all()] to approve all tool calls, "
"or policies=[policy.deny_all(), policy.allow('tool_name')] "
"to selectively allow specific tools."
)
if active_policies:
self._hook_runner.register_hook(
policy.enforce(
active_policies, mcp_servers=self._config.mcp_servers
)
)
all_tools = list(self._config.tools)
self._tool_runner = tool_runner.ToolRunner(tools=all_tools)
self._strategy = self._config.create_strategy(
tool_runner=self._tool_runner,
hook_runner=self._hook_runner,
)
logging.info("Starting connection and creating conversation...")
self._conversation = await self._exit_stack.enter_async_context(
conversation.Conversation.create(self._strategy)
)
# Start triggers via TriggerRunner.
if self._pending_triggers:
logging.info("Starting triggers...")
self._trigger_runner = await self._exit_stack.enter_async_context(
trigger_runner.TriggerRunner(
triggers=list(self._pending_triggers),
connection=self.conversation.connection,
)
)
self._pending_triggers.clear()
# Wire ToolContext into ToolRunner so tools can access
# conversation capabilities (same pattern as TriggerRunner).
if self._tool_runner:
ctx = tool_context.ToolContext(self.conversation)
self._tool_runner.set_context(ctx)
return self
except Exception:
logging.exception("Failed to start Agent session, cleaning up...")
await self._exit_stack.aclose()
raise
async def __aexit__(self, exc_type, exc_val, exc_tb):
"""Stops the agent session.
Args:
exc_type: The exception type, if any.
exc_val: The exception value, if any.
exc_tb: The traceback, if any.
Returns:
True if the exception was suppressed, False or None otherwise.
"""
logging.info("Stopping Agent session")
return await self._exit_stack.__aexit__(exc_type, exc_val, exc_tb)
async def chat(self, prompt: types.Content) -> types.ChatResponse:
"""Sends a prompt and returns the final response.
Args:
prompt: The user prompt or content to send.
Returns:
The final response from the agent.
"""
return await self.conversation.chat(prompt)
@property
def is_started(self) -> bool:
"""Whether the agent session has been started."""
return self._conversation is not None
@property
def conversation(self) -> conversation.Conversation:
"""Returns the active Conversation session.
Use this for advanced session introspection: history, turn count,
compaction indices, usage, or direct send/receive_steps control.
For most use cases, prefer chat() instead.
Raises:
RuntimeError: If the agent session has not been started.
"""
if not self._conversation:
raise RuntimeError(
"Agent session not started. Use 'async with Agent(...)'."
)
return self._conversation
@property
def conversation_id(self) -> str | None:
"""Returns the conversation identifier assigned by the runtime.
Available after the session has started and at least one message has
been exchanged. Pass this value back via SessionConfig.conversation_id
to resume from a saved session. Returns None before the session starts.
"""
if not self._conversation:
return None
return self._conversation.conversation_id or None