Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace host string and port with Url #45

Merged
merged 7 commits into from
Apr 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 11 additions & 10 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@ readme = "README.md"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
reqwest = { version = "0.12.3", default-features = false }
serde = { version = "1.0.190", features = ["derive"] }
serde_json = "1.0.116"
reqwest = { version = "0.12.4", default-features = false }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio = { version = "1", features = ["full"], optional = true }
tokio-stream = { version = "0.1.15", optional = true }
url = "2"

[features]
default = ["reqwest/default-tls"]
Expand Down
8 changes: 4 additions & 4 deletions src/generation/chat/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,13 @@ impl Ollama {
let mut request = request;
request.stream = true;

let uri = format!("{}/api/chat", self.uri());
let url = format!("{}api/chat", self.url_str());
let serialized = serde_json::to_string(&request)
.map_err(|e| e.to_string())
.unwrap();
let res = self
.reqwest_client
.post(uri)
.post(url)
.body(serialized)
.send()
.await
Expand Down Expand Up @@ -74,11 +74,11 @@ impl Ollama {
let mut request = request;
request.stream = false;

let uri = format!("{}/api/chat", self.uri());
let url = format!("{}api/chat", self.url_str());
let serialized = serde_json::to_string(&request).map_err(|e| e.to_string())?;
let res = self
.reqwest_client
.post(uri)
.post(url)
.body(serialized)
.send()
.await
Expand Down
8 changes: 4 additions & 4 deletions src/generation/completion/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,11 @@ impl Ollama {
let mut request = request;
request.stream = true;

let uri = format!("{}/api/generate", self.uri());
let url = format!("{}api/generate", self.url_str());
let serialized = serde_json::to_string(&request).map_err(|e| e.to_string())?;
let res = self
.reqwest_client
.post(uri)
.post(url)
.body(serialized)
.send()
.await
Expand Down Expand Up @@ -68,11 +68,11 @@ impl Ollama {
let mut request = request;
request.stream = false;

let uri = format!("{}/api/generate", self.uri());
let url = format!("{}api/generate", self.url_str());
let serialized = serde_json::to_string(&request).map_err(|e| e.to_string())?;
let res = self
.reqwest_client
.post(uri)
.post(url)
.body(serialized)
.send()
.await
Expand Down
4 changes: 2 additions & 2 deletions src/generation/embeddings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ impl Ollama {
options,
};

let uri = format!("{}/api/embeddings", self.uri());
let url = format!("{}api/embeddings", self.url_str());
let serialized = serde_json::to_string(&request).map_err(|e| e.to_string())?;
let res = self
.reqwest_client
.post(uri)
.post(url)
.body(serialized)
.send()
.await
Expand Down
33 changes: 30 additions & 3 deletions src/history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,42 @@ impl Ollama {
}

/// Create new instance with chat history
pub fn new_with_history(host: String, port: u16, messages_number_limit: u16) -> Self {
///
/// # Panics
///
/// Panics if the host is not a valid URL or if the URL cannot have a port.
pub fn new_with_history(
host: impl crate::IntoUrl,
port: u16,
messages_number_limit: u16,
) -> Self {
let mut url = host.into_url().unwrap();
url.set_port(Some(port)).unwrap();
Self::new_with_history_from_url(url, messages_number_limit)
}

/// Create new instance with chat history from a [`url::Url`].
#[inline]
pub fn new_with_history_from_url(url: url::Url, messages_number_limit: u16) -> Self {
Self {
host,
port,
url,
messages_history: Some(MessagesHistory::new(messages_number_limit)),
..Default::default()
}
}

#[inline]
pub fn try_new_with_history(
url: impl crate::IntoUrl,
messages_number_limit: u16,
) -> Result<Self, url::ParseError> {
Ok(Self {
url: url.into_url()?,
messages_history: Some(MessagesHistory::new(messages_number_limit)),
..Default::default()
})
}

/// Add AI's message to a history
pub fn add_assistant_response(&mut self, entry_id: String, message: String) {
if let Some(messages_history) = self.messages_history.as_mut() {
Expand Down
124 changes: 116 additions & 8 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,36 +4,144 @@ pub mod generation;
pub mod history;
pub mod models;

use url::Url;

/// A trait to try to convert some type into a [`Url`].
///
/// This trait is "sealed", such that only types within ollama-rs can
/// implement it.
pub trait IntoUrl: IntoUrlSealed {}

impl IntoUrl for Url {}
impl IntoUrl for String {}
impl<'a> IntoUrl for &'a str {}
impl<'a> IntoUrl for &'a String {}

pub trait IntoUrlSealed {
fn into_url(self) -> Result<Url, url::ParseError>;

fn as_str(&self) -> &str;
}

impl IntoUrlSealed for Url {
fn into_url(self) -> Result<Url, url::ParseError> {
Ok(self)
}

fn as_str(&self) -> &str {
self.as_str()
}
}

impl<'a> IntoUrlSealed for &'a str {
fn into_url(self) -> Result<Url, url::ParseError> {
Url::parse(self)?.into_url()
}

fn as_str(&self) -> &str {
self
}
}

impl<'a> IntoUrlSealed for &'a String {
fn into_url(self) -> Result<Url, url::ParseError> {
(&**self).into_url()
}

fn as_str(&self) -> &str {
self.as_ref()
}
}

impl IntoUrlSealed for String {
fn into_url(self) -> Result<Url, url::ParseError> {
(&*self).into_url()
}

fn as_str(&self) -> &str {
self.as_ref()
}
}

#[derive(Debug, Clone)]
pub struct Ollama {
pub(crate) host: String,
pub(crate) port: u16,
pub(crate) url: Url,
pub(crate) reqwest_client: reqwest::Client,
#[cfg(feature = "chat-history")]
pub(crate) messages_history: Option<history::MessagesHistory>,
}

impl Ollama {
pub fn new(host: String, port: u16) -> Self {
/// # Panics
///
/// Panics if the host is not a valid URL or if the URL cannot have a port.
pub fn new(host: impl IntoUrl, port: u16) -> Self {
let mut url: Url = host.into_url().unwrap();
url.set_port(Some(port)).unwrap();

Self::from_url(url)
}

/// Tries to create new instance by converting `url` into [`Url`].
#[inline]
pub fn try_new(url: impl IntoUrl) -> Result<Self, url::ParseError> {
Ok(Self::from_url(url.into_url()?))
}

/// Create new instance from a [`Url`].
#[inline]
pub fn from_url(url: Url) -> Self {
Self {
host,
port,
url,
..Default::default()
}
}

/// Returns the http URI of the Ollama instance
///
/// # Panics
///
/// Panics if the URL does not have a host.
#[inline]
pub fn uri(&self) -> String {
format!("{}:{}", self.host, self.port)
self.url.host().unwrap().to_string()
}

/// Returns the URL of the Ollama instance as a [`Url`].
pub fn url(&self) -> &Url {
&self.url
}

/// Returns the URL of the Ollama instance as a [str].
///
/// Syntax in pseudo-BNF:
///
/// ```bnf
/// url = scheme ":" [ hierarchical | non-hierarchical ] [ "?" query ]? [ "#" fragment ]?
/// non-hierarchical = non-hierarchical-path
/// non-hierarchical-path = /* Does not start with "/" */
/// hierarchical = authority? hierarchical-path
/// authority = "//" userinfo? host [ ":" port ]?
/// userinfo = username [ ":" password ]? "@"
/// hierarchical-path = [ "/" path-segment ]+
/// ```
#[inline]
pub fn url_str(&self) -> &str {
self.url.as_str()
}
}

impl From<Url> for Ollama {
fn from(url: Url) -> Self {
Self::from_url(url)
}
}

impl Default for Ollama {
/// Returns a default Ollama instance with the host set to `http://127.0.0.1:11434`.
fn default() -> Self {
Self {
host: "http://127.0.0.1".to_string(),
port: 11434,
url: Url::parse("http://127.0.0.1:11434").unwrap(),
reqwest_client: reqwest::Client::new(),
#[cfg(feature = "chat-history")]
messages_history: None,
Expand Down
4 changes: 2 additions & 2 deletions src/models/copy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ impl Ollama {
destination,
};

let uri = format!("{}/api/copy", self.uri());
let url = format!("{}api/copy", self.url_str());
let serialized = serde_json::to_string(&request).map_err(|e| e.to_string())?;
let res = self
.reqwest_client
.post(uri)
.post(url)
.body(serialized)
.send()
.await
Expand Down
8 changes: 4 additions & 4 deletions src/models/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ impl Ollama {

request.stream = true;

let uri = format!("{}/api/create", self.uri());
let url = format!("{}api/create", self.url_str());
let serialized = serde_json::to_string(&request).map_err(|e| e.to_string())?;
let res = self
.reqwest_client
.post(uri)
.post(url)
.body(serialized)
.send()
.await
Expand Down Expand Up @@ -63,11 +63,11 @@ impl Ollama {
&self,
request: CreateModelRequest,
) -> crate::error::Result<CreateModelStatus> {
let uri = format!("{}/api/create", self.uri());
let url = format!("{}api/create", self.url_str());
let serialized = serde_json::to_string(&request).map_err(|e| e.to_string())?;
let res = self
.reqwest_client
.post(uri)
.post(url)
.body(serialized)
.send()
.await
Expand Down
Loading
Loading