Skip to main content

Module native

Module native 

Source
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§

ModelTurn
What a model response contained.
ToolCall
One tool call requested by the model.
ToolOutput
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 (content blocks), or Ollama’s /api/chat (message).
tool_results_anthropic
Tool results as one Anthropic user message of tool_result blocks.
tool_results_openai
Tool results as OpenAI Chat Completions tool messages, to append after the assistant message that made the calls. Failed calls start with Error: (the format has no error flag).
tool_results_responses
Tool results as OpenAI Responses API function_call_output input items. Failed calls start with Error:.