aleph_alpha_client/stream.rs
1use reqwest::RequestBuilder;
2use serde::Deserialize;
3
4use crate::http::MethodJob;
5
6/// A job send to the Aleph Alpha Api using the http client. A job wraps all the knowledge required
7/// for the Aleph Alpha API to specify its result. Notably it includes the model(s) the job is
8/// executed on. This allows this trait to hold in the presence of services, which use more than one
9/// model and task type to achieve their result. On the other hand a bare [`crate::TaskCompletion`]
10/// can not implement this trait directly, since its result would depend on what model is chosen to
11/// execute it. You can remedy this by turning completion task into a job, calling
12/// [`Task::with_model`].
13pub trait StreamJob {
14 /// Output returned by [`crate::Client::output_of`]
15 type Output: Send;
16
17 /// Expected answer of the Aleph Alpha API
18 type ResponseBody: for<'de> Deserialize<'de> + Send;
19
20 /// Prepare the request for the Aleph Alpha API. Authentication headers can be assumed to be
21 /// already set.
22 fn build_request(&self, client: &reqwest::Client, base: &str) -> RequestBuilder;
23
24 /// Parses the response of the server into higher level structs for the user.
25 fn body_to_output(&self, response: Self::ResponseBody) -> Self::Output;
26}
27
28/// A task send to the Aleph Alpha Api using the http client. Requires to specify a model before it
29/// can be executed. Will return a stream of results.
30pub trait StreamTask {
31 /// Output returned by [`crate::Client::output_of`]
32 type Output: Send;
33
34 /// Expected answer of the Aleph Alpha API
35 type ResponseBody: for<'de> Deserialize<'de> + Send;
36
37 /// Prepare the request for the Aleph Alpha API. Authentication headers can be assumed to be
38 /// already set.
39 fn build_request(&self, client: &reqwest::Client, base: &str, model: &str) -> RequestBuilder;
40
41 /// Parses the response of the server into higher level structs for the user.
42 fn body_to_output(&self, response: Self::ResponseBody) -> Self::Output;
43
44 /// Turn your task into [`Job`] by annotating it with a model name.
45 fn with_model<'a>(&'a self, model: &'a str) -> MethodJob<'a, Self>
46 where
47 Self: Sized,
48 {
49 MethodJob { model, task: self }
50 }
51}
52
53impl<T> StreamJob for MethodJob<'_, T>
54where
55 T: StreamTask,
56{
57 type Output = T::Output;
58
59 type ResponseBody = T::ResponseBody;
60
61 fn build_request(&self, client: &reqwest::Client, base: &str) -> RequestBuilder {
62 self.task.build_request(client, base, self.model)
63 }
64
65 fn body_to_output(&self, response: T::ResponseBody) -> T::Output {
66 self.task.body_to_output(response)
67 }
68}