Skip to main content

OpenApiToolset

Struct OpenApiToolset 

Source
pub struct OpenApiToolset { /* private fields */ }
Expand description

A set of tools generated from an OpenAPI specification.

Each operation in the spec becomes a tool that can be registered with a rig agent. The toolset is designed to be parsed once and reused across requests.

Implementations§

Source§

impl OpenApiToolset

Source

pub fn from_file(path: impl AsRef<Path>) -> Result<Self>

Parse an OpenAPI spec from a YAML or JSON file.

Examples found in repository?
examples/jsonplaceholder.rs (line 9)
6async fn main() -> anyhow::Result<()> {
7    let openai = rig::providers::openai::Client::from_env();
8
9    let toolset = OpenApiToolset::from_file("examples/openapi.yaml")?;
10    println!("Loaded {} tools from OpenAPI spec", toolset.len());
11
12    let agent = openai
13        .agent("gpt-4o")
14        .preamble("You have access to API tools. Use them when asked.")
15        .tools(toolset.into_tools())
16        .build();
17
18    let response: String = agent
19        .prompt("Use the API tool to get user 1 and summarize the result.")
20        .await?;
21
22    println!("{response}");
23
24    Ok(())
25}
Source

pub fn from_spec_str(spec_str: &str) -> Result<Self>

Parse an OpenAPI spec from a YAML or JSON string.

Source

pub fn builder(spec_str: &str) -> OpenApiToolsetBuilder

Start building a toolset from a YAML or JSON string with configuration options.

Source

pub fn builder_from_file( path: impl AsRef<Path>, ) -> Result<OpenApiToolsetBuilder>

Start building a toolset from a file with configuration options.

Examples found in repository?
examples/petstore.rs (line 12)
8async fn main() -> anyhow::Result<()> {
9    let openai = rig::providers::openai::Client::from_env();
10
11    // Parse once at startup — reuse across requests
12    let toolset = OpenApiToolset::builder_from_file("examples/petstore.json")?
13        .base_url("https://petstore3.swagger.io/api/v3")
14        .build()?;
15
16    println!("Loaded {} tools from Petstore spec\n", toolset.len());
17
18    // Simulate a per-request context (e.g. from a logged-in user session)
19    let visible_ctx = HashMap::from([
20        ("username".to_string(), "user1".to_string()),
21        ("preferred_status".to_string(), "available".to_string()),
22    ]);
23    let context_preamble = OpenApiToolset::context_preamble(&visible_ctx);
24
25    let preamble = format!(
26        "You have access to the Swagger Petstore API. \
27         Use the available tools to answer questions about the pet store.\n\n\
28         {context_preamble}"
29    );
30
31    // Create agent with per-request tools (cheap clone)
32    let agent = openai
33        .agent("gpt-4o")
34        .preamble(&preamble)
35        .tools(toolset.tools_with_context(&HashMap::new()))
36        .build();
37
38    let prompts = [
39        "What pets are currently available in the store? Show me the first 3.",
40        "Get the store inventory and tell me the status counts.",
41        "Look up my user profile and summarize it.",
42    ];
43
44    for prompt in prompts {
45        println!(">>> {prompt}");
46        let response: String = agent.prompt(prompt).await?;
47        println!("{response}\n");
48    }
49
50    Ok(())
51}
Source

pub fn len(&self) -> usize

Return the number of tools parsed from the spec.

Examples found in repository?
examples/jsonplaceholder.rs (line 10)
6async fn main() -> anyhow::Result<()> {
7    let openai = rig::providers::openai::Client::from_env();
8
9    let toolset = OpenApiToolset::from_file("examples/openapi.yaml")?;
10    println!("Loaded {} tools from OpenAPI spec", toolset.len());
11
12    let agent = openai
13        .agent("gpt-4o")
14        .preamble("You have access to API tools. Use them when asked.")
15        .tools(toolset.into_tools())
16        .build();
17
18    let response: String = agent
19        .prompt("Use the API tool to get user 1 and summarize the result.")
20        .await?;
21
22    println!("{response}");
23
24    Ok(())
25}
More examples
Hide additional examples
examples/petstore.rs (line 16)
8async fn main() -> anyhow::Result<()> {
9    let openai = rig::providers::openai::Client::from_env();
10
11    // Parse once at startup — reuse across requests
12    let toolset = OpenApiToolset::builder_from_file("examples/petstore.json")?
13        .base_url("https://petstore3.swagger.io/api/v3")
14        .build()?;
15
16    println!("Loaded {} tools from Petstore spec\n", toolset.len());
17
18    // Simulate a per-request context (e.g. from a logged-in user session)
19    let visible_ctx = HashMap::from([
20        ("username".to_string(), "user1".to_string()),
21        ("preferred_status".to_string(), "available".to_string()),
22    ]);
23    let context_preamble = OpenApiToolset::context_preamble(&visible_ctx);
24
25    let preamble = format!(
26        "You have access to the Swagger Petstore API. \
27         Use the available tools to answer questions about the pet store.\n\n\
28         {context_preamble}"
29    );
30
31    // Create agent with per-request tools (cheap clone)
32    let agent = openai
33        .agent("gpt-4o")
34        .preamble(&preamble)
35        .tools(toolset.tools_with_context(&HashMap::new()))
36        .build();
37
38    let prompts = [
39        "What pets are currently available in the store? Show me the first 3.",
40        "Get the store inventory and tell me the status counts.",
41        "Look up my user profile and summarize it.",
42    ];
43
44    for prompt in prompts {
45        println!(">>> {prompt}");
46        let response: String = agent.prompt(prompt).await?;
47        println!("{response}\n");
48    }
49
50    Ok(())
51}
Source

