Expand description
Native tool calling: the JSON formats OpenAI, Anthropic and Ollama use.
Text ReAct (Action: tool(input)) works with any model, but current
models are trained to call tools through the API instead. This module
turns a ToolRegistry into the tools array each
API expects, reads the tool calls out of a raw response body, and formats
the results to send back. No HTTP client: you send and receive the JSON.
use wasm_agent::{Agent, AgentConfig, NativeStep, ToolSpec};
use wasm_agent::types::ToolResult;
let mut agent = Agent::new(AgentConfig::default());
agent.tools_mut().register(
ToolSpec::new("get_weather", "Weather for a city",
r#"{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}"#),
Box::new(|args: &str| ToolResult { tool_name: "get_weather".into(), output: format!("sunny ({args})"), success: true }),
)?;
let tools = agent.tools().openai_tools()?; // put this in the request body
assert_eq!(tools[0]["function"]["name"], "get_weather");
// The model's reply (OpenAI Chat Completions):
let reply = r#"{"choices":[{"message":{"role":"assistant","content":null,"tool_calls":[
{"id":"call_1","type":"function","function":{"name":"get_weather","arguments":"{\"city\":\"Paris\"}"}}]}}]}"#;
let NativeStep::ToolCalls(results) = agent.step_response(reply)? else { panic!() };
assert_eq!(results[0].output, r#"sunny ({"city":"Paris"})"#);
let follow_up = wasm_agent::native::tool_results_openai(&results); // append to messages
assert_eq!(follow_up[0]["tool_call_id"], "call_1");Structs§
- Model
Turn - What a model response contained.
- Tool
Call - One tool call requested by the model.
- Tool
Output - The result of one tool call, ready to send back.
Functions§
- parse_
model_ response - Read the text and tool calls out of a raw response body from OpenAI Chat
Completions (
choices[0].message), the OpenAI Responses API (output), Anthropic Messages (contentblocks), or Ollama’s/api/chat(message). - tool_
results_ anthropic - Tool results as one Anthropic
usermessage oftool_resultblocks. - tool_
results_ openai - Tool results as OpenAI Chat Completions
toolmessages, to append after the assistant message that made the calls. Failed calls start withError:(the format has no error flag). - tool_
results_ responses - Tool results as OpenAI Responses API
function_call_outputinput items. Failed calls start withError:.