Aller au contenu principal

Autoriser les agents à exécuter du code

Databricks fournit system.ai.python_exec, une fonction intégrée de Unity Catalog qui permet aux agents d'exécuter dynamiquement du code Python écrit par l'agent, fourni par un utilisateur ou extrait d'une base de code. Il est disponible par default et peut être utilisé directement dans une SQL query :

SQL
SELECT python_exec("""
import random
numbers = [random.random() for _ in range(10)]
print(numbers)
""")

Pour en savoir plus sur les outils d'agent, consultez MCP et outils d'agent.

Ajouter l'interpréteur de code à votre agent

Pour ajouter python_exec à votre agent, connectez-vous au serveur MCP géré pour le schéma Unity Catalog system.ai. L'interpréteur de code est disponible comme un outil MCP préconfiguré à https://<workspace-hostname>/api/2.0/mcp/functions/system/ai/python_exec.

Python
from agents import Agent, Runner
from databricks.sdk import WorkspaceClient
from databricks_openai.agents import McpServer

# WorkspaceClient picks up credentials from the environment (Databricks Apps, notebook, CLI)
workspace_client = WorkspaceClient()
host = workspace_client.config.host

# The context manager manages the MCP connection lifecycle and ensures cleanup on exit.
# from_uc_function constructs the endpoint URL from UC identifiers and wires in auth
# from workspace_client, avoiding hardcoded URLs and manual token handling.
async with McpServer.from_uc_function(
catalog="system",
schema="ai",
function_name="python_exec",
workspace_client=workspace_client,
name="code-interpreter",
) as code_interpreter:
agent = Agent(
name="Coding agent",
instructions="You are a helpful coding assistant. Use the python_exec tool to run code.",
model="databricks-claude-sonnet-4-5",
mcp_servers=[code_interpreter],
)
result = await Runner.run(agent, "Calculate the first 10 Fibonacci numbers")
print(result.final_output)

Accordez à l’application l’accès à la fonction dans databricks.yml:

YAML
resources:
apps:
my_agent_app:
resources:
- name: 'python_exec'
uc_securable:
securable_full_name: 'system.ai.python_exec'
securable_type: 'FUNCTION'
permission: 'EXECUTE'

Ressources supplémentaires