---
title: "Connect Riza to AI Agents: Orchestrate Secure Runtimes and Secrets"
slug: connect-riza-to-ai-agents-orchestrate-secure-runtimes-and-secrets
date: 2026-06-19
author: Uday Gajavalli
categories: ["AI & Agents"]
excerpt: "Learn how to connect Riza to AI agents using Truto's tool-calling API. Orchestrate secure runtimes, manage secrets, and execute sandboxed code natively."
tldr: "Connect Riza to AI agents to safely execute sandboxed code. This guide covers how to fetch Riza tools via Truto, handle custom runtimes, manage secrets, and bind Riza capabilities natively to frameworks like LangChain."
canonical: https://truto.one/blog/connect-riza-to-ai-agents-orchestrate-secure-runtimes-and-secrets/
---

# Connect Riza to AI Agents: Orchestrate Secure Runtimes and Secrets


You want to connect Riza to your AI agents so they can dynamically generate, compile, and execute code in secure, isolated sandboxes. Instead of risking arbitrary code execution on your local host or manually provisioning ephemeral Docker containers, you can use Riza to give your LLMs a secure execution environment. If your team uses ChatGPT, check out our guide on [connecting Riza to ChatGPT](https://truto.one/connect-riza-to-chatgpt-run-sandboxed-code-and-manage-tools/), or if you prefer Anthropic's ecosystem, read about [connecting Riza to Claude](https://truto.one/connect-riza-to-claude-automate-secure-custom-tool-execution/). 

For developers building custom autonomous workflows, you need a programmatic way to fetch these sandbox controls and bind them to your agent framework. This guide breaks down exactly how to use Truto's `/tools` endpoint and SDK to generate AI-ready tools for Riza, bind them natively to an LLM using frameworks like LangChain, LangGraph, or the Vercel AI SDK, and orchestrate complex code-execution workflows autonomously. For a deeper look at the architecture behind this tool-calling approach, refer to our research on [architecting AI agents and the SaaS integration bottleneck](https://truto.one/architecting-ai-agents-langgraph-langchain-and-the-saas-integration-bottleneck/).

## The Engineering Reality of Custom Riza Connectors

Building an AI agent that writes code is trivial; building an agent that can safely *execute* and iterate on that code against third-party APIs is an engineering headache. If you decide to build a custom Riza integration layer, you own the entire API lifecycle. You must write and maintain JSON schemas for every execution endpoint, handle authentication lifecycles, and teach the LLM how to parse Riza's specific response structures.

The Riza API introduces several domain-specific integration challenges that break standard LLM assumptions.

### Execution State vs. HTTP State
When an AI agent interacts with a standard SaaS API, an HTTP `200 OK` usually means the operation was successful. With Riza, an HTTP `200 OK` on a code execution endpoint simply means the API successfully received and ran the payload. The actual result of the script is nested inside the response payload as an `exit_code`. 

An LLM cannot natively assume success based on the network layer. It must be explicitly instructed to inspect the `exit_code`, parse `stdout` for the expected output, and, crucially, parse `stderr` if the script failed. If you hand-code these tools, you are responsible for mapping this nested error logic into the tool schema so the agent knows how to self-correct.

### Ephemeral Runtimes and Dependency Injection
LLMs love to import external libraries. If an agent writes a Python script using `pandas` or `requests`, it cannot simply execute that code in a bare-metal environment. Riza enforces strict environment control via Runtimes.

To successfully execute complex code, the agent must first understand that it needs to query existing runtimes or create a new runtime with a specific `manifest_file` (like a `requirements.txt`). This requires a multi-step orchestration process: analyze dependencies -> create runtime -> wait for runtime to be ready -> execute code using that runtime. Truto normalizes this by providing rich tool descriptions that guide the LLM through this dependency graph.

### Strict Rate Limit Boundaries
When orchestrating agents that write and test code in loops, you will inevitably hit rate limits. It is critical to understand how Truto handles these boundaries. 

Truto does not retry, throttle, or apply backoff on rate limit errors. When the upstream Riza API returns an HTTP `429 Too Many Requests`, Truto immediately passes that error back to the caller. However, Truto normalizes the upstream rate limit information into standardized HTTP headers (`ratelimit-limit`, `ratelimit-remaining`, `ratelimit-reset`) per the IETF specification. The caller (your agent framework) is strictly responsible for inspecting these headers and implementing its own retry or backoff logic. Do not rely on the infrastructure layer to absorb these errors.

## Riza Tool Calling: The Hero Tools

Truto maps Riza's API into a REST-based Proxy API architecture. We expose the Methods defined on Riza's Resources directly to the `/integrated-account/<id>/tools` endpoint, returning normalized descriptions and JSON schemas that LLMs natively understand. 

Here are the highest-leverage hero tools for Riza AI Agents integration. 

### Create a Riza Code Execution
This is the core execution primitive. It allows the agent to submit a raw script in a specified language (like Python, TypeScript, or Go) and receive the execution result. The agent uses this for ad-hoc processing, data transformation, or testing logic before saving it as a permanent tool.

**Usage Note:** The agent must be instructed to read the `stderr` and `exit_code` returned by this tool. If the `exit_code` is non-zero, the agent should automatically rewrite the code and call this tool again.

> "I have a raw text block of poorly formatted CSV data. Write a Python script to parse it, clean the trailing whitespaces, and calculate the sum of the third column. Execute the script in Riza and tell me the final sum."

### Create a Riza Runtime
When an agent needs to execute code that relies on external packages, it must provision a custom runtime. This tool allows the agent to define a `manifest_file` specifying dependencies and the target language engine.

**Usage Note:** Creating a runtime is not instantaneous. Agents should be prompted to create the runtime and then verify its status before attempting to execute code against it.

> "I need to scrape a website and parse the HTML. First, create a new Python runtime in Riza with 'beautifulsoup4' and 'requests' in the manifest. Let me know when the runtime ID is ready so we can run the scraper."

### Create a Riza Secret
Sandboxes are isolated by design. If the agent writes code that needs to query your internal database or a third-party API, it cannot hardcode the API key in the script. It must use this tool to securely inject the secret into the Riza project environment.

**Usage Note:** Secrets are mapped to execution environments at runtime. The agent should create the secret first, then reference it via standard environment variable calls (e.g., `os.environ.get('MY_SECRET')`) in its subsequent code execution.

> "We need to fetch data from the Stripe API. Take this API key, create a Riza secret named 'STRIPE_SECRET_KEY', and then write a Node.js script that uses this secret to fetch our latest 5 charges."

### Create a Riza Tool
Once an agent has perfected a script through trial and error, it can codify that logic into a persistent Riza Tool. This essentially allows the agent to build its own API endpoints on the fly, complete with strict input schemas.

**Usage Note:** The agent must provide a highly detailed `input_schema` (JSON Schema) when creating the tool. This ensures future executions of the tool are strictly typed and safe.

> "The data transformation script you just wrote worked perfectly. Now, save it permanently by creating a new Riza tool. Name it 'clean_sales_data' and define the input schema to accept a raw string payload."

### Execute a Riza Tool
This tool allows the agent to run previously saved Riza Tools by their ID. Instead of passing raw code, the agent simply passes a JSON payload that matches the tool's defined input schema.

**Usage Note:** This is the most efficient way to run recurring tasks. It bypasses the need for the agent to rewrite the logic, saving massive amounts of context window and token costs.

> "Run the 'clean_sales_data' tool using ID 'tool_8f7d9a' on the following text block, and return the formatted JSON array it outputs."

### List All Riza Executions
Debugging autonomous agents requires observability. This tool allows the agent (or a separate supervisor agent) to list historical executions, filter them by non-zero exit codes, and analyze failures.

**Usage Note:** Agents can use the `only_non_zero_exit_codes` filter to specifically hunt for failed tasks across the project, making this invaluable for automated remediation loops.

> "Look up all recent executions in Riza that failed with a non-zero exit code. Give me a summary of the error messages so we can figure out what dependencies are breaking."

*Note: This is a curated list of high-leverage tools. For the complete inventory of available Riza endpoints, schema definitions, and parameters, visit the [Riza integration page](https://truto.one/integrations/detail/riza) or read our guide on [building MCP servers for AI agents](https://truto.one/the-hands-on-guide-to-building-mcp-servers-for-ai-agents-2026/).* 

## Workflows in Action

Giving an AI agent isolated code execution changes the paradigm of integration. Instead of the agent trying to transform data in its own context window (which leads to hallucination and token limits), the agent delegates the heavy lifting to deterministic code. Here is how these tools orchestrate real-world operations.

### 1. The Autonomous Data Extraction and Parsing Loop
An agent is asked to retrieve unstructured data from an external source, parse it securely, and return the structured result.

> "Go to this public data repository URL, download the raw logs, extract only the IPs that hit a 500 error, and give me the list. Use a Python script to do this accurately."

1. The agent calls `create_a_riza_code_execution` containing a Python script utilizing the standard `urllib` library to fetch the URL, parse the text, and print the resulting IPs.
2. The Riza API returns the payload. The agent reads the `stdout` field from the tool response.
3. The agent formats the output and presents the clean IP list to the user.

### 2. Custom Environment Provisioning for API Interaction
A user wants the agent to interact with a third-party API that requires specific SDKs, without exposing the API keys to the LLM's chat interface.

> "Here is a temporary GitHub token. Create a secure runtime that includes the PyGithub library, save the token as a secret, and run a script to list all open PRs in our core repo."

1. The agent calls `create_a_riza_secret` with the provided token and the name `GITHUB_TEMP_TOKEN`.
2. The agent calls `create_a_riza_runtime` specifying Python and a `manifest_file` containing `PyGithub==2.3.0`.
3. The agent calls `create_a_riza_code_execution` with a script that initializes the PyGithub client using `os.environ.get('GITHUB_TEMP_TOKEN')` and fetches the PRs.
4. The agent reads the `stdout`, parsing the list of PRs to the user.

## Building Multi-Step Workflows

To build these workflows in production, you need to connect Truto's tool output natively to your agent framework. If you are managing multiple distinct agents, you may need to focus on [handling auth and tool sharing in multi-agent frameworks via MCP](https://truto.one/handling-auth-tool-sharing-in-multi-agent-frameworks-via-mcp/) to simplify permissions. Truto provides the `truto-langchainjs-toolset` to abstract the boilerplate, allowing you to fetch tools and bind them directly to the model.

Here is a conceptual architectural flow of how the agent interacts with Truto and Riza.

```mermaid
sequenceDiagram
    participant App as "Your Application"
    participant LLM as "LLM (OpenAI/Anthropic)"
    participant Truto as "Truto Proxy API"
    participant Riza as "Riza API"

    App->>Truto: GET /integrated-account/<id>/tools
    Truto-->>App: Returns JSON Schemas for Riza Tools
    App->>LLM: .bindTools(rizaTools)
    
    Note over App,LLM: User Prompt: "Run a script to parse this data"
    
    LLM-->>App: ToolCall: create_a_riza_code_execution
    App->>Truto: POST /proxy/riza/executions (with script payload)
    Truto->>Riza: Forwards normalized request
    Riza-->>Truto: HTTP 200 OK (exit_code: 1, stderr: "SyntaxError")
    Truto-->>App: Returns execution result
    App->>LLM: Returns Tool Message (Failed)
    
    Note over LLM,App: LLM analyzes stderr and self-corrects
    
    LLM-->>App: ToolCall: create_a_riza_code_execution (Fixed script)
    App->>Truto: POST /proxy/riza/executions
    Truto->>Riza: Forwards corrected request
    Riza-->>Truto: HTTP 200 OK (exit_code: 0, stdout: "Success")
    Truto-->>App: Returns execution result
    App-->>LLM: Returns Tool Message (Success)
```

### Implementing the Agent Loop in LangChain

Below is an example of how to implement this robust Riza API AI agent loop. This code uses Truto's SDK to fetch the tools, binds them to the LLM, and handles execution errors—including the strict requirement to handle HTTP 429 rate limits manually using Truto's normalized headers.

```typescript
import { ChatOpenAI } from "@langchain/openai";
import { TrutoToolManager } from "truto-langchainjs-toolset";
import { HumanMessage } from "@langchain/core/messages";

async function runRizaAgent() {
  // 1. Initialize Truto Tool Manager with the specific Riza integrated account ID
  const trutoManager = new TrutoToolManager({
    apiKey: process.env.TRUTO_API_KEY,
    accountId: "riza_account_12345",
  });

  // 2. Fetch Riza tools via Truto's /tools endpoint
  const rizaTools = await trutoManager.getTools();

  // 3. Initialize the LLM and bind the tools
  const llm = new ChatOpenAI({
    modelName: "gpt-4o",
    temperature: 0,
  }).bindTools(rizaTools);

  // 4. Create the execution loop
  const messages = [new HumanMessage("Write a Python script to print the first 10 Fibonacci numbers and execute it in Riza.")];

  let isComplete = false;

  while (!isComplete) {
    try {
      const response = await llm.invoke(messages);
      messages.push(response);

      if (response.tool_calls && response.tool_calls.length > 0) {
        for (const toolCall of response.tool_calls) {
          console.log(`Executing Tool: ${toolCall.name}`);
          
          // Execute the tool call using Truto's normalized Proxy API
          const toolResult = await trutoManager.executeTool(toolCall);
          messages.push(toolResult);

          // Inspect execution payload for Riza-specific failure states
          const parsedContent = JSON.parse(toolResult.content);
          if (parsedContent.exit_code && parsedContent.exit_code !== 0) {
             console.warn(`Riza Execution Failed: ${parsedContent.stderr}`);
             // The LLM will automatically see this in the message history 
             // and attempt to self-correct in the next loop iteration.
          }
        }
      } else {
        console.log("Final Answer:", response.content);
        isComplete = true;
      }
    } catch (error) {
      // 5. Handle Rate Limits explicitly
      if (error.status === 429) {
        const resetTime = error.headers['ratelimit-reset'];
        console.error(`Rate limit hit. Must wait until ${resetTime} before retrying.`);
        // Implement custom delay logic here. Truto does NOT backoff automatically.
        await new Promise(resolve => setTimeout(resolve, 5000)); 
      } else {
        console.error("Workflow failed:", error);
        break;
      }
    }
  }
}

runRizaAgent();
```

### The Value of Tool Normalization

By leveraging Truto's Proxy APIs, your agent framework receives normalized input schemas for complex operations. You do not have to write manual serializers to handle Riza's internal JSON requirements for `manifest_file` structures or base64 encode payloads arbitrarily. 

Truto dynamically parses the Riza integration definition and returns clean JSON Schema objects to your LLM. When you update a tool description in the Truto UI to give the LLM better instructions (e.g., *"Always import standard libraries first"*), the `/tools` endpoint updates automatically. You never have to redeploy your Node.js application or manually patch an OpenAPI spec.

## Final Thoughts

Connecting Riza to AI Agents unlocks deterministic capabilities for stochastic models. When an LLM can write a script, provision the exact dependencies it needs, inject secure credentials, and execute the code in an isolated environment, it ceases to be a simple text generator and becomes an autonomous software engineer.

By relying on Truto to generate the tool definitions, handle authentication, and normalize upstream behavior, your engineering team can focus on agent orchestration and prompt strategy rather than building and maintaining custom Riza API wrappers.

> Stop hand-coding API wrappers for your AI agents. Learn how Truto's `/tools` endpoint can securely connect your LLMs to 100+ B2B APIs in minutes.
>
> [Talk to us](https://cal.com/truto/partner-with-truto)
