Every provider has a different client
In most projects that interface with LLMs, there is often a need to communicate with multiple providers, such as Anthropic and OpenAI, to meet the user's needs.
Once you support more than one LLM provider, the problem stops being "how do I call an API?" and becomes "how do I avoid leaking provider-specific details everywhere?"
I wanted to support Anthropic, OpenAI, Gemini, and Ollama through the same interface, so the rest of the router wouldn't have to care which provider was behind a request.
Wrapping Rig's completion model
Luckily, Rig.rs already provides a simple way to do that.
In Rig 0.47.1, each provider builds its own completion model. I can call
erase() to turn it into a DynModel<Completion>, which keeps the completion
interface and hides the provider-specific types. This is what I store on my
Agent, along with its preamble and memory tool.
pub struct Agent<S: MemoryStorage> {
model: DynModel<Completion>,
preamble: String,
memory: MemoryTool<S>,
}
I keep control over when tools are run, so the agent can execute its own memory tool and hand other tool calls back to the router. I've left out the imports and application-specific helper types in the snippets below.
From clients to abstract Agents
But how do I get from a connection to Gemini or Anthropic to my Agent struct?
Rig already provides provider-specific clients that can be configured with the required settings, such as API keys, base URLs, and other provider-specific options. That allows me to keep my own abstraction small.
For example, building an agent for Gemini looks like this. The reqwest feature
on rig-core provides the default HTTP transport used by Gemini::new.
fn gemini_agent<S: MemoryStorage>(
api_key: &str,
model_name: &str,
preamble: String,
storage: Arc<S>,
scope: MemoryScope,
) -> Agent<S> {
let model = Gemini::new(api_key).completion(model_name).erase();
Agent {
model,
preamble,
memory: MemoryTool { storage, scope },
}
}
Anthropic, OpenAI, and Ollama each have their own client. Once I erase their
completion models, I can pass any of them to the same Agent.
Sending a request from an Agent to the LLM
At this point, I can send a CompletionRequest directly to the model.
The caller supplies the conversation, generation options, and tools. I add the
agent's system message and memory tool definition before sending the request.
If the model replies with text, I return the response. If it asks only for memory operations, I execute them and append the assistant's reply followed by the tool results. Then I send the request again. If any call needs the router, I return the whole batch so the caller can handle it together.
// Bound the number of model calls made while handling memory tools.
const MAX_COMPLETION_ROUNDS: usize = 8;
impl<S: MemoryStorage + 'static> Agent<S> {
async fn complete(&self, request: CompletionRequest) -> Result<CompletionResponse> {
let mut request = self.prepare_request(request).await?;
let mut usage = Usage::default();
for round in 1..=MAX_COMPLETION_ROUNDS {
let mut response = self.model.call(request.clone()).await?;
usage += response.usage;
let calls: Vec<_> = response.tool_calls().collect();
if !matches!(response.stop(), StopReason::ToolUse)
|| calls.is_empty()
|| calls.iter().any(|call| call.function.name != MemoryTool::<S>::NAME)
{
response.usage = usage;
return Ok(response);
}
if round == MAX_COMPLETION_ROUNDS {
break;
}
let mut results = Vec::with_capacity(calls.len());
for call in calls {
let args = serde_json::from_str(&call.function.raw_arguments())?;
let output = self.memory.call(&mut ToolContext::default(), args).await?;
results.push(call.result(vec![ToolResultContent::text(output)]));
}
if let Some(message) = response.message() {
request.chat_history.push(Arc::new(message));
}
request.chat_history.push(Arc::new(Message::tool_results(results)));
}
anyhow::bail!("model exceeded the internal tool round limit");
}
async fn stream(&self, request: CompletionRequest) -> Result<CompletionStream> {
let request = self.prepare_request(request).await?;
Ok(self.model.stream(request)?)
}
}
MAX_COMPLETION_ROUNDS prevents the agent from getting stuck if the model keeps
asking for memory operations. I also add up the usage from every round, since
one call to complete can involve more than one request to the provider.
I can also use stream() to receive events as they arrive. In this version,
the caller consumes the stream and handles every tool call, including memory
calls. The loop above is for complete().
Adding user and session memory through a Rig Tool
One of the core functionalities of LLM agents is the possibility to use session and user memories. I want the agent to save meaningful information for reuse in the current session and across sessions, including user preferences. Later, the agent needs to be able to recall those memories.
For this purpose, I implemented a MemoryStorage trait and a Rig Tool.
The backend is shared, so each operation takes a MemoryScope with the user
and session IDs. The tool gets this scope from the application when I build
the agent.
First, I defined a MemoryRecord to keep track of each memory. A key lets
the tool find or replace the record later.
#[derive(Debug)]
pub struct MemoryRecord {
/// Opaque, backend-defined handle identifying this entry. Pass it back to
/// `forget_*` to remove exactly this entry.
pub handle: String,
/// Optional topic. A keyed entry upserts on its key, so a later record with
/// the same key replaces this one; keyless entries accumulate freely.
pub key: Option<String>,
/// The remembered fact.
pub content: String,
}
Then I used this data as the core type for MemoryStorage.
#[derive(Clone, Debug)]
pub struct MemoryScope {
pub user_id: String,
pub session_id: String,
}
pub trait MemoryStorage: Send + Sync {
type Error: std::error::Error + Send + Sync + 'static;
fn put_user_memory(
&self,
scope: &MemoryScope,
key: Option<String>,
content: String,
) -> impl Future<Output = Result<MemoryRecord, Self::Error>> + Send;
fn forget_user_memory(
&self,
scope: &MemoryScope,
handle: String,
) -> impl Future<Output = Result<(), Self::Error>> + Send;
fn get_user_memories(
&self,
scope: &MemoryScope,
limit: Option<usize>,
) -> impl Future<Output = Result<Vec<MemoryRecord>, Self::Error>> + Send;
fn get_user_memory_by_key(
&self,
scope: &MemoryScope,
key: String,
) -> impl Future<Output = Result<Option<MemoryRecord>, Self::Error>> + Send;
}
I've shown the user methods here. The trait exposes the same methods for session records.
To collect operations on memories, I need to use a Tool.
A tool is a typed function exposed to the model. The model emits a
structured tool call, and the host application decides whether and how to
run it. In Rig 0.47.1, a Tool describes itself through description and
parameters. Its call method also receives a ToolContext, which I can
leave unused here because the tool already has its storage and scope.
pub struct MemoryTool<S>
where
S: MemoryStorage,
{
storage: Arc<S>,
scope: MemoryScope,
}
impl<S> Tool for MemoryTool<S>
where
S: MemoryStorage + 'static,
{
const NAME: &'static str = "memory";
type Error = MemoryToolError<S::Error>;
type Args = MemoryArgs;
type Output = String;
fn description(&self) -> String {
concat!(
"Record or forget a memory addressed by a key. ",
"Use user scope for durable facts such as preferences, ",
"and session scope for facts relevant to the current session. ",
"Recording under an existing key replaces its value. ",
"Stored memories are supplied as context at the start of each turn."
)
.to_owned()
}
fn parameters(&self) -> serde_json::Value {
serde_json::json!({
"type": "object",
"properties": {
"op": { "type": "string", "enum": ["record", "forget"] },
"scope": { "type": "string", "enum": ["user", "session"] },
"key": { "type": "string" },
"value": {
"type": "string",
"description": "The fact to record. Required for record."
}
},
"required": ["op", "scope", "key"]
})
}
async fn call(
&self,
_context: &mut ToolContext,
args: MemoryArgs,
) -> Result<String, Self::Error> {
let MemoryArgs {
op,
scope: store,
key,
value,
} = args;
let store_label = store.label();
match op {
MemoryOp::Record => {
let value = value.ok_or(MemoryToolError::MissingValue)?;
match store {
MemoryStore::User => {
self.storage
.put_user_memory(&self.scope, Some(key.clone()), value)
.await?;
}
MemoryStore::Session => {
self.storage
.put_session_memory(&self.scope, Some(key.clone()), value)
.await?;
}
}
Ok(format!("Recorded {store_label} memory \"{key}\"."))
}
MemoryOp::Forget => match self.handle_for(store, key.clone()).await? {
Some(handle) => {
match store {
MemoryStore::User => self.storage.forget_user_memory(&self.scope, handle).await?,
MemoryStore::Session => self.storage.forget_session_memory(&self.scope, handle).await?,
}
Ok(format!("Forgot {store_label} memory \"{key}\"."))
}
None => Ok(format!("No {store_label} memory found for \"{key}\".")),
},
}
}
}
The scope argument tells me which store the model wants to use, user or
session. The MemoryScope on the tool tells the backend whose records it can
access.
Notice that the tool doesn't expose a recall operation. I load the memories before the turn starts and append them to the agent's preamble. The model can record or forget memories, and the host handles retrieval.
Linking Memory into the Agent
At this point, I can use my MemoryStorage implementation to provide both
the tool and the user's records to the agent. I load the user and session
memories using the same scope as the tool. I then put the base preamble and
the memories together before adding them to the request.
impl<S: MemoryStorage + 'static> Agent<S> {
async fn prepare_request(&self, request: CompletionRequest) -> Result<CompletionRequest> {
let storage = &self.memory.storage;
let scope = &self.memory.scope;
let user_memories = storage.get_user_memories(scope, None).await?;
let session_memories = storage.get_session_memories(scope, None).await?;
let mut preamble = self.preamble.clone();
for (heading, records) in [
("User memories", user_memories),
("Session memories", session_memories),
] {
if records.is_empty() {
continue;
}
preamble.push_str(&format!("\n\n{heading}:"));
for record in records {
preamble.push_str("\n- ");
preamble.push_str(&record.content);
}
}
let memory = tool_definition(&self.memory);
anyhow::ensure!(
request.tools.iter().all(|tool| tool.name != memory.name),
"the memory tool name is reserved for the agent"
);
Ok(request.preamble(preamble).tool(memory))
}
}
Conclusion
I still needed my own abstraction. Rig moved the provider-specific complexity to the edges.
Each provider still has its own client, authentication, model names, and
configuration. Once I have a DynModel<Completion>, the router can use the
same Agent, attach the same memory tool, and handle completions through the
same flow.
Keeping the loop in the agent gives me control over which tool calls I can handle right away and which ones need to go back to the router.



