feat(live-voice): configurable GPT-Live endpoint, model and key (#13360)

Signed-off-by: Tyler Longwell <tlongwell@squareup.com>
Co-authored-by: Eva <011987e296fd5006292d2f930b574be47c7801048d1983c46c425d3c95f0cffd@buzz.block.builderlab.xyz>
This commit is contained in:
Tyler
2026-11-08 00:41:28 +00:00
committed by GitHub
parent 4facf56cba
commit 5bad61a87c
9 changed files with 484 additions and 38 deletions
+1 -1
View File
@@ -86,7 +86,7 @@ jobs:
cargo build -p goose --bin goose-acp \
--profile lean \
--no-default-features \
--features rustls-tls,system-keyring,online-model-meta \
--features rustls-tls,system-keyring,online-model-meta,live-voice \
--target "$TARGET"
- name: Verify macOS system library dependencies
+105 -1
View File
@@ -230,6 +230,31 @@ impl OpenAiLiveClient {
self
}
/// Points signaling at a GPT-Live compatible sessions URL, such as
/// `https://host/v1/live/sessions`; the sideband uses the same URL over `ws(s)`.
pub fn with_endpoint(self, endpoint: &str) -> Result<Self> {
let mut url = url::Url::parse(endpoint.trim())?;
let websocket_scheme = match url.scheme() {
"https" => "wss",
"http" => "ws",
_ => bail!("OpenAI Live endpoint must be an http or https URL"),
};
// The parser already refuses an http(s) URL without a host.
if !url.username().is_empty()
|| url.password().is_some()
|| url.query().is_some()
|| url.fragment().is_some()
{
bail!("OpenAI Live endpoint must not carry credentials, a query or a fragment");
}
let http_endpoint = url.to_string();
url.set_scheme(websocket_scheme)
.map_err(|_| anyhow::anyhow!("OpenAI Live endpoint has no WebSocket form"))?;
Ok(self
.with_http_endpoint(http_endpoint)
.with_websocket_endpoint(url.to_string()))
}
pub fn with_tls_config(mut self, tls_config: TlsConfig) -> Self {
self.tls_config = Some(tls_config);
self
@@ -448,7 +473,9 @@ impl OpenAiLiveWebRtcConnector {
) -> Result<OpenAiLiveWebRtcNegotiation> {
let client = self.client.clone();
let request = self.request(offer_sdp)?;
let mut http_request = ApiClient::http_client(client.tls_config.as_ref())?
let mut http_request = ApiClient::http_client_builder(client.tls_config.as_ref())?
.redirect(reqwest::redirect::Policy::none())
.build()?
.post(request.endpoint)
.json(&json!({
"session": request.session,
@@ -960,6 +987,83 @@ mod tests {
assert_eq!(negotiation.answer_sdp, "answer-sdp");
}
#[test]
fn a_custom_endpoint_is_a_plain_http_or_https_url() {
let client = OpenAiLiveClient::new("key")
.with_endpoint("HTTP://Voice.Example:8080/v1/live/sessions/")
.unwrap();
assert_eq!(
client.http_endpoint,
"http://voice.example:8080/v1/live/sessions/"
);
assert_eq!(
client
.existing_session(OpenAiLiveSessionId("session_1".into()))
.request()
.unwrap()
.endpoint,
"ws://voice.example:8080/v1/live/sessions/session_1/attach"
);
let client = OpenAiLiveClient::new("key")
.with_endpoint("https://example.com/v1/live/sessions")
.unwrap();
assert_eq!(
client.websocket_endpoint,
"wss://example.com/v1/live/sessions"
);
for endpoint in [
"",
"example.com/v1/live/sessions",
"ftp://example.com/v1/live/sessions",
"ws://example.com/v1/live/sessions",
"http://",
"http://:19137/v1/live/sessions",
"http://user@example.com/v1/live/sessions",
"http://user:pass@example.com/v1/live/sessions",
"http://example.com/v1/live/sessions?x=1",
"http://example.com/v1/live/sessions#x",
] {
assert!(
OpenAiLiveClient::new("key")
.with_endpoint(endpoint)
.is_err(),
"{endpoint}"
);
}
}
#[tokio::test]
async fn webrtc_negotiation_does_not_follow_redirects() {
let server = MockServer::start().await;
let elsewhere = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/v1/live/sessions"))
.respond_with(
ResponseTemplate::new(307)
.insert_header("location", format!("{}/v1/live/sessions", elsewhere.uri())),
)
.mount(&server)
.await;
Mock::given(method("POST"))
.respond_with(ResponseTemplate::new(201).set_body_json(json!({
"session": { "id": "session_1" },
"transport": { "type": "webrtc", "sdp": "answer-sdp" }
})))
.expect(0)
.mount(&elsewhere)
.await;
let result = OpenAiLiveClient::new("test-key")
.with_endpoint(&format!("{}/v1/live/sessions", server.uri()))
.unwrap()
.webrtc(config())
.negotiate("offer-sdp")
.await;
assert!(result.is_err());
}
#[test]
fn session_identity_must_not_be_empty() {
let error = OpenAiLiveProtocol
@@ -28,6 +28,7 @@ const SIDEBAND_ATTACH_TIMEOUT: Duration = Duration::from_secs(10);
const DELEGATION_UPDATE_ACK_TIMEOUT: Duration = Duration::from_secs(10);
pub struct OpenAiLiveVoiceProvider {
client: OpenAiLiveClient,
model: String,
voice: String,
instructions: String,
delivery_failure_instructions: String,
@@ -49,6 +50,7 @@ impl OpenAiLiveVoiceProvider {
}
Ok(Self {
client: OpenAiLiveClient::new(api_key),
model: OPENAI_LIVE_MODEL.into(),
voice,
instructions,
delivery_failure_instructions,
@@ -59,6 +61,16 @@ impl OpenAiLiveVoiceProvider {
self.client = self.client.with_tls_config(tls_config);
self
}
pub fn with_model(mut self, model: String) -> Self {
self.model = model;
self
}
pub fn with_endpoint(mut self, endpoint: &str) -> Result<Self> {
self.client = self.client.with_endpoint(endpoint)?;
Ok(self)
}
}
#[async_trait]
@@ -69,7 +81,7 @@ impl LiveVoiceProvider for OpenAiLiveVoiceProvider {
input_messages: Vec<LiveVoiceInputMessage>,
) -> Result<(WebRtcAnswer, Box<dyn ProviderConnection>)> {
let config = OpenAiLiveSessionConfig {
model: OPENAI_LIVE_MODEL.into(),
model: self.model.clone(),
instructions: self.instructions.clone(),
voice: Some(self.voice.clone()),
input_messages: input_messages
+2 -1
View File
@@ -84,7 +84,8 @@ use url::Url;
use uuid::Uuid;
use self::message_meta::{
content_chunk_for_message, message_meta_without_steer, populate_output_token_limit_content,
content_chunk_for_message, live_transcript_chunk, message_meta_without_steer,
populate_output_token_limit_content,
};
use self::tool_calls::chain::{breaks_consecutive_tool_calls, ReadyToolChain, ToolChainTracker};
use self::tool_calls::conversion::{
+1 -1
View File
@@ -107,7 +107,7 @@ impl AcpConnection {
let [MessageContent::Text(text)] = message.content.as_slice() else {
return;
};
let chunk = content_chunk_for_message(
let chunk = live_transcript_chunk(
&message,
ContentBlock::Text(TextContent::new(text.text.clone())),
);
@@ -102,6 +102,16 @@ pub(super) fn content_chunk_for_message(message: &Message, content: ContentBlock
chunk
}
pub(super) fn live_transcript_chunk(message: &Message, content: ContentBlock) -> ContentChunk {
let mut chunk = content_chunk_for_message(message, content);
if let Some(serde_json::Value::Object(goose)) =
chunk.meta.as_mut().and_then(|meta| meta.get_mut("goose"))
{
goose.insert("liveTranscript".into(), true.into());
}
chunk
}
pub(super) fn populate_output_token_limit_content(message: &mut Message) {
if message.role != rmcp::model::Role::Assistant
|| !message.content.is_empty()
@@ -131,6 +141,27 @@ mod tests {
use agent_client_protocol::schema::v1::TextContent;
use rmcp::model::Role;
#[test]
fn live_transcript_chunks_are_marked() {
let message = Message::new(Role::User, 1_700_000_000, vec![]).with_id("msg_live_1");
let content = || ContentBlock::Text(TextContent::new("hi"));
assert_eq!(
live_transcript_chunk(&message, content())
.meta
.and_then(|meta| meta.get("goose").cloned()),
Some(serde_json::json!({
"created": 1_700_000_000,
"messageId": "msg_live_1",
"liveTranscript": true,
})),
);
assert!(content_chunk_for_message(&message, content())
.meta
.and_then(|meta| meta.get("goose").cloned())
.is_some_and(|goose| goose.get("liveTranscript").is_none()));
}
#[test]
fn message_meta_serializes_message_fields() {
let message = Message::new(Role::Assistant, 1_700_000_000, vec![]).with_id("msg_live");
+64 -20
View File
@@ -794,6 +794,28 @@ impl Config {
}
}
/// Like `get_param`, but an unreadable config file or a non-Unicode environment value is
/// an error rather than a missing key.
pub(crate) fn get_param_strict<T: for<'de> Deserialize<'de>>(
&self,
key: &str,
) -> Result<T, ConfigError> {
let env_key = key.to_uppercase();
match env::var(&env_key) {
Ok(value) => Ok(serde_json::from_value(Self::parse_env_value(&value)?)?),
Err(env::VarError::NotPresent) => {
let value = self
.load_strict()?
.remove(key)
.ok_or_else(|| ConfigError::NotFound(key.to_string()))?;
Ok(serde_yaml::from_value(value)?)
}
Err(env::VarError::NotUnicode(_)) => Err(ConfigError::DeserializeError(format!(
"{env_key} contains non-Unicode data"
))),
}
}
pub(crate) fn get_param_source_values<T: for<'de> Deserialize<'de>>(
&self,
key: &str,
@@ -933,6 +955,22 @@ impl Config {
.and_then(|v| Ok(serde_json::from_value(v.clone())?))
}
/// Like `get_secret`, but reads storage without the process's secrets cache, so a value
/// another process wrote since is seen. Leaves the cache and `generation` untouched.
pub fn get_secret_uncached<T: for<'de> Deserialize<'de>>(
&self,
key: &str,
) -> Result<T, ConfigError> {
if let Ok(val) = env::var(key.to_uppercase()) {
return Ok(serde_json::from_value(Self::parse_env_value(&val)?)?);
}
let value = self
.load_secrets_from_storage()?
.remove(key)
.ok_or_else(|| ConfigError::NotFound(key.to_string()))?;
Ok(serde_json::from_value(value)?)
}
/// Get secrets. If primary is in env, use env for all keys. Otherwise, use secret storage.
pub fn get_secrets(
&self,
@@ -1277,31 +1315,12 @@ config_value!(GOOSE_SEARCH_PATHS, Vec<String>);
config_value!(GOOSE_MODE, GooseMode);
impl Config {
pub(crate) fn resolve_goose_mode(&self) -> Result<GooseMode, ConfigError> {
match self.get_goose_mode_strict() {
match self.get_param_strict("GOOSE_MODE") {
Ok(mode) => Ok(mode),
Err(ConfigError::NotFound(_)) => Ok(GooseMode::Auto),
Err(error) => Err(error),
}
}
pub(crate) fn get_goose_mode_strict(&self) -> Result<GooseMode, ConfigError> {
match env::var("GOOSE_MODE") {
Ok(value) => {
let value = Self::parse_env_value(&value)?;
Ok(serde_json::from_value(value)?)
}
Err(env::VarError::NotPresent) => {
let values = self.load_strict()?;
let value = values
.get("GOOSE_MODE")
.ok_or_else(|| ConfigError::NotFound("GOOSE_MODE".to_string()))?;
Ok(serde_yaml::from_value(value.clone())?)
}
Err(env::VarError::NotUnicode(_)) => Err(ConfigError::DeserializeError(
"GOOSE_MODE contains non-Unicode data".to_string(),
)),
}
}
}
// GOOSE_PROVIDER and GOOSE_MODEL are handled by crate::config::providers
// which checks the structured `providers:` block first and falls back to
@@ -1805,6 +1824,31 @@ mod tests {
Ok(())
}
#[test]
fn uncached_secret_reads_see_other_writers_without_touching_the_cache(
) -> Result<(), ConfigError> {
let directory = TempDir::new().unwrap();
let config_path = directory.path().join("config.yaml");
let secrets_path = directory.path().join("secrets.yaml");
let first = Config::new_with_file_secrets(&config_path, &secrets_path)?;
let second = Config::new_with_file_secrets(&config_path, &secrets_path)?;
first.set_secret("key", &"initial")?;
assert_eq!(first.get_secret::<String>("key")?, "initial");
let generation = first.generation();
second.set_secret("key", &"updated")?;
assert_eq!(first.get_secret_uncached::<String>("key")?, "updated");
assert_eq!(first.get_secret::<String>("key")?, "initial");
assert_eq!(first.generation(), generation);
assert!(matches!(
first.get_secret_uncached::<String>("missing"),
Err(ConfigError::NotFound(_))
));
Ok(())
}
#[test]
fn test_concurrent_writes() -> Result<(), ConfigError> {
use std::sync::{Arc, Barrier, Mutex};
+73 -13
View File
@@ -23,7 +23,14 @@ const LIVE_VOICE_ENABLED_CONFIG_KEY: &str = "GOOSE_LIVE_VOICE_ENABLED";
#[cfg(feature = "live-voice")]
const LIVE_VOICE_CONFIG_KEY: &str = "GOOSE_LIVE_VOICE";
#[cfg(feature = "live-voice")]
const LIVE_VOICE_ENDPOINT_CONFIG_KEY: &str = "GOOSE_LIVE_VOICE_ENDPOINT";
#[cfg(feature = "live-voice")]
const LIVE_VOICE_MODEL_CONFIG_KEY: &str = "GOOSE_LIVE_VOICE_MODEL";
#[cfg(feature = "live-voice")]
const LIVE_VOICE_API_KEY_CONFIG_KEY: &str = "GOOSE_LIVE_VOICE_API_KEY";
#[cfg(feature = "live-voice")]
const DEFAULT_OPENAI_LIVE_VOICE: &str = "marin";
#[cfg(feature = "live-voice")]
const LIVE_SESSION_INSTRUCTIONS: &str = concat!(
"You are Goose's live voice interface. Keep the conversation natural and concise.\n",
@@ -356,33 +363,86 @@ fn configured_live_voice_enabled() -> bool {
})
}
#[cfg(feature = "live-voice")]
#[derive(Debug, PartialEq)]
struct LiveVoiceSettings {
api_key: String,
endpoint: Option<String>,
model: Option<String>,
voice: String,
}
#[cfg(feature = "live-voice")]
fn live_voice_settings(config: &crate::config::Config) -> Result<LiveVoiceSettings, &'static str> {
// Only an absent or blank endpoint means OpenAI; an unreadable one, or an unreadable
// config file that might hold it, must not.
let endpoint = match config.get_param_strict::<String>(LIVE_VOICE_ENDPOINT_CONFIG_KEY) {
Ok(endpoint) => Some(endpoint).filter(|endpoint| !endpoint.trim().is_empty()),
Err(crate::config::ConfigError::NotFound(_)) => None,
Err(_) => return Err("Live voice endpoint is invalid"),
};
// A custom endpoint only ever receives its own key: OPENAI_API_KEY must not leave for
// another server, which is also what makes a plain-http endpoint acceptable.
let api_key_name = if endpoint.is_some() {
LIVE_VOICE_API_KEY_CONFIG_KEY
} else {
"OPENAI_API_KEY"
};
// Read past the secrets cache: another process may have saved the key since.
let api_key = config
.get_secret_uncached::<String>(api_key_name)
.map_err(|_| "Live voice provider is not configured")?;
let model = config
.get_param::<String>(LIVE_VOICE_MODEL_CONFIG_KEY)
.ok()
.filter(|model| !model.trim().is_empty());
let voice = config
.get_param::<String>(LIVE_VOICE_CONFIG_KEY)
.unwrap_or_else(|_| DEFAULT_OPENAI_LIVE_VOICE.into());
Ok(LiveVoiceSettings {
api_key,
endpoint,
model,
voice,
})
}
#[cfg(feature = "live-voice")]
fn configured_live_voice() -> Result<Arc<dyn LiveVoiceProvider>, &'static str> {
if !configured_live_voice_enabled() {
return Err("Live voice is disabled");
}
Ok(Arc::new(live_voice_provider(
crate::config::Config::global(),
)?))
}
let config = crate::config::Config::global();
let api_key = config
.get_secret::<String>("OPENAI_API_KEY")
.map_err(|_| "Live voice provider is not configured")?;
let voice = config
.get_param::<String>(LIVE_VOICE_CONFIG_KEY)
.unwrap_or_else(|_| DEFAULT_OPENAI_LIVE_VOICE.into());
#[cfg(feature = "live-voice")]
fn live_voice_provider(
config: &crate::config::Config,
) -> Result<OpenAiLiveVoiceProvider, &'static str> {
let settings = live_voice_settings(config)?;
let tls_config = crate::config::tls::provider_tls_config_from_config(config)
.map_err(|_| "Live voice TLS configuration is invalid")?;
let provider = OpenAiLiveVoiceProvider::new(
api_key,
voice,
let mut provider = OpenAiLiveVoiceProvider::new(
settings.api_key,
settings.voice,
LIVE_SESSION_INSTRUCTIONS.into(),
DELEGATION_DELIVERY_FAILURE_INSTRUCTIONS.into(),
)
.map_err(|_| "Live voice provider is not configured")?;
let provider = match tls_config {
if let Some(model) = settings.model {
provider = provider.with_model(model);
}
if let Some(endpoint) = settings.endpoint {
provider = provider
.with_endpoint(&endpoint)
.map_err(|_| "Live voice endpoint is invalid")?;
}
Ok(match tls_config {
Some(tls_config) => provider.with_tls_config(tls_config),
None => provider,
};
Ok(Arc::new(provider))
})
}
#[cfg(not(feature = "live-voice"))]
@@ -1187,3 +1187,197 @@ fn stale_cleanup_cannot_remove_a_later_call() {
));
assert!(active_runs.is_active("main-session"));
}
#[cfg(feature = "live-voice")]
mod settings {
use super::super::{live_voice_provider, live_voice_settings};
use crate::config::Config;
use goose_providers::live_voice_provider::{LiveVoiceProvider, WebRtcOffer};
use tempfile::TempDir;
use wiremock::{
matchers::{header, method, path},
Mock, MockServer, ResponseTemplate,
};
const ENV: [(&str, Option<&str>); 5] = [
("OPENAI_API_KEY", None),
("GOOSE_LIVE_VOICE_ENDPOINT", None),
("GOOSE_LIVE_VOICE_MODEL", None),
("GOOSE_LIVE_VOICE_API_KEY", None),
("GOOSE_LIVE_VOICE", None),
];
const ENDPOINT: &str = "http://192.0.2.10:8080/v1/live/sessions";
fn config(directory: &TempDir) -> Config {
Config::new_with_file_secrets(
directory.path().join("config.yaml"),
directory.path().join("secrets.yaml"),
)
.unwrap()
}
#[test]
fn without_an_endpoint_the_openai_key_and_defaults_are_used() {
let _env = env_lock::lock_env(ENV);
for endpoint in [None, Some(""), Some(" ")] {
let directory = TempDir::new().unwrap();
let config = config(&directory);
config.set_secret("OPENAI_API_KEY", &"openai-key").unwrap();
config
.set_secret("GOOSE_LIVE_VOICE_API_KEY", &"voice-key")
.unwrap();
if let Some(endpoint) = endpoint {
config
.set_param("GOOSE_LIVE_VOICE_ENDPOINT", endpoint)
.unwrap();
}
let settings = live_voice_settings(&config).unwrap();
assert_eq!(settings.api_key, "openai-key");
assert_eq!(settings.endpoint, None);
assert_eq!(settings.model, None);
assert_eq!(settings.voice, "marin");
}
}
#[test]
fn a_custom_endpoint_never_receives_the_openai_key() {
let _env = env_lock::lock_env(ENV);
let directory = TempDir::new().unwrap();
let config = config(&directory);
config.set_secret("OPENAI_API_KEY", &"openai-key").unwrap();
config
.set_param("GOOSE_LIVE_VOICE_ENDPOINT", ENDPOINT)
.unwrap();
assert_eq!(
live_voice_settings(&config),
Err("Live voice provider is not configured")
);
}
#[test]
fn an_unreadable_endpoint_does_not_fall_back_to_openai() {
let _env = env_lock::lock_env(ENV);
for contents in [
format!("GOOSE_LIVE_VOICE_ENDPOINT: [{ENDPOINT}]\n"),
format!("GOOSE_LIVE_VOICE_ENDPOINT: {ENDPOINT}: [\n"),
] {
let directory = TempDir::new().unwrap();
let config = config(&directory);
config.set_secret("OPENAI_API_KEY", &"openai-key").unwrap();
std::fs::write(directory.path().join("config.yaml"), &contents).unwrap();
assert_eq!(
live_voice_settings(&config),
Err("Live voice endpoint is invalid"),
"{contents}"
);
}
}
#[cfg(unix)]
#[test]
fn a_non_unicode_endpoint_variable_does_not_fall_back_to_openai() {
use std::os::unix::ffi::OsStrExt;
let _env = env_lock::lock_env(ENV);
let directory = TempDir::new().unwrap();
let config = config(&directory);
config.set_secret("OPENAI_API_KEY", &"openai-key").unwrap();
std::env::set_var(
"GOOSE_LIVE_VOICE_ENDPOINT",
std::ffi::OsStr::from_bytes(b"\xff\xfe"),
);
assert_eq!(
live_voice_settings(&config),
Err("Live voice endpoint is invalid")
);
}
#[test]
fn a_custom_endpoint_uses_its_own_key_and_model() {
let _env = env_lock::lock_env(ENV);
let directory = TempDir::new().unwrap();
let config = config(&directory);
config.set_secret("OPENAI_API_KEY", &"openai-key").unwrap();
config
.set_secret("GOOSE_LIVE_VOICE_API_KEY", &"voice-key")
.unwrap();
config
.set_param("GOOSE_LIVE_VOICE_ENDPOINT", ENDPOINT)
.unwrap();
config
.set_param("GOOSE_LIVE_VOICE_MODEL", "custom-live-model")
.unwrap();
let settings = live_voice_settings(&config).unwrap();
assert_eq!(settings.api_key, "voice-key");
assert_eq!(settings.endpoint.as_deref(), Some(ENDPOINT));
assert_eq!(settings.model.as_deref(), Some("custom-live-model"));
}
#[tokio::test]
async fn a_custom_endpoint_receives_its_key_and_model() {
let _env = env_lock::lock_env(ENV);
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/v1/live/sessions"))
.and(header("authorization", "Bearer voice-key"))
.respond_with(ResponseTemplate::new(503))
.expect(1)
.mount(&server)
.await;
let directory = TempDir::new().unwrap();
let config = config(&directory);
config.set_secret("OPENAI_API_KEY", &"openai-key").unwrap();
config
.set_secret("GOOSE_LIVE_VOICE_API_KEY", &"voice-key")
.unwrap();
config
.set_param(
"GOOSE_LIVE_VOICE_ENDPOINT",
format!("{}/v1/live/sessions", server.uri()),
)
.unwrap();
config
.set_param("GOOSE_LIVE_VOICE_MODEL", "custom-live-model")
.unwrap();
let start = live_voice_provider(&config)
.unwrap()
.start(WebRtcOffer::new("offer-sdp".into()).unwrap(), vec![])
.await;
assert!(start.is_err());
let requests = server.received_requests().await.unwrap();
let body: serde_json::Value = serde_json::from_slice(&requests[0].body).unwrap();
assert_eq!(body["session"]["model"], "custom-live-model");
}
#[test]
fn each_start_reads_a_key_another_process_saved() {
let _env = env_lock::lock_env(ENV);
let directory = TempDir::new().unwrap();
let agent = config(&directory);
let setup = config(&directory);
agent
.set_param("GOOSE_LIVE_VOICE_ENDPOINT", ENDPOINT)
.unwrap();
agent
.set_secret("GOOSE_LIVE_VOICE_API_KEY", &"old-key")
.unwrap();
assert_eq!(live_voice_settings(&agent).unwrap().api_key, "old-key");
let generation = agent.generation();
setup
.set_secret("GOOSE_LIVE_VOICE_API_KEY", &"new-key")
.unwrap();
assert_eq!(live_voice_settings(&agent).unwrap().api_key, "new-key");
assert_eq!(agent.generation(), generation);
}
}