Skip to main content

Client

Struct Client 

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

A client of the TypeSafe API.

A client holds the settings of each request. A clone shares the connections, the cache, the limit on requests, and the total of tokens. A builder method changes only its own client.

.ask on a question set uses the global client. Its first use makes it with Client::from_env. Client::set_global replaces it.

§Examples

use std::time::Duration;
use system2::{Client, noul};

let client = Client::from_env()?
    .model("jev-1.14.0")
    .timeout(Duration::from_secs(30));
let urgent = noul!("Is the ticket urgent?");
let answer = client.ask(urgent, "The site is down.").await?;

Implementations§

Source§

impl Client

Source

pub fn new() -> Self

Makes a client with the default settings, and no environment.

The client has no API key, so it answers only from a cache until api_key gives one.

§Panics

Panics if TLS cannot start, as reqwest::Client::new does.

Source

pub fn from_env() -> Result<Self, EnvError>

Makes a client from the environment.

It reads five variables. It removes whitespace from the start and the end of each one. An empty variable counts as not set.

  • TYPESAFE_API_KEY: the key. With no key, only the cache answers.
  • TYPESAFE_BASE_URL: the base URL.
  • TYPESAFE_DEFAULT_MODEL: the model.
  • SYSTEM2_CACHE: the path of a cache file. With no path, the client has no cache.
  • SYSTEM2_OFFLINE: 1 makes the client offline.
§Errors
Source

pub fn api_key(self, api_key: impl Into<String>) -> Self

Sets the API key. The default is no key.

It removes whitespace from the start and the end of the key, and an empty key counts as no key. The client needs a key only for a request that it sends. ask returns AskError::MissingApiKey with no key, and AskError::InvalidApiKey if the key is not a valid HTTP header value.

Source

pub fn base_url(self, base_url: impl Into<String>) -> Self

Sets the base URL of the API. The default is https://api.typesafe.ai.

https://openrouter.ai/api sends each request through OpenRouter, which serves Jev with the same API. Give the client an OpenRouter key with api_key or TYPESAFE_API_KEY.

ask returns AskError::InvalidBaseUrl if the URL is not an absolute HTTP or HTTPS URL.

Source

pub fn model(self, model: impl Into<String>) -> Self

Sets the model. The default is jev-latest.

The client does not validate the name. The API refuses an unknown model, and ask returns AskError::Http.

Source

pub fn timeout(self, timeout: Duration) -> Self

Sets the timeout of each attempt, from the send to the end of the response. The default is 10 s.

Source

pub fn max_retries(self, max_retries: u32) -> Self

Sets the number of attempts after the first. The default is 2.

A 408, a 429, a 5xx, a timeout, or a failed connection gets a retry. The wait comes from the retry-after-ms or Retry-After header, or else from a backoff from 0.5 s to 5 s. If a header asks for a wait of more than 30 s, the client returns the error.

Source

pub fn max_concurrent_requests(self, max_concurrent_requests: usize) -> Self

Sets the number of requests that the client and its clones send at the same time. The default is 8.

A request over the limit waits. An answer from the cache does not wait. A limit of 0 is a limit of 1. On a clone, it gives a new limit, which only the later clones of that clone share.

Source

pub fn long_context(self, long_context: bool) -> Self

Raises the token limits of the API. The default is false.

It sends the header TypeSafe-Danger-Zone-Long-Context: true. OpenRouter always has the long context, so this changes nothing there.

Source

pub fn compression(self, compression: Compression) -> Self

Sets the compression of each request body. The default is Compression::Zstd.

Source

pub fn cache(self, path: impl Into<PathBuf>) -> Result<Self, CacheError>

Opens a cache file, and makes it the cache of the client. The default is no cache.

The cache is a JSON Lines file. Each line holds the SHA-256 of a request body and the response. A request with an equal body gets the stored response, with no network. A response goes into the file only after its answers are valid. The client reads the file only here, so it does not see the lines that another process adds later.

It makes the file if the file does not exist, but not its folder. A file that the client can only read, such as on a read-only file system, still gives its responses. Then ask returns AskError::Cache for a new response. On a clone, it gives a new cache, which only the later clones of that clone share.

§Errors
Source

pub fn offline(self, offline: bool) -> Self

Makes the client answer only from the cache. The default is false.

An offline request that is not in the cache returns AskError::Offline.

Source

pub fn trace_bodies(self, trace_bodies: bool) -> Self

Writes the body of each request in a TRACE event. The default is false.

The event has the target system2::body, and the body is in its field system2.body. A body holds the state, which is often private.

Source

pub fn usage(&self) -> Usage

Returns the total of tokens of the client and its clones.

It counts the tokens of each response from the API, also when the answers or the model are not valid. An answer from the cache adds no tokens.

Source

pub fn set_global(self) -> Client

Makes the client the global client, and returns a clone of it.

A request that .ask started before keeps its client. A clone of the old global client does not change.

Source

pub fn global() -> Result<Client, EnvError>

Returns a clone of the global client.

If there is no global client, it makes one with Client::from_env, as the first .ask does. A clone shares the total of tokens, so its usage is the total of each .ask since the last set_global.

§Errors

Returns the EnvError of Client::from_env if there is no global client, and the environment has a bad value.

Source

pub fn ask<Q: QuestionSet, S: Serialize + ?Sized>( &self, question_set: Q, state: &S, ) -> AskFuture<Q> ⓘ

Asks a question set about a state, with this client.

It is the same as Ask::ask, which uses the global client.

§Errors

The future returns an AskError if the request fails.

§Panics

The future panics if it sends a request outside a Tokio runtime.

Source

pub fn ask_with_receipt<Q: QuestionSet, S: Serialize + ?Sized>( &self, question_set: Q, state: &S, ) -> AskWithReceiptFuture<Q> ⓘ

Asks a question set with this client, and returns a Receipt next to the answers.

It is the same as Ask::ask_with_receipt, which uses the global client.

§Errors

The future returns an AskError as Client::ask does.

§Panics

The future panics if it sends a request outside a Tokio runtime.

Trait Implementations§

Source§

impl Clone for Client

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Client

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Client

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl From<Client> for Client

Source§

fn from(client: Client) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl !RefUnwindSafe for Client

§

impl !UnwindSafe for Client

§

impl Forget for Client

§

impl Freeze for Client

§

impl Move for Client

§

impl Send for Client

§

impl Sync for Client

§

impl Unpin for Client

§

impl UnsafeUnpin for Client

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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, 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: Sized + 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: Sized + 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> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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