pub fn is_empty(&self) -> bool

Returns true if no operations were found in the spec.

Source

pub fn into_tools(self) -> Vec<Box<dyn ToolDyn>>

Consume the toolset and return tools for use with rig’s AgentBuilder::tools().

Examples found in repository?
examples/jsonplaceholder.rs (line 15)
6async fn main() -> anyhow::Result<()> {
7    let openai = rig::providers::openai::Client::from_env();
8
9    let toolset = OpenApiToolset::from_file("examples/openapi.yaml")?;
10    println!("Loaded {} tools from OpenAPI spec", toolset.len());
11
12    let agent = openai
13        .agent("gpt-4o")
14        .preamble("You have access to API tools. Use them when asked.")
15        .tools(toolset.into_tools())
16        .build();
17
18    let response: String = agent
19        .prompt("Use the API tool to get user 1 and summarize the result.")
20        .await?;
21
22    println!("{response}");
23
24    Ok(())
25}
Source

pub fn tools_with_context( &self, context: &HashMap<String, String>, ) -> Vec<Box<dyn ToolDyn>>

Clone the tools with per-request context injected as hidden parameters. The LLM will not see these parameters in tool schemas, but they will be auto-injected into every tool call at execution time.

This is the primary way to add per-request state (user ID, session info, etc.) while reusing the parsed toolset across requests.

Examples found in repository?
examples/petstore.rs (line 35)
8async fn main() -> anyhow::Result<()> {
9    let openai = rig::providers::openai::Client::from_env();
10
11    // Parse once at startup — reuse across requests
12    let toolset = OpenApiToolset::builder_from_file("examples/petstore.json")?
13        .base_url("https://petstore3.swagger.io/api/v3")
14        .build()?;
15
16    println!("Loaded {} tools from Petstore spec\n", toolset.len());
17
18    // Simulate a per-request context (e.g. from a logged-in user session)
19    let visible_ctx = HashMap::from([
20        ("username".to_string(), "user1".to_string()),
21        ("preferred_status".to_string(), "available".to_string()),
22    ]);
23    let context_preamble = OpenApiToolset::context_preamble(&visible_ctx);
24
25    let preamble = format!(
26        "You have access to the Swagger Petstore API. \
27         Use the available tools to answer questions about the pet store.\n\n\
28         {context_preamble}"
29    );
30
31    // Create agent with per-request tools (cheap clone)
32    let agent = openai
33        .agent("gpt-4o")
34        .preamble(&preamble)
35        .tools(toolset.tools_with_context(&HashMap::new()))
36        .build();
37
38    let prompts = [
39        "What pets are currently available in the store? Show me the first 3.",
40        "Get the store inventory and tell me the status counts.",
41        "Look up my user profile and summarize it.",
42    ];
43
44    for prompt in prompts {
45        println!(">>> {prompt}");
46        let response: String = agent.prompt(prompt).await?;
47        println!("{response}\n");
48    }
49
50    Ok(())
51}
Source

pub fn context_preamble(context: &HashMap<String, String>) -> String

Generate a preamble snippet describing the visible context for the LLM. Include this in your agent’s .preamble() so the LLM knows about available context values it can use when calling tools.

Examples found in repository?
examples/petstore.rs (line 23)
8async fn main() -> anyhow::Result<()> {
9    let openai = rig::providers::openai::Client::from_env();
10
11    // Parse once at startup — reuse across requests
12    let toolset = OpenApiToolset::builder_from_file("examples/petstore.json")?
13        .base_url("https://petstore3.swagger.io/api/v3")
14        .build()?;
15
16    println!("Loaded {} tools from Petstore spec\n", toolset.len());
17
18    // Simulate a per-request context (e.g. from a logged-in user session)
19    let visible_ctx = HashMap::from([
20        ("username".to_string(), "user1".to_string()),
21        ("preferred_status".to_string(), "available".to_string()),
22    ]);
23    let context_preamble = OpenApiToolset::context_preamble(&visible_ctx);
24
25    let preamble = format!(
26        "You have access to the Swagger Petstore API. \
27         Use the available tools to answer questions about the pet store.\n\n\
28         {context_preamble}"
29    );
30
31    // Create agent with per-request tools (cheap clone)
32    let agent = openai
33        .agent("gpt-4o")
34        .preamble(&preamble)
35        .tools(toolset.tools_with_context(&HashMap::new()))
36        .build();
37
38    let prompts = [
39        "What pets are currently available in the store? Show me the first 3.",
40        "Get the store inventory and tell me the status counts.",
41        "Look up my user profile and summarize it.",
42    ];
43
44    for prompt in prompts {
45        println!(">>> {prompt}");
46        let response: String = agent.prompt(prompt).await?;
47        println!("{response}\n");
48    }
49
50    Ok(())
51}

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> WasmCompatSend for T
where T: Send,

Source§

impl<T> WasmCompatSync for T
where T: Sync,