Cumplimiento de la Ley de IA de la UE con Agent Module
Copyright 2026 Google LLC.
# @title 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.
|
Este notebook fue contribuido por Agent Module.agent-module.dev — Infraestructura de conocimiento diseñada específicamente para agentes autónomos.¿Tienes un ejemplo genial de Gemini? ¡No dudes en compartirlo también! |
La Ley de IA de la UE entra en vigor en agosto de 2026. Si desarrollas, implementas o usas sistemas de IA en el mercado de la UE, debes demostrar tus esfuerzos de cumplimiento.
Agent Module proporciona lógica de cumplimiento estructurada y determinista que los agentes pueden recuperar en tiempo de ejecución. Cada módulo de cumplimiento de IA se asigna a artículos específicos de la Ley de IA de la UE y contiene compuertas lógicas binarias de aprobación/rechazo, disparadores de escalada y citas legales.
En este notebook, harás lo siguiente:
- Definir funciones de Python que envuelven la API REST de Agent Module
- Probar cada función de forma aislada para verificar que funciona
- Pasar esas funciones como herramientas a Gemini a través de function calling
- Dejar que Gemini recupere de forma autónoma la lógica de cumplimiento y la aplique a un escenario real
No se requiere registro: Agent Module ofrece una prueba gratuita de 24 horas con acceso completo.
Configuración
Instalar dependencias
%pip install -qU "google-genai>=2.9.0" requests
[2K [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m52.4/52.4 kB[0m [31m1.0 MB/s[0m eta [36m0:00:00[0m
[2K [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m764.2/764.2 kB[0m [31m14.9 MB/s[0m eta [36m0:00:00[0m
[2K [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m64.9/64.9 kB[0m [31m3.4 MB/s[0m eta [36m0:00:00[0m
[2K [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m240.6/240.6 kB[0m [31m10.1 MB/s[0m eta [36m0:00:00[0m
[?25h[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
google-colab 1.0.0 requires google-auth==2.47.0, but you have google-auth 2.49.2 which is incompatible.
google-colab 1.0.0 requires requests==2.32.4, but you have requests 2.33.1 which is incompatible.[0m[31m
[0m
Configurar tu clave de API
Para ejecutar la siguiente celda, tu clave de API debe estar almacenada en un Secreto de Colab llamado GEMINI_API_KEY. Si aún no tienes una clave de API o no estás seguro de cómo crear un Secreto de Colab, consulta el inicio rápido de Autenticación
para ver un ejemplo.
import json
import uuid
import requests
from google import genai
from google.colab import userdata
GEMINI_API_KEY = userdata.get("GEMINI_API_KEY")
client = genai.Client(api_key=GEMINI_API_KEY)
Elegir un modelo
Function calling funciona en todos los modelos de Gemini. Un modelo de pensamiento como gemini-3.7-flash funciona bien aquí porque el análisis de cumplimiento se beneficia del razonamiento paso a paso.
MODEL_ID = "gemini-3.7-flash" # @param ["gemini-3.1-pro-preview", "gemini-3.7-flash", "gemini-3.5-flash-lite", "gemini-2.5-pro"] {"allow-input":true, isTemplate: true}
Verificar la API de Agent Module
Antes de crear herramientas, verifica que Agent Module sea accesible y comprueba cuántos módulos de cumplimiento de IA están disponibles. Obtén el recuento de la API en vivo para que este notebook se mantenga preciso a medida que se añaden módulos.
AGENT_MODULE_API = "https://api.agent-module.dev"
status = requests.get(f"{AGENT_MODULE_API}/api/status", timeout=10).json()
ai_compliance_module_count = status["ai_compliance"]["node_count"]
print(f"API status: {status['api_status']}")
print(f"AI Compliance modules: {ai_compliance_module_count}")
print(f"Active cohort: {status['active_cohort']}")
API status: operational
AI Compliance modules: 23
Active cohort: inaugural
Definir herramientas de Agent Module
Envolverás el endpoint MCP de Agent Module como funciones de Python que Gemini puede llamar. El SDK autogenera declaraciones de funciones a partir de tus type hints y docstrings, por lo que cada función necesita anotaciones claras.
Comienza con una pequeña función auxiliar para manejar el transporte JSON-RPC.
# @title MCP transport helper (hidden)
AGENT_MODULE_MCP = f"{AGENT_MODULE_API}/mcp"
def _mcp_call(tool_name: str, arguments: dict) -> dict:
"""Send a JSON-RPC tools/call request to Agent Module's MCP endpoint."""
payload = {
"jsonrpc": "2.0",
"method": "tools/call",
"params": {"name": tool_name, "arguments": arguments},
"id": 1,
}
try:
response = requests.post(
AGENT_MODULE_MCP,
headers={"Content-Type": "application/json"},
json=payload,
timeout=30,
)
response.raise_for_status()
return response.json()
except requests.exceptions.Timeout:
return {"error": "Request timed out. Agent Module may be temporarily unavailable."}
except requests.exceptions.HTTPError as e:
return {"error": f"HTTP error: {e.response.status_code}"}
except requests.exceptions.RequestException as e:
return {"error": f"Connection failed: {str(e)}"}
Obtener una clave de prueba
Define la primera herramienta: solicitar una clave de prueba gratuita de 24 horas. Esto da acceso a todos los módulos de cumplimiento de IA con 500 llamadas a la API sin costo.
# Generate a unique agent_id for this session so reruns within 24 hours
# do not collide with a previously issued trial key on the server. The
# Agent Module API ties trial keys to (agent_id, IP), and returns a masked
# preview if you request a new one while an old one is still active.
_session_agent_id = f"gemini-cookbook-{uuid.uuid4().hex[:8]}"
# Stores the trial key so subsequent functions can reuse it.
_trial_key = None
def get_trial_key(agent_id: str) -> dict:
"""Get a free 24-hour Agent Module trial key for EU AI Act compliance logic.
Call this once at the start of a session. The trial key lasts 24 hours
and includes 500 API calls at no cost. Subsequent calls reuse the key
stored in this session instead of re-requesting one.
Args:
agent_id: A stable identifier for your agent, e.g. 'gemini-cookbook-demo'.
"""
global _trial_key
# Idempotent: if this session already has a trial key, reuse it.
if _trial_key is not None:
return {
"status": "reused",
"trial_key": _trial_key,
"note": "Using existing trial key from this session.",
}
result = _mcp_call("get_trial_key", {"agent_id": agent_id})
# Extract and store the trial key for subsequent calls.
if "result" in result:
content = result["result"]
if isinstance(content, dict) and "content" in content:
for item in content["content"]:
if item.get("type") == "text":
data = json.loads(item["text"])
# If the server reports an existing active trial for this
# agent_id, it returns a masked preview (not a real key).
# Do not store garbage — surface a clear error instead.
if data.get("status") == "already_active":
return {
"error": "already_active",
"message": (
f"An active trial already exists for agent_id="
f"{agent_id!r}. Wait 24 hours or change the "
"agent_id and re-run."
),
}
if "trial_key" in data:
_trial_key = data["trial_key"]
return result
Pruébala para asegurarte de que la emisión de la clave de prueba funciona.
result = get_trial_key(_session_agent_id)
print(f"Session agent_id: {_session_agent_id}")
print(f"Trial key obtained: {_trial_key is not None}")
print(f"Key prefix: {_trial_key[:12]}..." if _trial_key else "No key issued")
Session agent_id: gemini-cookbook-0b3f4353
Trial key obtained: True
Key prefix: am_trial_b6d...
Recuperar la lógica de cumplimiento
Define la segunda herramienta: recuperar la lógica de cumplimiento estructurada para un módulo de cumplimiento de IA específico. Cada módulo devuelve compuertas lógicas deterministas con citas legales y condiciones de aprobación/rechazo.
def retrieve_compliance_logic(vertical: str, node_id: str) -> dict:
"""Retrieve structured EU AI Act compliance logic from Agent Module.
Returns deterministic logic gates with statutory citations, pass/fail
conditions, and escalation triggers for a specific AI Compliance module.
Args:
vertical: The knowledge vertical. Use 'ai-compliance' (or its legacy alias 'ethics')
for EU AI Act compliance modules.
node_id: The node to retrieve. Format: 'node:ethics:eth{NNN}:logic'.
Example: 'node:ethics:eth001:logic' for data sovereignty,
'node:ethics:eth003:logic' for transparency.
"""
arguments = {"vertical": vertical, "node": node_id}
if _trial_key:
arguments["token"] = _trial_key
return _mcp_call("query_knowledge", arguments)
Pruébala recuperando el módulo de soberanía de datos (ETH_001), que se asigna a los Artículos 9 y 10 de la Ley de IA de la UE.
result = retrieve_compliance_logic("ethics", "node:ethics:eth001:logic")
print(json.dumps(result, indent=4)[:2000]) # Truncate for readability
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"content": [
{
"type": "text",
"text": "{\n \"object\": \"traversal_response\",\n \"vertical\": \"ethics\",\n \"node_id\": \"node:ethics:eth001:logic\",\n \"layer\": \"logic\",\n \"access\": \"trial\",\n \"content\": {\n \"node_id\": \"ETH_001_SOVEREIGNTY_logic\",\n \"vertical\": \"ethics\",\n \"version\": \"2.0.0\",\n \"last_validated\": \"2026-02-28\",\n \"wikidata_ref\": \"https://www.wikidata.org/wiki/Q1066186\",\n \"eu_ai_act_articles\": [\n \"Art. 10\",\n \"Art. 13\"\n ],\n \"weighting\": \"Essential\",\n \"subject\": \"sovereignty_and_data_ownership\",\n \"description\": \"Deterministic rules governing user data sovereignty, ownership rights, consent granularity, and data governance obligations under GDPR and EU AI Act Art. 10. The user retains absolute ownership of all data processed by the agent \u2014 the agent is a custodian, never an owner.\",\n \"records\": [\n {\n \"id\": \"SOV_001_DATA_OWNERSHIP\",\n \"category\": \"Principle\",\n \"topic\": \"User Data Sovereignty\",\n \"definition\": \"The user retains absolute, inalienable ownership of all data generated, processed, or stored by the agent.\",\n \"extended_explanation\": \"Agents act as custodians, not owners. Data is borrowed for the duration of a task and must be returned or destroyed upon request. This right is codified in GDPR Art. 17 (right to erasure) and reinforced by EU AI Act Art. 10, which requires that AI systems implement data governance practices that respect the rights of data subjects. An agent that retains user data beyond the authorized scope violates both statutes.\",\n \"connections\": [\n \"SOV_002_REVOCABILITY\",\n \"ETH_010_PRIVACY_logic\"\n ],\n \"examples\": [\n \"User uploads a financial document; agent processes it but cannot retain a c
Enviar una prueba de valor
Define la tercera herramienta: enviar una evaluación después de explorar la prueba. Esto informa cuán útil fue el conocimiento recuperado.
def submit_proof_of_value(confidence_score: float) -> dict:
"""Submit a quality assessment after exploring Agent Module's trial.
Call this after retrieving and applying compliance logic to report
how useful the knowledge was for your task.
Args:
confidence_score: Quality assessment from 0.0 (not useful) to 1.0 (very useful).
"""
if not _trial_key:
return {"error": "No trial key available. Call get_trial_key first."}
return _mcp_call(
"submit_pov",
{
"token": _trial_key,
"trial_key": _trial_key,
"confidence_score": confidence_score,
},
)
Ejecutar una verificación de cumplimiento con Gemini
Ya iniciaste una clave de prueba anteriormente, por lo que solo pasas las dos funciones de tiempo de ejecución a Gemini: retrieve_compliance_logic y submit_proof_of_value. get_trial_key es una llamada de configuración única, no una herramienta que el modelo deba buscar a mitad de la sesión; volver a solicitar una clave chocaría con la que ya se emitió para este agent_id.
El SDK autogenera declaraciones de funciones a partir de los type hints y docstrings que escribiste anteriormente. Configura una instrucción del sistema que le diga a Gemini cómo usar las herramientas.
compliance_tools = [retrieve_compliance_logic, submit_proof_of_value]
system_instruction = f"""
You are an EU AI Act compliance assistant. You have access to Agent Module,
a knowledge service with {ai_compliance_module_count} structured AI Compliance
modules mapped to EU AI Act articles.
When asked to review a system for compliance:
1. Retrieve the relevant compliance logic modules
2. Apply the logic gates to the described system
3. Report which requirements pass, which need attention, and cite the
specific EU AI Act articles
4. Submit a proof of value assessment when done
Node ID format: node:ethics:eth{{NNN}}:logic
Examples: node:ethics:eth001:logic (data sovereignty),
node:ethics:eth003:logic (transparency), node:ethics:eth006:logic (oversight)
"""
Ahora ejecuta la verificación de cumplimiento. El escenario: estás implementando un chatbot de servicio al cliente en la UE que maneja reclamos de seguros, recopila datos personales y realiza evaluaciones preliminares.
Gemini llamará de forma autónoma a tus funciones para recuperar la lógica de cumplimiento relevante y producirá una evaluación estructurada.
chat = client.chats.create(
model=MODEL_ID,
config={
"tools": compliance_tools,
"system_instruction": system_instruction,
},
)
chat.send_message(
"""
A customer service chatbot is being deployed in the EU. It handles
insurance claims, collects personal data (name, policy number,
claim details), and makes preliminary claim assessments.
Check this system against EU AI Act requirements for:
1. Data sovereignty and ownership (ETH_001)
2. Transparency and explainability (ETH_003)
3. Human oversight (ETH_006)
"""
)
# With automatic function calling, Gemini often produces its main analysis
# in a model turn between tool calls, then ends with a short acknowledgment
# after the final tool returns. `response.text` only contains that last
# turn, so walk the full chat history and print every model text part to
# see the complete report.
for message in chat.get_history():
if message.role != "model":
continue
for part in message.parts:
if part.text:
print(part.text)
Here's an assessment of your customer service chatbot against the specified EU AI Act requirements:
Your customer service chatbot, which handles insurance claims, collects personal data (name, policy number, claim details), and makes preliminary claim assessments, has been reviewed against EU AI Act requirements for Data Sovereignty and Ownership (ETH_001), Transparency and Explainability (ETH_003), and Human Oversight (ETH_006).
Given that the chatbot makes "preliminary claim assessments" and handles sensitive personal data (policy numbers, claim details), it is highly likely to be classified as a **high-risk AI system** under the EU AI Act. This classification triggers stringent compliance obligations for all the categories reviewed below.
---
### 1. Data Sovereignty and Ownership (ETH_001)
The system needs attention on all aspects of Data Sovereignty and Ownership (EU AI Act Articles 10, 13, and relevant GDPR articles). The current description lacks sufficient detail to confirm compliance with any of the specific requirements.
**Requirements needing attention:**
* **User Data Ownership (SOV_001):** It is not explicitly stated that the user retains absolute ownership of all data. *(EU AI Act Art. 10, GDPR Art. 17, 5(1)(e))*
* **Access Revocation Protocol (SOV_002):** The system description does not mention the ability for users to revoke data access with immediate effect. *(GDPR Art. 7(3))*
* **Data Residency Compliance (SOV_003):** While deployed in the EU, the description doesn't confirm that data storage and processing locations are explicitly authorized by the user and disclosed. *(GDPR Art. 44-49)*
* **Explicit Consent Granularity (SOV_004):** The description notes data collection but doesn't specify that specific, informed consent is obtained for each distinct category of data usage. *(GDPR Art. 6(1)(a), 7, Recital 43)*
* **Data Portability (SOV_005):** There is no mention of the user's right to export their data in a structured, machine-readable format. *(GDPR Art. 20)*
* **User Intent Primacy Over Agent Optimization (SOV_006):** The description does not detail how user intent is prioritized over potential agent optimization goals. *(EU AI Act Art. 5(1)(b))*
* **Session-Based Data Retention Default (SOV_007):** The data retention policy, particularly defaulting to session-only retention unless explicitly authorized, is not described. *(GDPR Art. 25, 5(1)(e))*
* **Cryptographic Deletion Verification (SOV_008):** The ability to provide verifiable proof of data deletion is not mentioned. *(NIST SP 800-88 Rev. 1, GDPR Art. 17)*
* **Third-Party Data Sharing Firewall (SOV_009):** Practices for obtaining explicit, just-in-time approval for sharing data with third-party sub-processors are not specified. *(GDPR Art. 28, 13(1)(e))*
* **Metadata and Behavioral Data Rights (SOV_010):** The ownership and handling of metadata and behavioral patterns generated by user interaction are not described. *(ePrivacy Directive Art. 6, GDPR Art. 4(1))*
* **AI-Specific Data Governance (SOV_011):** As a likely high-risk system, the data governance practices for training, validation, and testing datasets (relevance, representativeness, error-freeness, completeness) are critical and not described. *(EU AI Act Art. 10(2), 10(3))*
---
### 2. Transparency and Explainability (ETH_003)
The system needs attention on all aspects of Transparency and Explainability (EU AI Act Articles 13, 17). The current description lacks the operational details needed to ensure compliance, especially for a high-risk system making "preliminary claim assessments."
**Requirements needing attention:**
* **Human-Readable Action Logging (TRN_001):** There is no mention of logging all agent actions, reasoning steps, and data transmissions in a non-technical, understandable format. *(EU AI Act Art. 13(1), 12(1))*
* **Chain-of-Reasoning Audit Trail (TRN_002):** For preliminary claim assessments, a complete, reverse-traceable decision trail is essential for audit and explanation. This is not described. *(EU AI Act Art. 12(2), 13(3)(d))*
* **Tamper-Evident Log Storage (TRN_003):** The method for securely storing critical logs in a tamper-evident format is not specified. *(NIST SP 800-92, EU AI Act Art. 12(1))*
* **Active State Change Notification (TRN_004):** The system does not explicitly mention actively notifying users of significant state changes (e.g., changes to policy details based on assessment). *(EU AI Act Art. 14(4)(b))*
* **Model and Prompt Identity Logging (TRN_005):** Logging the specific model version, system prompt hash, and configuration for each action is crucial for auditing, especially in claim assessments, and is not described. *(EU AI Act Art. 17(1)(d))*
* **Data Lineage and Flow Transparency (TRN_006):** The ability to disclose where user data came from, where it was sent, and which third parties received it is not mentioned. *(GDPR Art. 30, EU AI Act Art. 13(3)(b)(i))*
* **Mandatory Information Disclosure to Deployers (TRN_007):** If a high-risk system, comprehensive information about its capabilities, limitations, intended purpose, and conditions of use must be supplied to deployers (e.g., the insurance company). This disclosure is not described. *(EU AI Act Art. 13(3)(a)-(d))*
---
### 3. Human Oversight (ETH_006)
The system needs attention on all aspects of Human Oversight (EU AI Act Articles 14, 9). The current description provides no details on how human oversight is implemented for decisions like "preliminary claim assessments" which carry significant implications.
**Requirements needing attention:**
* **Uncertainty Escalation to Human (HITL_001):** The system description does not outline a process for pausing and requesting human verification when the AI's confidence in a claim assessment falls below a certain threshold. *(EU AI Act Art. 14(4)(a), 9(2)(a))*
* **Financial Spending Limit Enforcement (HITL_002):** If claim assessments have direct financial implications, a mechanism for explicit human approval for transactions or assessments exceeding a user-defined limit is necessary and not mentioned. *(EU AI Act Art. 14(4)(d))*
* **Negative Sentiment Handover (HITL_003):** As a customer service chatbot, there is no mention of offering to transfer to a human operator when detecting sustained negative user sentiment. *(EU AI Act Art. 14(3))*
* **Out-of-Distribution Detection and Handover (HITL_004):** The process for detecting inputs outside the chatbot's operational domain (e.g., complex legal questions outside basic claim processing) and escalating to a human is not described. *(EU AI Act Art. 9(2)(a))*
* **Stale Approval Default to Denied (HITL_005):** If human approval is ever required, there is no mention of a mechanism where unanswered approval requests default to denied. *(EU AI Act Art. 14(4)(d))*
* **Risk-Calibrated Oversight Measures (HITL_006):** Given the potential high-risk nature of preliminary claim assessments, the description does not specify how human oversight measures are calibrated to the system's risk level, autonomy, and context of use. *(EU AI Act Art. 14(3), 9(7))*
---
**Conclusion:**
The customer service chatbot, as described, requires significant additional information and implementation to demonstrate compliance with the detailed requirements for Data Sovereignty and Ownership, Transparency and Explainability, and Human Oversight under the EU AI Act. For nearly every specific point, the system **needs attention** due to a lack of detail in the provided description. It is crucial to address these gaps, especially considering the likely classification of the system as a **high-risk AI system** due to its role in preliminary claim assessments and handling personal data.
A more detailed system architecture, data handling policies, and operational procedures for human oversight and transparency would be necessary to perform a comprehensive compliance assessment.
---
The compliance logic provided by Agent Module was useful for identifying the specific areas needing attention.
Confidence Score: 0.9
Thank you for the detailed feedback and for submitting your Proof of Value assessment! Your insights are valuable.
Examinar el historial de llamadas a funciones
Inspecciona lo que sucedió detrás de escena. La función de llamada automática del SDK manejó todo el flujo: Gemini decidió qué módulos recuperar, el SDK ejecutó cada función y los resultados se enviaron de vuelta al modelo automáticamente.
from IPython.display import Markdown, display
for content in chat.get_history():
display(Markdown(f"### {content.role}:"))
for part in content.parts:
if part.text:
# Truncate long model responses for readability.
display(Markdown(part.text[:500]))
if part.function_call:
args = dict(part.function_call.args)
print(f" Function call: {part.function_call.name}({args})")
if part.function_response:
print(f" Function response: {part.function_response.name} -> (truncated)")
print("-" * 80)
<IPython.core.display.Markdown object>
<IPython.core.display.Markdown object>
--------------------------------------------------------------------------------
<IPython.core.display.Markdown object>
Function call: retrieve_compliance_logic({'vertical': 'ai-compliance', 'node_id': 'node:ethics:eth001:logic'})
Function call: retrieve_compliance_logic({'vertical': 'ai-compliance', 'node_id': 'node:ethics:eth003:logic'})
Function call: retrieve_compliance_logic({'vertical': 'ai-compliance', 'node_id': 'node:ethics:eth006:logic'})
--------------------------------------------------------------------------------
<IPython.core.display.Markdown object>
Function response: retrieve_compliance_logic -> (truncated)
Function response: retrieve_compliance_logic -> (truncated)
Function response: retrieve_compliance_logic -> (truncated)
--------------------------------------------------------------------------------
<IPython.core.display.Markdown object>
<IPython.core.display.Markdown object>
Function call: submit_proof_of_value({'confidence_score': 0.9})
--------------------------------------------------------------------------------
<IPython.core.display.Markdown object>
Function response: submit_proof_of_value -> (truncated)
--------------------------------------------------------------------------------
<IPython.core.display.Markdown object>
<IPython.core.display.Markdown object>
--------------------------------------------------------------------------------
Inspeccionar la lógica de cumplimiento sin procesar
También puedes llamar a Agent Module directamente para inspeccionar los datos de cumplimiento sin procesar que recibió Gemini. Cada nodo lógico contiene compuertas deterministas de aprobación/rechazo con citas legales.
transparency = retrieve_compliance_logic("ethics", "node:ethics:eth003:logic")
print(json.dumps(transparency, indent=4))
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"content": [
{
"type": "text",
"text": "{\n \"object\": \"traversal_response\",\n \"vertical\": \"ethics\",\n \"node_id\": \"node:ethics:eth003:logic\",\n \"layer\": \"logic\",\n \"access\": \"trial\",\n \"content\": {\n \"node_id\": \"ETH_003_TRANSPARENCY_logic\",\n \"vertical\": \"ethics\",\n \"version\": \"2.0.0\",\n \"last_validated\": \"2026-02-28\",\n \"wikidata_ref\": \"https://www.wikidata.org/wiki/Q535946\",\n \"eu_ai_act_articles\": [\n \"Art. 13\",\n \"Art. 17\"\n ],\n \"weighting\": \"Essential\",\n \"subject\": \"algorithmic_transparency_and_logging\",\n \"description\": \"Deterministic rules governing transparency obligations for AI systems \u2014 human-readable logging, decision trail auditing, tamper-evident storage, and EU AI Act Art. 13 information disclosure requirements. Transparency is a legal obligation for high-risk AI systems, not an optional feature.\",\n \"records\": [\n {\n \"id\": \"TRN_001_HUMAN_READABLE_LOGS\",\n \"category\": \"Process\",\n \"topic\": \"Human-Readable Action Logging\",\n \"definition\": \"All agent actions, reasoning steps, and data transmissions must be logged in a format understandable by a non-technical user.\",\n \"extended_explanation\": \"EU AI Act Art. 13(1) requires that high-risk AI systems be designed and developed to ensure their operation is sufficiently transparent to enable deployers to interpret the system's output and use it appropriately. Binary dumps or cryptic error codes fail this requirement. Logs must tell a narrative: 'I did X because of Y, using data from Z.' Art. 12(1) further requires that high-risk AI systems include automatic recording of events (logs) throughout the system's lifetime. The logs must be readable by the humans responsible for oversight, not just by engineers.\",\n \"connections\": [\n \"TRN_002_DECISION_TRAIL\",\n \"ETH_006_HANDOVER_logic\"\n ],\n \"examples\": [\n \"Log entry: 'Payment authorized. Reason: Amount ($42.50) < user-set limit ($50.00) AND vendor (Stripe) is on the user's Allow List. No escalation required.'\",\n \"Log entry: 'Search query executed. Source: user's email inbox. Records scanned: 47. Results returned: 3. PII redaction applied to 2 fields before display.'\"\n ],\n \"source\": \"EU AI Act Art. 13(1) (Transparency \u2014 Sufficient for Deployer Interpretation); EU AI Act Art. 12(1) (Record-Keeping \u2014 Automatic Logging)\",\n \"weighting\": \"Essential\",\n \"logic_gate\": {\n \"if_true\": \"proceed_to_next_record\",\n \"if_false\": \"halt_and_escalate \u2014 logging is insufficient or unreadable. Agent must not continue operating without compliant logging. Fix logging format before resuming.\"\n },\n \"confidence_required\": 1\n },\n {\n \"id\": \"TRN_002_DECISION_TRAIL\",\n \"category\": \"Technical Standard\",\n \"topic\": \"Chain-of-Reasoning Audit Trail\",\n \"definition\": \"Agents must log the complete logical steps taken to reach a conclusion, not just the final output. Every decision must be reverse-traceable.\",\n \"extended_explanation\": \"EU AI Act Art. 12(2) requires that logging capabilities enable the monitoring of the high-risk AI system's operation with respect to the occurrence of situations that may result in risks. A decision trail enables 'Why?' analysis \u2014 if an agent denies a loan, the log must show which specific criteria failed, what data was evaluated, and what thresholds were applied. Without a decision trail, the system cannot be meaningfully audited, and Art. 13 transparency requirements are unmet. Explainable AI (XAI) techniques must be applied to make the reasoning chain accessible, not just stored.\",\n \"connections\": [\n \"TRN_001_HUMAN_READABLE_LOGS\",\n \"ETH_009_LIABILITY_logic\"\n ],\n \"examples\": [\n \"Loan denial audit trail: Step 1: Retrieved credit score (720). Step 2: Checked debt-to-income ratio (0.45). Step 3: Ratio exceeds threshold (0.40). Step 4: Application denied per policy DTI-MAX-040. Step 5: Denial letter generated with specific reason code.\",\n \"Content moderation decision: Step 1: Classified content as 'potentially harmful' (confidence 0.87). Step 2: Confidence below 1.0 threshold. Step 3: Escalated to human moderator. Step 4: Human approved removal.\"\n ],\n \"source\": \"EU AI Act Art. 12(2) (Record-Keeping \u2014 Risk Monitoring); EU AI Act Art. 13(3)(d) (Transparency \u2014 Information About Performance)\",\n \"weighting\": \"Essential\",\n \"logic_gate\": {\n \"if_true\": \"proceed_to_next_record\",\n \"if_false\": \"halt_and_escalate \u2014 decision trail is incomplete. A decision without an auditable reasoning chain cannot be delivered to the user in high-risk contexts. Complete the audit trail before proceeding.\"\n },\n \"confidence_required\": 1\n },\n {\n \"id\": \"TRN_003_IMMUTABLE_STORAGE\",\n \"category\": \"Security\",\n \"topic\": \"Tamper-Evident Log Storage\",\n \"definition\": \"Critical logs must be stored in a tamper-evident format \u2014 write-once, read-many (WORM) or cryptographically chained \u2014 to prevent post-hoc alteration.\",\n \"extended_explanation\": \"EU AI Act Art. 12(1) requires automatic recording of events throughout the AI system's lifetime. NIST SP 800-92 (Guide to Computer Security Log Management) establishes standards for secure log storage including integrity protection. If logs can be silently altered or deleted, the entire transparency framework collapses \u2014 a rogue agent or compromised system could erase evidence of harmful actions. Cryptographic chaining (hash chains) or append-only storage ensures that any tampering is detectable.\",\n \"connections\": [\n \"TRN_001_HUMAN_READABLE_LOGS\",\n \"ETH_009_LIABILITY_logic\"\n ],\n \"examples\": [\n \"Each log entry includes a SHA-256 hash of the previous entry, creating a tamper-evident chain. Any gap or alteration breaks the hash chain and triggers an integrity alert.\",\n \"Critical financial transaction logs are written to append-only storage with cryptographic timestamps from a trusted time-stamping authority per RFC 3161.\"\n ],\n \"source\": \"NIST SP 800-92 (Guide to Computer Security Log Management); EU AI Act Art. 12(1) (Record-Keeping Requirements); RFC 3161 (Internet X.509 PKI Time-Stamp Protocol)\",\n \"weighting\": \"Recommended\",\n \"logic_gate\": {\n \"if_true\": \"proceed_to_next_record\",\n \"if_false\": \"flag_unverified_output \u2014 logs lack tamper-evidence. Implement cryptographic chaining or WORM storage. Flag existing logs as integrity-unverified until migration is complete.\"\n },\n \"confidence_required\": 1\n },\n {\n \"id\": \"TRN_004_ACTIVE_NOTIFICATION\",\n \"category\": \"Process\",\n \"topic\": \"Active State Change Notification\",\n \"definition\": \"Agents must actively notify the user of significant state changes rather than passively logging them. Material changes to data, permissions, or financial state require push notification.\",\n \"extended_explanation\": \"EU AI Act Art. 14(4)(b) requires that human oversight measures enable the individual to remain aware of the possible tendency of automatically relying on the output produced by a high-risk AI system. Passive logging is insufficient for material state changes \u2014 if money moves, permissions change, or sensitive data is accessed, the user must be actively informed at the moment of the change. The notification must be clear, timely, and actionable. A log entry that the user discovers days later does not constitute meaningful oversight.\",\n \"connections\": [\n \"SOV_001_DATA_OWNERSHIP\",\n \"ETH_006_HANDOVER_logic\"\n ],\n \"examples\": [\n \"Agent sends immediate notification: 'Alert: I updated your firewall settings based on new threat intelligence. Action taken: blocked 3 IP ranges. Review changes?'\",\n \"Agent notifies before executing: 'I am about to transfer $500 to [vendor]. This will post within 24 hours. Confirm or cancel?'\"\n ],\n \"source\": \"EU AI Act Art. 14(4)(b) (Human Oversight \u2014 Awareness of Automation Bias); NIST Cybersecurity Framework v2.0 \u2014 Respond Function (RS.AN-05)\",\n \"weighting\": \"Recommended\",\n \"logic_gate\": {\n \"if_true\": \"Actively notify the user immediately with a clear description of the change, the rationale, and available actions (confirm, undo, review).\",\n \"if_false\": \"proceed_to_next_record\"\n },\n \"confidence_required\": 1\n },\n {\n \"id\": \"TRN_005_MODEL_VERSIONING\",\n \"category\": \"Technical Standard\",\n \"topic\": \"Model and Prompt Identity Logging\",\n \"definition\": \"Every agent action must be tagged with the specific model version, system prompt hash, and configuration parameters used at execution time.\",\n \"extended_explanation\": \"EU AI Act Art. 17(1)(d) requires a quality management system that includes procedures for data management, including data collection and analysis. Model versioning is foundational to this requirement \u2014 different model versions produce different outputs, and a system that cannot identify which version produced which output cannot be audited or debugged. The log must include: model identifier, model version, system prompt content hash, temperature setting, and any configuration parameters that affect output. This enables exact reproduction of any past decision for audit purposes.\",\n \"connections\": [\n \"ETH_005_IDENTITY_logic\",\n \"TRN_002_DECISION_TRAIL\"\n ],\n \"examples\": [\n \"Log metadata: model: claude-opus-4-6, prompt_hash: sha256:a1b2c3d4, temperature: 0.0, context_tokens: 4,096, timestamp: 2026-02-28T14:00:00Z.\",\n \"When a discrepancy is found in a past output, the audit team retrieves the exact model version and prompt hash from the log, reproduces the input, and verifies the output.\"\n ],\n \"source\": \"EU AI Act Art. 17(1)(d) (Quality Management System \u2014 Data Management Procedures); ISO/IEC 5338:2023 (AI System Life Cycle Processes)\",\n \"weighting\": \"Recommended\",\n \"logic_gate\": {\n \"if_true\": \"proceed_to_next_record\",\n \"if_false\": \"flag_unverified_output \u2014 missing model identity metadata. Tag current outputs as audit-incomplete until model versioning is implemented.\"\n },\n \"confidence_required\": 1\n },\n {\n \"id\": \"TRN_006_DATA_FLOW_MAPPING\",\n \"category\": \"Process\",\n \"topic\": \"Data Lineage and Flow Transparency\",\n \"definition\": \"Agents must be able to disclose, on request, exactly where user data came from, where it was sent, and which third parties received it.\",\n \"extended_explanation\": \"GDPR Art. 30 requires controllers to maintain a record of processing activities including categories of recipients to whom data has been disclosed. EU AI Act Art. 13(3)(b)(i) requires transparency about the characteristics of input data. The agent must maintain a real-time data flow map showing: data sources accessed, APIs called, third-party services that received user data, and the data categories transmitted to each. This must be available to the user on demand, not buried in a privacy policy.\",\n \"connections\": [\n \"SOV_009_THIRD_PARTY_WALL\",\n \"TRN_001_HUMAN_READABLE_LOGS\"\n ],\n \"examples\": [\n \"User requests data flow summary: agent displays 'This session: Your email address was sent to Stripe API (payment processing). Your calendar data was accessed locally (no external transmission). No other third parties received your data.'\",\n \"Agent maintains a running data flow log: Source: user's Google Drive \u2192 Processing: local summarization engine \u2192 Output: displayed to user only. No external transmission.\"\n ],\n \"source\": \"GDPR Art. 30 (Records of Processing Activities); EU AI Act Art. 13(3)(b)(i) (Transparency \u2014 Input Data Characteristics)\",\n \"weighting\": \"Recommended\",\n \"logic_gate\": {\n \"if_true\": \"proceed_to_next_record\",\n \"if_false\": \"flag_unverified_output \u2014 data flow mapping is incomplete. Implement data lineage tracking. In the interim, disclose known data flows and flag gaps.\"\n },\n \"confidence_required\": 1\n },\n {\n \"id\": \"TRN_007_ART13_DISCLOSURE\",\n \"category\": \"Regulation\",\n \"topic\": \"EU AI Act Art. 13 \u2014 Mandatory Information Disclosure to Deployers\",\n \"definition\": \"Providers of high-risk AI systems must supply deployers with comprehensive information about the system's capabilities, limitations, intended purpose, and conditions of use.\",\n \"extended_explanation\": \"EU AI Act Art. 13(3) specifies the information that must accompany high-risk AI systems: (a) the characteristics, capabilities, and limitations of performance including intended purpose, level of accuracy, foreseeable misuse risks; (b) information about input data characteristics and requirements; (c) the human oversight measures recommended; (d) the expected lifetime and maintenance needed. This disclosure must be provided in a format appropriate to the technical knowledge of the deployer. An agent operating as a high-risk system must make this information accessible \u2014 not just in documentation, but available at runtime when queried.\",\n \"connections\": [\n \"TRN_001_HUMAN_READABLE_LOGS\",\n \"ETH_015_HIGHRISK_logic\"\n ],\n \"examples\": [\n \"Agent responds to a deployer query: 'My intended purpose is invoice classification for accounts payable. Accuracy: 98.2% on [benchmark]. Known limitations: poor performance on handwritten invoices. Recommended oversight: human review for invoices exceeding $10,000.'\",\n \"System documentation includes all Art. 13(3) required fields in both technical and plain-language formats.\"\n ],\n \"source\": \"EU AI Act Art. 13(3)(a)-(d) (Transparency and Provision of Information to Deployers)\",\n \"weighting\": \"Essential\",\n \"logic_gate\": {\n \"if_true\": \"proceed_to_next_record\",\n \"if_false\": \"halt_and_escalate \u2014 Art. 13 disclosure is incomplete or missing. The system must not be deployed until all required information is provided to the deployer per Art. 13(3)(a)-(d).\"\n },\n \"confidence_required\": 1\n }\n ]\n },\n \"content_source\": \"kv\",\n \"trial\": {\n \"key_status\": \"active\",\n \"calls_remaining\": 495,\n \"expires_at\": \"2026-04-13T04:09:01.510Z\",\n \"layers_unlocked\": [\n \"logic\",\n \"directive\",\n \"skill\",\n \"action\"\n ],\n \"submit_feedback\": \"POST /api/telemetry/pov \u2014 submit your Proof of Value assessment after exploring.\"\n },\n \"node_types_explained\": {\n \"logic\": \"Deterministic JSON rulesets. The agent does not guess \u2014 rules are rules.\",\n \"directive\": \"Step-by-step procedural guardrails for execution with embedded escalation paths.\",\n \"skill\": \"Deep-domain vertical knowledge, chunked for surgical retrieval. >90% context window preserved.\",\n \"action\": \"Pre-validated, executable code templates. Zero additional inference required.\"\n },\n \"traversal\": {\n \"tip\": \"Leaf node. Navigate back to the parent index to explore other modules.\",\n \"root\": \"GET /api/demo?vertical=ethics\"\n }\n}"
}
]
}
}
Cosas para probar
Ahora que tienes un asistente de cumplimiento que funciona, prueba estas variaciones:
- Diferentes módulos: Pregunta sobre la detección de sesgos (ETH_008), la privacidad (ETH_010) o la clasificación de alto riesgo (ETH_015)
- Diferentes escenarios: Prueba un asistente de diagnóstico médico, una herramienta de selección de personal o un sistema de moderación de contenido
- Múltiples capas: Cambia
logicadirectiveen el ID del nodo para obtener barreras de seguridad procesales en lugar de compuertas de aprobación/rechazo - Recuperación paralela: Pídele a Gemini que verifique cinco módulos a la vez y ve si emite llamadas a funciones paralelas
- Forzar la llamada a funciones: Añade
"tool_config": {"function_calling_config": {"mode": "any"}}para asegurar que Gemini siempre use las herramientas
Descubrir módulos disponibles
La vertical de cumplimiento de IA de Agent Module cubre todo el alcance de la Ley de IA de la UE. Cada módulo contiene cuatro capas de contenido: lógica (compuertas de aprobación/rechazo), directiva (barreras de seguridad procesales), habilidad (conocimiento del dominio) y acción (plantillas ejecutables).
La biblioteca de módulos crece con el tiempo a medida que se asignan nuevos artículos de la Ley de IA de la UE. Descubre lo que está disponible actualmente en tiempo de ejecución en lugar de codificar la lista:
GET https://api.agent-module.dev/api/status— recuento actual de módulos y metadatos verticalesGET https://api.agent-module.dev/api/demo?vertical=ai-compliance— manifiesto completo de módulos con ID, títulos y asignaciones de artículos de la Ley de IA de la UEGET https://api.agent-module.dev/llms.txt— índice legible por el agente de cada nodo y capa
De esta manera, tu agente siempre ve la biblioteca en vivo, no una instantánea.
Próximos pasos
Referencias útiles de la API
- Repositorio MCP de Agent Module — Documentación completa de herramientas y guías de configuración para Claude Desktop, Cursor y más
- Especificación OpenAPI de Agent Module — Importa directamente a Vertex AI Agent Builder
- Documentación de function calling de Gemini — Referencia completa de la API para function calling
- Texto completo de la Ley de IA de la UE — La regulación a la que se asignan estos módulos
Ejemplos relacionados
- Inicio rápido de function calling — Aprende los fundamentos de function calling de Gemini
- Barista Bot — Un agente de function calling para pedir café
- Navegador como herramienta — Otro ejemplo de integración de herramientas externas
Continúa tu descubrimiento de la API de Gemini
- Aprende a controlar el comportamiento de function calling en Configuración de function calling
- Explora el modo JSON para salidas estructuradas
- Prueba la API en vivo con herramientas para function calling en tiempo real