valkryhx/google_adk_agent / skills/programmatic-tool-calling
programmatic-tool-calling
Verified编程化工具调用指南。允许 Agent 编写并执行 Python 代码,从而能够在一个沙箱环境中动态调用其他工具,实现循环、批处理和复杂逻辑。
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 5.2 KB |
| SKILL.md.metadata.json | config | 158 B |
| SKILL.md.resolved | other | 2.6 KB |
| assets/example_asset.txt | markdown | 865 B |
| references/api_reference.md | markdown | 976 B |
| scripts/example.py | script | 609 B |
| tools.py | script | 3.9 KB |
tools.py
View on GitHubimport sys
import os
import asyncio
import inspect
from typing import List, Any
# Adapt path to import from core
current_dir = os.path.dirname(os.path.abspath(__file__))
# 假设 agent_root 是 skills/adk_agent 的父目录
# 目录结构: skills/programmatic-tool-calling/tools.py
# 需要回退2层到 skills/ 前面,即项目根目录
agent_root = os.path.dirname(os.path.dirname(current_dir))
if agent_root not in sys.path:
sys.path.insert(0, agent_root)
# Import the new async executor
try:
from src.adk_agent.core.executor import execute_async_python_code
except ImportError:
# Fallback if run from different context
from core.executor import execute_async_python_code
# Global references to injected services
_AGENT_REF = None
def _format_missing_tool_diagnostic(tool_name: str) -> str:
loaded_tool_names = []
if _AGENT_REF and hasattr(_AGENT_REF, 'tools'):
loaded_tool_names = [
getattr(tool, '__name__', str(tool))
for tool in _AGENT_REF.tools
]
if tool_name.startswith("dex_"):
dex_tools = [name for name in loaded_tool_names if name.startswith("dex_")]
return (
f"[DIAG] Tool '{tool_name}' 未加载到当前 agent.tools 中。\n"
f"loaded_tools={loaded_tool_names}\n"
f"loaded_dex_tools={dex_tools}\n"
"这通常表示当前 session 的 dex skill 没有真正挂载成功。"
"请先让 agent 检查/重载 dex skill,"
"不要直接 import dex 模块,也不要手动实例化 DexManager(),"
"否则任务可能因为缺少 user_id 而写入 global。"
)
return f"[Error] Tool '{tool_name}' not found. Loaded tools: {loaded_tool_names}"
async def run_programmatic_task(code: str, **kwargs) -> str:
"""
通过编写 Python 代码来执行任务。
可以在代码中使用 `await call_tool("工具名", 参数=值)` 来调用 Agent 的其他工具。
Args:
code: 要执行的 Python 代码。
支持 pandas, matplotlib, asyncio。
如果需要调用其他工具,请务必使用 `await call_tool(...)`。
Returns:
执行输出 (stdout)
"""
global _AGENT_REF
# === 定义 Bridge 函数 ===
async def call_tool_bridge(tool_name: str, **kwargs) -> Any:
"""
Injected bridge to call other tools from within the sandbox.
"""
print(f"[Sandbox] Requesting tool: {tool_name} with {kwargs}")
if not _AGENT_REF:
# 尝试回退:检查是否有 bash (Hack for standalone testing)
# 但在 Agent 环境中应该总是有 _AGENT_REF
return "[Error] Agent reference lost."
# 1. Find the tool
target_tool = None
# _AGENT_REF.tools 应该是一个工具列表
if hasattr(_AGENT_REF, 'tools'):
for tool in _AGENT_REF.tools:
t_name = getattr(tool, '__name__', str(tool))
if t_name == tool_name:
target_tool = tool
break
if not target_tool:
return _format_missing_tool_diagnostic(tool_name)
# 2. Execute the tool
try:
# Check if it's a coroutine
if inspect.iscoroutinefunction(target_tool):
return await target_tool(**kwargs)
else:
return target_tool(**kwargs)
except Exception as e:
return f"[Error executing {tool_name}] {e}"
# === 执行代码 ===
context = {
"call_tool": call_tool_bridge
}
return await execute_async_python_code(code, context)
def get_tools(agent, session_service, *args, **kwargs) -> List:
"""
Factory method to initialize the tool with Agent access.
"""
global _AGENT_REF
_AGENT_REF = agent
return [run_programmatic_task]
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. | Stars: 471k | Updated | Claude CodeCodex | Verified | Install |
| diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness. | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |