Run RSI tuning with Local Gym
If your agent runs on your own test machine, in a container, or in an intranet environment and depends on internal tools, databases, or private services, you can integrate it with AgentLoop by using Local Gym and let AgentLoop automatically run multi-round evaluation and self-improvement tuning (RSI) on the real agent. This topic describes the complete integration process, how to configure the two local functions, and how to troubleshoot common issues.
How it works
One tuning loop involves four entities and two actions that you must provide. The four entities are the AgentLoop server, Gym Client, the asset directory, and your agent. The two actions are the apply function, which syncs a candidate version to the agent environment and makes it take effect, and the run function, which calls the agent to answer a single evaluation question and passes through the trace identifier.
Before you start tuning, copy the prompt or skill that you want to tune from the agent into a separate asset directory so that tuning is decoupled from your business code repository. Gym Client then drives each round automatically:
Outbound HTTPS communication: Gym Client proactively connects to the AgentLoop server, pulls the candidate version and evaluation questions for the round, and reports answers and trace IDs after evaluation.
Reading and writing the asset copy: Gym Client reads the initial assets, writes each new candidate to the asset directory, and restores the initial version when the session ends.
apply function: Syncs the latest version in the asset directory back to your agent environment and makes it take effect, for example by copying files back to the agent directory or triggering a hot reload. The same synchronization is performed when the baseline is restored after tuning.
run function: Passes a single evaluation question and the trace identifier to your agent, obtains the real answer, and returns it to Gym Client.
Reporting execution traces: Your agent uses the passed-through trace identifier to report execution traces directly to the AgentLoop server. The server combines traces and answers, scores them with the evaluator, and generates a better version for the next round.
Prerequisites
Test environment: A Linux test machine (x86_64 or arm64) that can run your agent, uses a non-root regular account, and can access the Internet over HTTPS (port 443).
Trace reporting enabled: Your agent is already connected to the observability pipeline of the current AgentSpace. Self-developed services are connected with the OpenTelemetry SDK; AI coding agents such as Qoder, Claude Code, and Codex have LoongSuite Pilot installed. The agent must be able to report execution traces based on the traceparent that it receives.
Console resources ready: The current AgentSpace already has a training set (15 to 50 typical questions are recommended, and a separate validation set is optional) and at least one agent evaluator.
Step 1: Prepare the tuning directory and install Gym Client
On the test machine, create a dedicated directory for tuning that is separate from the business code repository, and copy the prompt or skill that you want to tune into it:
# 1. Create a dedicated tuning directory (example path; customize as needed)
mkdir -p ~/rsi-workspace/prompts ~/rsi-workspace/skills
# 2. Copy the prompt and/or skill to tune (prepare either or both as needed)
# - Prompts go to prompts/*.md
# - Skills go to skills/<skill-name>/SKILL.md
cp /path/to/your-agent/prompts/system.md ~/rsi-workspace/prompts/system.md
# cp -r /path/to/your-agent/skills/my-skill ~/rsi-workspace/skills/my-skillLog on to the AgentLoop console and obtain the installation command:
Go to the Optimization tasks page, choose Create optimization task, and select RSI iterative optimization as the task type.
In the Optimization Target & Runtime section, set Runtime type to Local Gym and click Connect Gym.
In the Connect Local Gym drawer, confirm the Gym Hub endpoint and AgentSpace, enter a connection name as needed (for example, order-support-gym), and click Get Trace LicenseKey.
Click Copy one-click install command, and then paste and run the command as a non-root regular account in the ~/rsi-workspace directory on the test machine.
After the command finishes, an ./agentloop-gym/ folder is created in the current directory and local connection registration is complete. If the installation encounters network jitter or an incorrect key, correct the issue and rerun the same command to continue registration.
The installation command contains ARMS_LICENSE_KEY. It is used only for the initial local key registration and is not written to gym.yaml or backend service configuration files. Do not paste the command into tickets, group chats, or code repositories.
If your machine uses a coding agent such as Qoder, Claude Code, Codex, or Cursor, you can also expand the first item of the Frequently Asked Questions (FAQ) section at the bottom of the connection drawer and give the connection document to the coding agent so that it completes the configuration and scripts automatically.
Step 2: Configure the asset directory and functions
Go to the client directory. All subsequent configuration edits and command-line operations are performed in the ./agentloop-gym directory:
cd ~/rsi-workspace/agentloop-gymYou need to confirm or modify three files: The asset directory configuration gym.yaml, the apply function apply_hook.sh, and the run function run_agent.py.
Confirm the asset directory (gym.yaml)
If you copied prompts/*.md or skills/<skill-name>/SKILL.md under ~/rsi-workspace in Step 1 and then ran the installation, assets.dir in gym.yaml already points to ~/rsi-workspace by default and does not need to be changed.
If you tune only prompts or only skills, place only the corresponding files; you do not need to create empty folders.
If you store the copied assets elsewhere (for example, /srv/my-rsi-assets), change assets.dir to that directory path. If the subdirectory names are not the default prompts or skills, set prompts_dir or skills_dir as needed:
assets:
dir: ".." # Points to the copied asset directory (an absolute path is also supported)
# The following two items scan prompts/*.md and skills/<skill-name>/SKILL.md by default. Set them only when the subdirectory names differ:
# prompts_dir: "my_prompts"
# skills_dir: "my_skills"Write the apply function (apply_hook.sh)
The apply function syncs the latest prompt or skill in the asset directory to your agent environment and makes it take effect, and performs the same restore when tuning ends and the baseline is restored. Key points:
When the script runs, the current directory automatically switches to the asset directory (that is, assets.dir).
Sync the files in the asset directory to the location that the agent actually reads, notify the agent to reload or restart if necessary, and return exit code 0 after confirming that the changes take effect.
To distinguish applying a new version from restoring the baseline, read the GYM_APPLY_PHASE environment variable, whose value is apply or restore.
Choose one form based on your agent type:
Example A: The agent reads files from a specified directory on each run. Copy the files from the asset directory back to the agent directory.
#!/usr/bin/env sh
set -eu
# The current directory is already the asset directory. Sync the latest assets to the agent working directory.
cp ./prompts/system.md /path/to/your-agent/prompts/system.mdExample B: The agent is a long-running HTTP or gRPC service. Sync the files first, then trigger a hot reload and confirm service health.
#!/usr/bin/env sh
set -eu
cp ./prompts/system.md /path/to/your-agent/prompts/system.md
curl -fsS -X POST http://127.0.0.1:8080/admin/reload >/dev/null
curl -fsS http://127.0.0.1:8080/healthz >/dev/nullAfter saving the script, make it executable:
chmod +x ./apply_hook.shWrite the run function (run_agent.py)
The run function receives a single input question from the evaluation set, calls your real agent, and writes the answer and trace ID to the result file. Key points:
Delete the example stub code in the run_agent() template (raise StarterStubUnconfiguredError(...)).
Read one line of JSON from stdin. input is the evaluation question field, control.traceparent is the trace identifier to pass to the agent, and control.result_file is the output path.
When calling the real agent, pass control.traceparent in a request header or environment variable, write a JSON object that contains status, actual_trace_id, and output to control.result_file, and exit with code 0.
The following is a ready-to-use reference template for an HTTP agent:
#!/usr/bin/env python3
import json
from pathlib import Path
import sys
import urllib.request
def run_agent(row: dict, traceparent: str) -> tuple[str, str]:
# Extract trace_id from traceparent (00-<32-char trace_id>-<16-char span_id>-01)
parts = traceparent.split("-")
injected_trace_id = parts[1] if len(parts) >= 2 else ""
req = urllib.request.Request(
"http://127.0.0.1:8080/chat",
data=json.dumps(row, ensure_ascii=False).encode("utf-8"),
headers={
"Content-Type": "application/json",
"traceparent": traceparent, # Pass to your agent to correlate cloud traces
},
method="POST",
)
with urllib.request.urlopen(req, timeout=120) as resp:
body = json.loads(resp.read().decode("utf-8"))
actual_trace_id = body.get("trace_id") or injected_trace_id
return actual_trace_id, body["answer"]
def main() -> int:
envelope = json.loads(sys.stdin.readline())
control = envelope["control"]
try:
actual_trace_id, answer = run_agent(envelope["input"], control["traceparent"])
result = {"status": "success", "actual_trace_id": actual_trace_id, "output": answer}
except Exception as exc:
print(f"[run_agent] {exc}", file=sys.stderr)
result = {
"status": "failed",
"actual_trace_id": "",
"error": "script_reported_failure",
"output": str(exc),
}
Path(control["result_file"]).write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8")
return 0
if __name__ == "__main__":
raise SystemExit(main())Verify both functions locally
Before starting the client, manually verify that apply_hook.sh and run_agent.py work:
# 1. Verify in the asset directory that the apply function syncs and takes effect
(cd .. && GYM_APPLY_PHASE=apply ./agentloop-gym/apply_hook.sh) && echo "apply_hook OK"
# 2. Send one test question to verify that the run function reaches the agent and returns an answer
printf '{"input":{"query":"Hello, please explain the return policy"},"control":{"traceparent":"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01","result_file":"/tmp/gym-smoke-test.json"}}\n' \
| python3 ./run_agent.py
cat /tmp/gym-smoke-test.jsonAfter /tmp/gym-smoke-test.json shows status as success and contains the agent's real answer, continue to the next step.
Step 3: Self-check and start the client
Still in the ./agentloop-gym directory, run the self-check:
./bin/gym-client doctor --config ./gym.yamlConfirm the following three points before starting the client:
The overall status is ready.
The scanned file list contains exactly the prompts or skills that you copied.
No warning states that the template stub code has not been replaced.
After confirming, start the client:
./bin/gym-client run --config ./gym.yamlIf the test machine must run unattended for a long time and restart automatically after a reboot, go to the advanced options in the Connect Local Gym drawer in the console and run ./bin/gym-client service install --config ./gym.yaml in ./agentloop-gym to register the client as a system background service.
Step 4: Configure the task in the console and start tuning
Return to the Create RSI iterative optimization task page in the console and complete the following configuration:
Select the online Gym and assets to tune: Click Refresh, select the Local Gym instance that just came online, confirm that its status is online, idle, and ready, and then select the prompts or skills to optimize.
Select the dataset and evaluator: Select the training set (required) and validation set (optional, recommended for checking generalization) in step 1 Dataset; bind an agent evaluator and field mappings in step 3 Evaluation; set the maximum number of iterations and the target score in step 4 Tuning.
Confirm the input fields passed to the agent: Go to step 2 Deploy & Run and manually check the evaluation fields sent to the local runner. Select only the actual input question columns (for example, input and query), and clear reference, expected, expected_answer, ground_truth, and other reference-answer columns so that standard answers are not sent to the agent under test. Cloud evaluators can still read reference answers from the dataset for scoring.
Save a draft and run a smoke test: Save the draft first, and then click Run Smoke Preview. If the button is unavailable, the page shows which step is missing. After you complete the configuration, click Save draft at the bottom (this saves and stays on the page). When the button becomes available, verify the full pipeline with one sample.
Start tuning: After 6/6 stages are confirmed, switch to the last step and click Save & Start Tuning to begin multi-round optimization.
Step 5: View results and merge into the code repository
During and after tuning, you can view the score trend and improvement summary for each round on the task details page.
Click Details > View diff for the best round to compare the additions and deletions between the best version and the initial version line by line, and open the trace of a single question to confirm the agent's actual behavior.
After tuning ends, your agent environment has been automatically restored to the initial version. When you are satisfied with the best result, click Download new text (which directly overwrites the target file) or Download Patch on the details page, and merge the result into the code repository through your normal code review process.
The exported patch paths are generated relative to the asset directory. If the repository path has one more prefix directory than the asset directory (for example, the asset directory contains skills/... but the repository contains .qoder/skills/...), add the --directory parameter when you apply the patch:
git apply --check --directory=<prefix-dir> candidate.patch
git apply --directory=<prefix-dir> candidate.patchTo verify at the rule level which subdirectories are scanned, run ./bin/gym-client doctor in the client directory to view the files included in this tuning run.
Example: Connect Qoder CLI to tune a skill
The following example demonstrates the complete process in a real scenario. Assume that the business repository is /srv/sql-review-demo and contains a Qoder skill to tune: /srv/sql-review-demo/.qoder/skills/sql-review/SKILL.md. The approach is to copy the assets independently, let Gym read and write the copy, and then copy it back through the apply function.
The directory relationship is as follows:
/srv/sql-review-demo/ # Business project directory (do not install Gym here)
├── .qoder/skills/sql-review/SKILL.md # Skill actually read by Qoder (synced/restored by the apply function)
└── migrations/ # Business code
/srv/qoder-rsi-workspace/ # New dedicated tuning directory
├── skills/sql-review/SKILL.md # Copy of the asset to tune, copied from the business project
└── agentloop-gym/ # Generated after the one-click installation command in Step 1
├── gym.yaml # Scans ../skills/sql-review/SKILL.md by default
├── apply_hook.sh # Copies the copy back to the business project
├── run_agent.py # Calls qodercli in /srv/sql-review-demo to answer questions
└── bin/gym-clientEnable Qoder trace reporting and upstream correlation
Go to the Integration Center page in the console, click By method, and install LoongSuite Pilot as instructed.
You must enable upstreamLink.enabled and restart Pilot. Pilot disables upstream TRACEPARENT correlation by default. If you do not enable it, Qoder execution traces are attached to another trace ID, and the cloud cannot find the traces of this invocation:
python3 -c 'import json, pathlib; p = pathlib.Path.home() / ".loongsuite-pilot/config.json"; d = json.loads(p.read_text()); d.setdefault("upstreamLink", {})["enabled"] = True; p.write_text(json.dumps(d, indent=2, ensure_ascii=False) + "\n")'
loongsuite-pilot restart
loongsuite-pilot statusCreate the tuning directory, copy the skill, and install the client
# Create a dedicated tuning directory and copy the SKILL.md to tune
mkdir -p /srv/qoder-rsi-workspace/skills/sql-review
cp /srv/sql-review-demo/.qoder/skills/sql-review/SKILL.md \
/srv/qoder-rsi-workspace/skills/sql-review/SKILL.md
# Go to the dedicated tuning directory and paste the one-click installation command generated by the console
cd /srv/qoder-rsi-workspace
# <Paste and run the one-click installation command copied from the console>Go to ./agentloop-gym, edit gym.yaml, and set the concurrency max_concurrency to 1 to prevent concurrent questions from operating on the same repository. assets.dir is already set to ".." by default and automatically scans skills/sql-review/SKILL.md, so no change is needed:
assets:
dir: ".."
functions:
apply:
command: "./apply_hook.sh"
timeout_seconds: 15
run:
interpreter: "python3"
command: "./run_agent.py"
args: []
cwd: "."
max_concurrency: 1Write apply_hook.sh and run_agent.py
apply_hook.sh copies the latest SKILL.md from the asset directory back to /srv/sql-review-demo. It syncs the corresponding version both when a new candidate is applied and when the baseline is restored at the end:
#!/usr/bin/env sh
set -eu
# When this script runs, the current directory is the asset directory (/srv/qoder-rsi-workspace)
cp ./skills/sql-review/SKILL.md /srv/sql-review-demo/.qoder/skills/sql-review/SKILL.mdrun_agent.py calls qodercli non-interactively in /srv/sql-review-demo and passes TRACEPARENT:
#!/usr/bin/env python3
import json
import os
from pathlib import Path
import subprocess
import sys
AGENT_PROJECT_DIR = "/srv/sql-review-demo"
def parse_qoder_output(stdout: str) -> str:
text = stdout.strip()
if not text:
return ""
for line in reversed(text.splitlines()):
line = line.strip()
if not line:
continue
try:
obj = json.loads(line)
except json.JSONDecodeError:
continue
if isinstance(obj, dict):
for key in ("result", "output", "content", "message", "text"):
val = obj.get(key)
if isinstance(val, str) and val.strip():
return val.strip()
return text
def run_agent(row: dict, traceparent: str) -> tuple[str, str]:
parts = traceparent.split("-")
trace_id = parts[1] if len(parts) >= 2 else ""
query = str(row.get("query") or row.get("input") or "").strip()
sql_diff = str(row.get("sql_diff") or "").strip()
prompt = f"Review the following SQL change according to the sql-review skill and give a clear conclusion:\n\n{query}"
if sql_diff:
prompt += f"\n\nSQL change:\n{sql_diff}"
env = os.environ.copy()
if traceparent:
env["TRACEPARENT"] = traceparent
env["LOONGSUITE_PILOT_SPAN_ATTRIBUTES"] = f"gen_ai.session.id=gym-{trace_id[:16]}"
cmd = [
"qodercli",
"-p",
"--output-format", "json",
"--permission-mode", "dont_ask", # If the skill needs file access or command execution, use bypass_permissions instead
"-w", AGENT_PROJECT_DIR,
prompt,
]
proc = subprocess.run(cmd, cwd=AGENT_PROJECT_DIR, env=env, capture_output=True, text=True, timeout=180)
if proc.returncode != 0:
raise RuntimeError(f"qodercli exited {proc.returncode}: {proc.stderr.strip()[:500]}")
answer = parse_qoder_output(proc.stdout)
if not answer:
raise RuntimeError("qodercli returned empty output")
return trace_id, answer
def main() -> int:
envelope = json.loads(sys.stdin.readline())
control = envelope["control"]
try:
actual_trace_id, answer = run_agent(envelope["input"], control["traceparent"])
result = {"status": "success", "actual_trace_id": actual_trace_id, "output": answer}
except Exception as exc:
print(f"[run_agent] {exc}", file=sys.stderr)
result = {
"status": "failed",
"actual_trace_id": "",
"error": "script_reported_failure",
"output": str(exc),
}
Path(control["result_file"]).write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8")
return 0
if __name__ == "__main__":
raise SystemExit(main())Verify locally, self-check, and start
# 1. Verify that apply_hook.sh copies SKILL.md back to the business project
(cd .. && GYM_APPLY_PHASE=apply ./agentloop-gym/apply_hook.sh) && echo "apply_hook OK"
# 2. Send one sample to verify that qodercli returns normally
printf '{"input":{"query":"Review the following query statement","sql_diff":"SELECT * FROM orders WHERE status = '\''PAID'\'';"},"control":{"traceparent":"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01","result_file":"/tmp/qoder-smoke.json"}}\n' \
| python3 ./run_agent.py
cat /tmp/qoder-smoke.json
# 3. Start the client after the self-check passes
./bin/gym-client doctor --config ./gym.yaml
./bin/gym-client run --config ./gym.yamlMerge the best candidate into the business repository
After tuning completes and you are satisfied with the best round, download the patch from the details page in the console (for example, candidate.patch). Because patch paths are relative to the dedicated asset directory (skills/sql-review/SKILL.md), use --directory=.qoder in the business repository /srv/sql-review-demo to add the directory prefix:
cd /srv/sql-review-demo
# First check that the patch applies cleanly, and then apply it
git apply --check --directory=.qoder /path/to/candidate.patch
git apply --directory=.qoder /path/to/candidate.patchYou can also click Download new text to overwrite /srv/sql-review-demo/.qoder/skills/sql-review/SKILL.md directly.
Notes for connecting Qoder:
Do not add --no-session-persistence. The LoongSuite Pilot agent needs to read Qoder local session records. If you add this parameter, the local run may appear to succeed, but the cloud never receives traces (trace_not_visible).
You must enable upstreamLink.enabled and restart Pilot. If it is not enabled, the cloud receives invocation records but under another trace ID, and the smoke test finds zero spans.
Keep non-interactive mode. Always add -p --permission-mode dont_ask. If file access or command execution is required, change it to bypass_permissions as needed so that evaluation does not stop at a manual confirmation prompt.
Handle occasional trace delays. If smoke tests occasionally time out while querying traces, add time.sleep(2) before run_agent.py returns to wait for the agent to finish reporting.
Troubleshooting and daily operations
Troubleshoot the six smoke test stages
Stage | Check | Common failure causes and solutions |
1. Channel and scheduling | Server-to-client connectivity | The client is not started, is offline, or is running another task: Run ./bin/gym-client status --config ./gym.yaml in ./agentloop-gym to check the status. |
2. Asset write | Writing the candidate version to the asset directory | The asset directory is not writable, or another program is modifying the same file: Check directory permissions and stop processes that are editing the directory. |
3. Apply function | Running apply_hook.sh | The executable permission is missing (chmod +x apply_hook.sh), the copy target does not exist, or the service hot reload fails: Run (cd .. && GYM_APPLY_PHASE=apply ./agentloop-gym/apply_hook.sh) manually to view the error. |
4. Run function | Running run_agent.py to answer one question | A template not configured message means that raise StarterStubUnconfiguredError in the example has not been deleted. If the script fails, check the exception output. |
5. Trace retrieval | Retrieving the execution trace by trace ID | run_agent.py does not pass control.traceparent to the agent, or trace reporting on the agent does not work. Qoder users should check that --no-session-persistence is not used, that upstreamLink.enabled is enabled in Pilot, and that loongsuite-pilot restart has been run. |
6. Evaluation scoring | Calling the evaluator to score | Check whether the evaluator field mappings are bound to the correct dataset columns. |
Common operations
Run the following commands in the ./agentloop-gym directory:
# Check client status
./bin/gym-client status --config ./gym.yaml
# Gracefully stop the client (waits for the current task, restores the baseline automatically, and syncs the restore; do not use kill -9)
./bin/gym-client stop --config ./gym.yaml
# Install as a Linux user-level background service (runs automatically after a reboot)
./bin/gym-client service install --config ./gym.yaml
# For a system-level background service, specify a non-root account
sudo ./bin/gym-client service install --config ./gym.yaml --scope system --user <agent-user>
# Upgrade the client smoothly (drains tasks, backs up the old version, and rolls back automatically on failure)
./bin/gym-client upgrade --config ./gym.yaml --binary ./gym-client-new --drain-timeout 30mSecurity and data protection
Local Gym is designed for minimal exposure and rollback safety to protect the local environment and business code:
Clear directory and change boundaries: Gym Client runs in a dedicated tuning directory and reads and modifies only the prompt and skill text files in the asset directory that you copied. It does not access or modify the business repository, databases, or production environments directly. How a new version is synced to the agent environment and how large its impact is are entirely controlled by the apply_hook.sh script that you write.
Outbound connections only, zero inbound exposure: The client only initiates standard outbound HTTPS (port 443) requests to the AgentLoop server. The test machine does not need to open any public inbound port or configure NAT traversal.
Automatic backup and baseline restore: Before writing a new version in each round, the client saves a read-only baseline backup (permission 0400) in ./agentloop-gym/.agentloop-gym/backups/ and verifies file consistency. If an unexpected external modification is detected, the client stops immediately to avoid overwriting it. When the tuning session ends or you run gym-client stop, the client restores the asset directory to the initial version and triggers apply_hook.sh again (GYM_APPLY_PHASE=restore) to restore the agent environment.
Least privilege and no credentials on disk: The client requires a non-root regular account. ARMS_LICENSE_KEY in the installation command is used only for the initial local key registration and is not written to gym.yaml or any background service configuration file. Later starts and restarts use the local key for authentication.
Controlled uploads and local egress auditing: The installation does not upload any prompt or skill content in advance. Before starting the client, you can use gym-client doctor to confirm the file list to be included in tuning, and then run gym-client run to establish the connection.
All outbound requests from the client to the server are recorded in the local audit log, with credentials automatically redacted. You can run the following command in ./agentloop-gym at any time to check the log:
grep '"type":"http_egress"' ./.agentloop-gym/audit/audit.jsonl | tail -n 5