Skip to content
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
1 change: 1 addition & 0 deletions Cargo.lock

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

8 changes: 7 additions & 1 deletion crates/goose-providers/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ uuid = { workspace = true, features = ["v4", "std"] }
async-trait = { workspace = true }
strum = { workspace = true }
tokio = { workspace = true }
tokio-stream = { workspace = true, features = ["io-util"] }
tokio-util = { workspace = true, features = ["compat"] }
rand = { workspace = true }
url = { workspace = true }
pem = { version = "3.0.2", default-features = false, features = ["std"], optional = true }
Expand All @@ -56,6 +58,10 @@ sec1 = { version = "0.7", default-features = false, features = ["der", "pkcs8",
[dev-dependencies]
test-case = { workspace = true }
tempfile = { workspace = true }
tokio = { workspace = true }
tokio = { workspace = true, features = ["rt-multi-thread"] }
tokio-stream = { workspace = true }
env-lock = { workspace = true }

[[example]]
name = "streaming"
required-features = ["rustls-tls"]
43 changes: 43 additions & 0 deletions crates/goose-providers/examples/streaming.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use std::env;

use anyhow::Result;
use futures::StreamExt;
use goose_providers::{
api_client::{ApiClient, AuthMethod},
base::Provider,
conversation::message::Message,
model::ModelConfig,
openai::OpenAiProvider,
};

#[tokio::main]
async fn main() -> Result<()> {
let model = ModelConfig::new("gpt-5.4-mini")?;
let key = env::var("OPENAI_API_KEY").map_err(|_| anyhow::anyhow!("need an OpenAI key"))?;
let api_client = ApiClient::new_with_tls(
"https://api.openai.com".to_string(),
AuthMethod::BearerToken(key),
Some(Default::default()),
)?;
let provider = OpenAiProvider::new(api_client, model.clone());

let system = "You are a knowledgable geography expert";
let messages = [Message::user().with_text("what is the capital of France?")];

let mut stream = provider
.stream(
&model,
"", // session-id
system,
&messages,
&[],
)
.await?;

while let Some((Some(msg), _)) = stream.next().await.transpose()? {
print!("{}", msg.as_concat_text());
}
println!();

Ok(())
}
191 changes: 191 additions & 0 deletions crates/goose-providers/src/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,193 @@ use crate::{
retry::RetryConfig,
};

/// Metadata about a provider's configuration requirements and capabilities
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct ProviderMetadata {
/// The unique identifier for this provider
pub name: String,
/// Display name for the provider in UIs
pub display_name: String,
/// Description of the provider's capabilities
pub description: String,
/// The default/recommended model for this provider
pub default_model: String,
/// A list of currently known models with their capabilities
pub known_models: Vec<ModelInfo>,
/// Link to the docs where models can be found
pub model_doc_link: String,
/// Required configuration keys
pub config_keys: Vec<ConfigKey>,
/// step-by-step instructions for set up providers eg: api key
#[serde(default)]
pub setup_steps: Vec<String>,
/// Hint shown in the model picker when this provider manages its own model selection.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub model_selection_hint: Option<String>,
}

impl ProviderMetadata {
pub fn new(
name: &str,
display_name: &str,
description: &str,
default_model: &str,
model_names: Vec<&str>,
model_doc_link: &str,
config_keys: Vec<ConfigKey>,
) -> Self {
Self {
name: name.to_string(),
display_name: display_name.to_string(),
description: description.to_string(),
default_model: default_model.to_string(),
known_models: model_names
.iter()
.map(|&model_name| model_info_for_provider_model(name, model_name))
.collect(),
model_doc_link: model_doc_link.to_string(),
config_keys,
setup_steps: vec![],
model_selection_hint: None,
}
}

pub fn with_models(
name: &str,
display_name: &str,
description: &str,
default_model: &str,
models: Vec<ModelInfo>,
model_doc_link: &str,
config_keys: Vec<ConfigKey>,
) -> Self {
Self {
name: name.to_string(),
display_name: display_name.to_string(),
description: description.to_string(),
default_model: default_model.to_string(),
known_models: models,
model_doc_link: model_doc_link.to_string(),
config_keys,
setup_steps: vec![],
model_selection_hint: None,
}
}

pub fn empty() -> Self {
Self {
name: "".to_string(),
display_name: "".to_string(),
description: "".to_string(),
default_model: "".to_string(),
known_models: vec![],
model_doc_link: "".to_string(),
config_keys: vec![],
setup_steps: vec![],
model_selection_hint: None,
}
}

pub fn with_setup_steps(mut self, steps: Vec<&str>) -> Self {
self.setup_steps = steps.into_iter().map(|s| s.to_string()).collect();
self
}

pub fn with_model_selection_hint(mut self, hint: &str) -> Self {
self.model_selection_hint = Some(hint.to_string());
self
}
}

/// Configuration key metadata for provider setup
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct ConfigKey {
/// The name of the configuration key (e.g., "API_KEY")
pub name: String,
/// Whether this key is required for the provider to function
pub required: bool,
/// Whether this key should be stored securely (e.g., in keychain)
pub secret: bool,
/// Optional default value for the key
pub default: Option<String>,
/// Whether this key should be configured using an OAuth flow
/// When true, the provider's configure_oauth() method will be called instead of prompting for manual input
pub oauth_flow: bool,
/// Whether this OAuth flow uses the device code grant (RFC 8628)
/// When true, the user must enter a verification code in the browser
#[serde(default)]
pub device_code_flow: bool,
/// Whether this key should be shown prominently during provider setup
/// (onboarding, settings modal, CLI configure)
#[serde(default)]
pub primary: bool,
}

impl ConfigKey {
/// Create a new ConfigKey
pub fn new(
name: &str,
required: bool,
secret: bool,
default: Option<&str>,
primary: bool,
) -> Self {
Self {
name: name.to_string(),
required,
secret,
default: default.map(|s| s.to_string()),
oauth_flow: false,
device_code_flow: false,
primary,
}
}

/// Create a new ConfigKey that uses an OAuth flow for configuration
///
/// This is used for providers that support OAuth authentication instead of manual API key entry.
/// When oauth_flow is true, the configuration system will call the provider's configure_oauth() method.
pub fn new_oauth(
name: &str,
required: bool,
secret: bool,
default: Option<&str>,
primary: bool,
) -> Self {
Self {
name: name.to_string(),
required,
secret,
default: default.map(|s| s.to_string()),
oauth_flow: true,
device_code_flow: false,
primary,
}
}

/// Create a new ConfigKey that uses OAuth device code flow (RFC 8628) for configuration
///
/// Similar to new_oauth, but indicates the provider uses the device code grant where the user
/// must enter a verification code in the browser.
pub fn new_oauth_device_code(
name: &str,
required: bool,
secret: bool,
default: Option<&str>,
primary: bool,
) -> Self {
Self {
name: name.to_string(),
required,
secret,
default: default.map(|s| s.to_string()),
oauth_flow: true,
device_code_flow: true,
primary,
}
}
}

/// Information about a model's capabilities
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq)]
pub struct ModelInfo {
Expand Down Expand Up @@ -76,6 +263,10 @@ impl ModelInfo {
}
}

