Agents
An agent gives a model instructions and tools, then repeats a simple cycle: ask the model what to do, run any requested tool, and give the result back to the model. The run ends when the model returns an answer or a configured limit is reached. Your application provides the model and tool implementations; the shared Rust runtime handles the cycle and configured policies.
The agent itself does not decide where every kind of state belongs. Use a
stable session_id plus a persistence store for dialogue that should continue
in a later run. Use ContextStore for mutable task data shared with tools or
subagents, and MemoryStore for reusable agent knowledge that can be recalled
across sessions. Context and memory are in memory unless persistence is
configured. See Short-Term Dialogue,
Context, and Memory.
- Python
- TypeScript
- Rust
- Go
- C#
- Java
import asyncio
from ish import Agent, tool
@tool
async def lookup_order(order_id: str) -> str:
"""Return the current status of an order."""
return f"Order {order_id} is being prepared."
async def main() -> None:
agent = Agent(
name="order_assistant",
model="gpt-4o-mini",
instructions="Answer using the available order lookup tool when needed.",
tools=[lookup_order],
max_turns=6,
)
try:
result = await agent.run("Where is order A-104?")
print(result.content)
finally:
agent.close()
if __name__ == "__main__":
asyncio.run(main())
import { Agent } from "ish-harness";
async function main(): Promise<void> {
const agent = new Agent({
name: "order_assistant",
model: { provider: "openai_chat", name: "gpt-4o-mini" },
instructions: "Answer using the available order lookup tool when needed.",
max_turns: 6,
tools: [
{
name: "lookup_order",
description: "Return the current status of an order.",
parameters: {
type: "object",
properties: { order_id: { type: "string" } },
required: ["order_id"],
},
execute: async (args) => {
const { order_id } = args as { order_id: string };
return `Order ${order_id} is being prepared.`;
},
},
],
});
try {
const result = await agent.run("Where is order A-104?");
console.log(result.content);
} finally {
agent.close();
}
}
main().catch(console.error);
use std::{env, io, sync::Arc};
use async_trait::async_trait;
use ish_harness::{data_plane::tool_backend::ToolBackend, Agent, OpenAIModel};
use serde_json::{json, Value};
struct LookupOrder;
#[async_trait]
impl ToolBackend for LookupOrder {
fn name(&self) -> &str {
"lookup_order"
}
fn description(&self) -> &str {
"Return the current status of an order."
}
fn schema_json(&self) -> Option<Value> {
Some(json!({
"type": "object",
"properties": { "order_id": { "type": "string" } },
"required": ["order_id"]
}))
}
async fn call(&self, arguments: Value) -> Result<String, String> {
let order_id = arguments["order_id"]
.as_str()
.ok_or_else(|| "order_id must be a string".to_string())?;
Ok(format!("Order {order_id} is being prepared."))
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let model = OpenAIModel::new(
"gpt-4o-mini".into(),
"https://api.openai.com/v1".into(),
env::var("OPENAI_API_KEY")?,
0.2,
);
let agent = Agent::builder(Arc::new(model))
.name("order_assistant")
.instructions("Answer using the available order lookup tool when needed.")
.tool(Arc::new(LookupOrder))
.max_turns(6)
.build()
.map_err(io::Error::other)?;
let result = agent
.run("Where is order A-104?")
.await
.map_err(io::Error::other)?;
println!("{}", result.content);
Ok(())
}
package main
import (
"context"
"fmt"
"github.com/ish-harness/ish-harness/sdks/go"
)
func main() {
client, err := ish.NewClient()
if err != nil {
panic(err)
}
defer client.Close()
agent := ish.NewAgent(client, ish.AgentRunRequest{
AgentName: "order_assistant",
Model: &ish.AgentModel{Provider: "openai_chat", Name: "gpt-4o-mini"},
SystemPrompt: ish.StringPtr("Answer using the available order lookup tool when needed."),
MaxTurns: ish.IntPtr(6),
Tools: []ish.AgentTool{
{
Name: "lookup_order",
Description: "Return the current status of an order.",
Parameters: map[string]any{
"type": "object",
"properties": map[string]any{
"order_id": map[string]any{"type": "string"},
},
"required": []string{"order_id"},
},
Execute: func(ctx context.Context, args map[string]any) (any, error) {
return fmt.Sprintf("Order %v is being prepared.", args["order_id"]), nil
},
},
},
})
result, err := agent.Run(context.Background(), "Where is order A-104?")
if err != nil {
panic(err)
}
fmt.Println(result["content"])
}
using System.Text.Json;
using Ish.Harness;
using var ish = new IshClient();
using var schema = JsonDocument.Parse(
"""{"type":"object","properties":{"order_id":{"type":"string"}},"required":["order_id"]}""");
var result = ish.Run(new AgentRunRequest
{
AgentName = "order_assistant",
Model = new AgentModel { Provider = "openai_chat", Name = "gpt-4o-mini" },
SystemPrompt = "Answer using the available order lookup tool when needed.",
UserPrompt = "Where is order A-104?",
MaxTurns = 6,
Tools =
[
new AgentTool
{
Name = "lookup_order",
Description = "Return the current status of an order.",
Parameters = schema.RootElement.Clone(),
Execute = (args, _) =>
{
var orderId = args.GetProperty("order_id").GetString();
return ValueTask.FromResult<object?>($"Order {orderId} is being prepared.");
},
},
],
});
Console.WriteLine(result.GetProperty("content").GetString());
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.ishharness.IshClient;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) throws Exception {
var schema = new ObjectMapper().readTree(
"{\"type\":\"object\",\"properties\":{\"order_id\":{\"type\":\"string\"}},\"required\":[\"order_id\"]}");
try (var ish = new IshClient(Path.of(System.getenv("ISH_NATIVE_LIBRARY")))) {
var request = new IshClient.AgentRequest(
"gpt-4o-mini",
"Answer using the available order lookup tool when needed.",
"Where is order A-104?")
.provider("openai_chat")
.agentName("order_assistant")
.maxTurns(6)
.tool(
"lookup_order",
"Return the current status of an order.",
schema,
toolArgs -> "Order " + toolArgs.path("order_id").asText() + " is being prepared.");
JsonNode result = ish.runAgent(request);
System.out.println(result.path("content").asText());
}
}
}
How the agent loop works
Before the first model call, the runtime validates the request and applies input checks. If configured, it also loads prior session history. Each turn then asks the model for an answer or tool call. Tool calls pass through permissions and guardrails before execution, and their results become input for the next turn. The runtime can batch eligible independent read-only tools; other calls run in order. Advanced options such as speculative prefetch and compaction are described below.
How independent tools run
When a model requests multiple independent, read-only tools in one turn, the runtime may run them concurrently. Calls that can write data, require approval, or pass through configured policy hooks remain ordered so checks happen consistently.
The runtime can also prefetch likely read-only work when you configure a draft model. Prefetch uses the run’s token and cost budgets. Context compaction can archive older turns before the model’s context window fills; the agent can retrieve those turns when needed.
Configure run limits
| Setting | What it controls |
|---|---|
max_turns | Maximum number of model/tool cycles |
max_total_tokens and max_cost_usd | Optional run budgets |
context_window_tokens | Starts proactive compaction before the context limit |
auto_virtualize and virtualize_threshold | Stores large tool results out of the prompt |
context_offload | Saves large results to files with a short preview |
tombstone_observations | Replaces older tool results in the conversation with a short note; tools can still access the original result during the run |
enable_circuit_breaker | Stops repeated identical tool calls |
See the API reference for every option and its defaults.
Create an agent
Each language exposes an agent entry point backed by the same Rust execution
loop. Python offers a host-specific @tool decorator for automatic schema
inference. TypeScript, Go, C#, and Java register explicit JSON Schema tool
descriptors. Rust applications can provide their own tool implementation using
the Rust tool interface.
Set the API key required by the selected provider before running the example. See Rust quickstart for Rust source-build setup and model integrations for provider configuration.
Streaming events
The runtime enriches each StreamEvent with monotonic per-run sequence,
trace_id, optional session_id, event_id ("<trace_id>:<16-hex sequence>"),
and tool_call_id when present. The terminal "done" event carries the
serialized AgentResult payload (usage, model_usages, total_cost_usd, and
verification):
- Python
- TypeScript
- Rust
- Go
- C#
- Java
async for event in agent.stream("Summarize order A-104."):
if event.event_type == "token":
print(event.data, end="", flush=True)
for await (const event of agent.stream("Summarize order A-104.")) {
console.log(event.event_type, event.data);
}
let result = agent
.stream("Summarize order A-104.", &mut |event| {
println!("{}: {}", event.event_type, event.data);
})
.await
.map_err(io::Error::other)?;
println!("Final: {}", result.content);
result, err := agent.Stream(
context.Background(),
"Summarize order A-104.",
func(event map[string]any) {
fmt.Println(event["event_type"], event["data"])
},
)
using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(2));
await foreach (var item in ish.StreamAsync(request, cts.Token))
{
Console.WriteLine(item);
}
JsonNode result = ish.streamAgent(
request,
event -> System.out.println(event.path("event_type").asText() + ": " + event.path("data")));
Results, checkpoints
AgentResult reports trace_id, content,
history, tool_calls_count, duration_ms, prompt_tokens,
completion_tokens, reasoning_tokens, total_tokens, total_cost_usd,
cost_is_estimate, cost_estimate_complete, model_usages, and
verification (VerificationReport with status: "passed", "incomplete",
or "not_configured"). Durable runner checkpoints (RunnerCheckpointOptions)
bind the saved run to a fingerprint of its tools, instructions, and settings.
If these inputs change before resume, ISH stops instead of continuing with a
different setup. See SQLite storage for details.
For language-specific option names and builder signatures, consult the package guides:
The shared conformance suite checks selected portable behavior across the six SDKs. Idiomatic method names, signatures, and host integrations can differ by language; the shared behavior covered by the suite is defined by the Rust operations and their conformance cases. The suite does not cover every possible input. See SDK coverage for its scope.
Continue reading
Reusable, remote agents
All six language SDKs provide a reusable Agent abstraction; C# and Java expose it alongside their IshClient run APIs. RemoteAgent provides a typed remote-run helper in the host SDKs. For coding tasks, compose the workspace tools, context, skills, memory, planning, policy gates, and child-agent definitions exposed by your SDK. There is currently no one-call coding-agent constructor in the public SDK surface. The ish-code command-line application is a separate Rust application. See each SDK guide for its available components and language-specific API names.