pub trait ProviderDescriptor {
fn metadata() -> ProviderMetadata;
}

/// A message stream yields partial text content but complete tool calls, all within the Message object
/// So a message with text will contain potentially just a word of a longer response, but tool calls
/// messages will only be yielded once concatenated.
Expand Down
1 change: 1 addition & 0 deletions crates/goose-providers/src/formats.rs
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
pub mod openai;
pub mod openai_responses;
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
use crate::conversation::message::{Message, MessageContent};
use crate::conversation::token_usage::{ProviderUsage, Usage};
use crate::errors::ProviderError;
use crate::formats::openai::{
extract_reasoning_effort, is_openai_responses_model, openai_reasoning_effort_for_thinking,
};
use crate::mcp_utils::extract_text_from_resource;
use crate::model::ModelConfig;
use anyhow::Error;
use async_stream::try_stream;
use chrono;
use futures::Stream;
use goose_providers::conversation::token_usage::{ProviderUsage, Usage};
use goose_providers::errors::ProviderError;
use goose_providers::formats::openai::{
extract_reasoning_effort, is_openai_responses_model, openai_reasoning_effort_for_thinking,
};
use goose_providers::model::ModelConfig;
use rmcp::model::{object, CallToolRequestParams, RawContent, Role, Tool};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
Expand Down Expand Up @@ -962,8 +962,8 @@ where
mod tests {
use super::*;
use crate::conversation::message::MessageContent;
use crate::model::ModelConfig;
use futures::StreamExt;
use goose_providers::model::ModelConfig;
use rmcp::model::CallToolRequestParams;
use rmcp::object;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@

use std::time::{Duration, SystemTime};

use crate::errors::ProviderError;
use chrono::{DateTime, NaiveDateTime, TimeZone, Utc};
use goose_providers::errors::ProviderError;
use reqwest::header::{HeaderMap, RETRY_AFTER};
use reqwest::{Response, StatusCode};
use serde_json::Value;
Expand Down Expand Up @@ -107,7 +107,7 @@ fn parse_http_date(value: &str) -> Option<SystemTime> {
None
}

pub(crate) fn is_context_length_exceeded_message(text: &str) -> bool {
pub fn is_context_length_exceeded_message(text: &str) -> bool {
let text_lower = text.to_lowercase();

let direct_context_phrases = [
Expand Down
3 changes: 3 additions & 0 deletions crates/goose-providers/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,13 @@ pub mod conversation;
pub mod errors;
pub mod formats;
pub mod goose_mode;
pub mod http_status;
pub mod images;
pub mod json;
pub(crate) mod mcp_utils;
pub mod model;
pub mod openai;
pub mod openai_compatible;
pub mod permission;
pub mod request_log;
pub mod retry;
Expand Down
Loading
Loading