aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
365
akode-rs/ext/web-search/src/extension.rs
Normal file
365
akode-rs/ext/web-search/src/extension.rs
Normal file
@@ -0,0 +1,365 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use akode_api::AllowedCaller;
|
||||
use akode_api::ApproximateLocation;
|
||||
use akode_api::ExternalWebAccess;
|
||||
use akode_api::ExternalWebAccessMode;
|
||||
use akode_api::LocationType;
|
||||
use akode_api::SearchContextSize;
|
||||
use akode_api::SearchFilters;
|
||||
use akode_api::SearchSettings;
|
||||
use akode_core::config::Config;
|
||||
use akode_extension_api::ConfigContributor;
|
||||
use akode_extension_api::ExtensionData;
|
||||
use akode_extension_api::ExtensionFuture;
|
||||
use akode_extension_api::ExtensionRegistryBuilder;
|
||||
use akode_extension_api::ThreadLifecycleContributor;
|
||||
use akode_extension_api::ThreadOriginator;
|
||||
use akode_extension_api::ThreadStartInput;
|
||||
use akode_extension_api::ToolContributor;
|
||||
use akode_http_client::HttpClientFactory;
|
||||
use akode_login::AuthManager;
|
||||
use akode_model_provider_info::ModelProviderInfo;
|
||||
use akode_protocol::config_types::WebSearchBackendConfig;
|
||||
use akode_protocol::config_types::WebSearchContextSize;
|
||||
use akode_protocol::config_types::WebSearchMode;
|
||||
use akode_protocol::openai_models::ModelInfo;
|
||||
|
||||
use crate::schema::LITERATURE_SEARCH_QUERY;
|
||||
use crate::tool::WebSearchTool;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct WebSearchExtension {
|
||||
auth_manager: Arc<AuthManager>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct WebSearchExtensionConfig {
|
||||
/// Client-side backend from `[web_search] backend = ...`; takes precedence.
|
||||
backend: Option<WebSearchBackendConfig>,
|
||||
provider_supports_search: bool,
|
||||
http_client_factory: HttpClientFactory,
|
||||
provider: ModelProviderInfo,
|
||||
settings: SearchSettings,
|
||||
}
|
||||
|
||||
impl From<&Config> for WebSearchExtensionConfig {
|
||||
fn from(config: &Config) -> Self {
|
||||
Self {
|
||||
backend: config.web_search_backend.clone(),
|
||||
// The provider-backed standalone search endpoint is opt-in per provider.
|
||||
provider_supports_search: config.model_provider.supports_standalone_web_search,
|
||||
http_client_factory: config.http_client_factory(),
|
||||
provider: config.model_provider.clone(),
|
||||
settings: search_settings(config),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn search_settings(config: &Config) -> SearchSettings {
|
||||
let web_search_config = config.web_search_config.as_ref();
|
||||
SearchSettings {
|
||||
user_location: web_search_config
|
||||
.and_then(|config| config.user_location.as_ref())
|
||||
.map(|location| ApproximateLocation {
|
||||
r#type: LocationType::Approximate,
|
||||
country: location.country.clone(),
|
||||
region: location.region.clone(),
|
||||
city: location.city.clone(),
|
||||
timezone: location.timezone.clone(),
|
||||
}),
|
||||
search_context_size: web_search_config
|
||||
.and_then(|config| config.search_context_size)
|
||||
.map(|size| match size {
|
||||
WebSearchContextSize::Low => SearchContextSize::Low,
|
||||
WebSearchContextSize::Medium => SearchContextSize::Medium,
|
||||
WebSearchContextSize::High => SearchContextSize::High,
|
||||
}),
|
||||
filters: web_search_config
|
||||
.and_then(|config| config.filters.as_ref())
|
||||
.map(|filters| SearchFilters {
|
||||
allowed_domains: filters.allowed_domains.clone(),
|
||||
blocked_domains: None,
|
||||
}),
|
||||
allowed_callers: Some(vec![AllowedCaller::Direct]),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn external_web_access_for_mode(web_search_mode: WebSearchMode) -> ExternalWebAccess {
|
||||
match web_search_mode {
|
||||
WebSearchMode::Disabled | WebSearchMode::Cached => ExternalWebAccess::Boolean(false),
|
||||
WebSearchMode::Indexed => ExternalWebAccess::Mode(ExternalWebAccessMode::Indexed),
|
||||
WebSearchMode::Live => ExternalWebAccess::Boolean(true),
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadLifecycleContributor<Config> for WebSearchExtension {
|
||||
fn on_thread_start<'a>(
|
||||
&'a self,
|
||||
input: ThreadStartInput<'a, Config>,
|
||||
) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
input
|
||||
.thread_store
|
||||
.insert(WebSearchExtensionConfig::from(input.config));
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ConfigContributor<Config> for WebSearchExtension {
|
||||
fn on_config_changed(
|
||||
&self,
|
||||
_session_store: &ExtensionData,
|
||||
thread_store: &ExtensionData,
|
||||
_previous_config: &Config,
|
||||
new_config: &Config,
|
||||
) {
|
||||
thread_store.insert(WebSearchExtensionConfig::from(new_config));
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolContributor for WebSearchExtension {
|
||||
fn tools_for_step(
|
||||
&self,
|
||||
session_store: &ExtensionData,
|
||||
thread_store: &ExtensionData,
|
||||
step_store: &ExtensionData,
|
||||
) -> Vec<
|
||||
Arc<dyn for<'call> akode_extension_api::ToolExecutor<akode_extension_api::ToolCall<'call>>>,
|
||||
> {
|
||||
let Some(config) = thread_store.get::<WebSearchExtensionConfig>() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mode = step_store.get::<WebSearchMode>();
|
||||
if let Some(backend) = config.backend.as_ref() {
|
||||
if mode.as_deref() == Some(&WebSearchMode::Disabled) {
|
||||
return Vec::new();
|
||||
}
|
||||
return match crate::searxng::searxng_tools(backend) {
|
||||
Ok(tools) => tools,
|
||||
Err(error) => {
|
||||
tracing::warn!("web search backend unavailable: {error}");
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
}
|
||||
let Some(mode) = mode else {
|
||||
return Vec::new();
|
||||
};
|
||||
if !config.provider_supports_search || *mode == WebSearchMode::Disabled {
|
||||
return Vec::new();
|
||||
}
|
||||
let auth = thread_store
|
||||
.get::<akode_model_provider::ProviderAuthContext>()
|
||||
.unwrap_or_else(|| {
|
||||
Arc::new(akode_model_provider::ProviderAuthContext {
|
||||
credentials: Arc::clone(&self.auth_manager),
|
||||
})
|
||||
});
|
||||
|
||||
vec![Arc::new(WebSearchTool {
|
||||
session_id: session_store.level_id().to_string(),
|
||||
http_client_factory: config.http_client_factory.clone(),
|
||||
provider: auth.model_provider(config.provider.clone()),
|
||||
settings: SearchSettings {
|
||||
external_web_access: Some(external_web_access_for_mode(*mode)),
|
||||
..config.settings.clone()
|
||||
},
|
||||
supports_literature_search: step_store.get::<ModelInfo>().is_some_and(|model| {
|
||||
model
|
||||
.experimental_supported_tools
|
||||
.iter()
|
||||
.any(|tool| tool == LITERATURE_SEARCH_QUERY)
|
||||
}),
|
||||
originator: thread_store
|
||||
.get::<ThreadOriginator>()
|
||||
.map(|originator| originator.0.clone()),
|
||||
})]
|
||||
}
|
||||
}
|
||||
|
||||
pub fn install(registry: &mut ExtensionRegistryBuilder<Config>, auth_manager: Arc<AuthManager>) {
|
||||
let extension = Arc::new(WebSearchExtension { auth_manager });
|
||||
registry.thread_lifecycle_contributor(extension.clone());
|
||||
registry.config_contributor(extension.clone());
|
||||
registry.tool_contributor(extension);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use akode_extension_api::ExtensionData;
|
||||
use akode_extension_api::ExtensionRegistryBuilder;
|
||||
use akode_extension_api::ToolName;
|
||||
use akode_http_client::HttpClientFactory;
|
||||
use akode_http_client::OutboundProxyPolicy;
|
||||
use akode_login::CodexAuth;
|
||||
use akode_model_provider_info::ModelProviderInfo;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::AuthManager;
|
||||
use super::Config;
|
||||
use super::WebSearchExtensionConfig;
|
||||
use super::external_web_access_for_mode;
|
||||
use super::install;
|
||||
use crate::tool::RUN_TOOL_NAME;
|
||||
use crate::tool::WEB_NAMESPACE;
|
||||
use akode_api::ExternalWebAccess;
|
||||
use akode_api::ExternalWebAccessMode;
|
||||
use akode_protocol::config_types::WebSearchBackendConfig;
|
||||
use akode_protocol::config_types::WebSearchMode;
|
||||
|
||||
#[test]
|
||||
fn external_web_access_preserves_legacy_values_until_indexed() {
|
||||
assert_eq!(
|
||||
[
|
||||
WebSearchMode::Disabled,
|
||||
WebSearchMode::Cached,
|
||||
WebSearchMode::Indexed,
|
||||
WebSearchMode::Live,
|
||||
]
|
||||
.map(external_web_access_for_mode),
|
||||
[
|
||||
ExternalWebAccess::Boolean(false),
|
||||
ExternalWebAccess::Boolean(false),
|
||||
ExternalWebAccess::Mode(ExternalWebAccessMode::Indexed),
|
||||
ExternalWebAccess::Boolean(true),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_extension_contributes_web_run_when_enabled() {
|
||||
let mut builder = ExtensionRegistryBuilder::<Config>::new();
|
||||
install(
|
||||
&mut builder,
|
||||
AuthManager::from_auth_for_testing(CodexAuth::from_api_key("dummy")),
|
||||
);
|
||||
let registry = builder.build();
|
||||
let session_store = ExtensionData::new("session");
|
||||
let thread_store = ExtensionData::new("11111111-1111-4111-8111-111111111111");
|
||||
let step_store = ExtensionData::new("step");
|
||||
step_store.insert(WebSearchMode::Cached);
|
||||
thread_store.insert(WebSearchExtensionConfig {
|
||||
backend: None,
|
||||
provider_supports_search: true,
|
||||
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
provider: ModelProviderInfo::create_responses_provider(
|
||||
"mock",
|
||||
Some("http://127.0.0.1:9/v1".to_string()),
|
||||
),
|
||||
settings: Default::default(),
|
||||
});
|
||||
|
||||
let tool_names = registry
|
||||
.tool_contributors()
|
||||
.iter()
|
||||
.flat_map(|contributor| {
|
||||
contributor.tools_for_step(&session_store, &thread_store, &step_store)
|
||||
})
|
||||
.map(|tool| (tool.tool_name(), tool.supports_parallel_tool_calls()))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(
|
||||
tool_names,
|
||||
vec![(ToolName::namespaced(WEB_NAMESPACE, RUN_TOOL_NAME), true)]
|
||||
);
|
||||
}
|
||||
|
||||
fn registry_tool_names(
|
||||
config: WebSearchExtensionConfig,
|
||||
mode: Option<WebSearchMode>,
|
||||
) -> Vec<ToolName> {
|
||||
let mut builder = ExtensionRegistryBuilder::<Config>::new();
|
||||
install(
|
||||
&mut builder,
|
||||
AuthManager::from_auth_for_testing(CodexAuth::from_api_key("dummy")),
|
||||
);
|
||||
let registry = builder.build();
|
||||
let session_store = ExtensionData::new("session");
|
||||
let thread_store = ExtensionData::new("11111111-1111-4111-8111-111111111111");
|
||||
let step_store = ExtensionData::new("step");
|
||||
if let Some(mode) = mode {
|
||||
step_store.insert(mode);
|
||||
}
|
||||
thread_store.insert(config);
|
||||
registry
|
||||
.tool_contributors()
|
||||
.iter()
|
||||
.flat_map(|contributor| {
|
||||
contributor.tools_for_step(&session_store, &thread_store, &step_store)
|
||||
})
|
||||
.map(|tool| tool.tool_name())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn config_with(
|
||||
backend: Option<WebSearchBackendConfig>,
|
||||
provider_supports_search: bool,
|
||||
) -> WebSearchExtensionConfig {
|
||||
WebSearchExtensionConfig {
|
||||
backend,
|
||||
provider_supports_search,
|
||||
http_client_factory: HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
|
||||
provider: ModelProviderInfo::create_responses_provider(
|
||||
"mock",
|
||||
Some("http://127.0.0.1:9/v1".to_string()),
|
||||
),
|
||||
settings: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn searxng(fetch: bool) -> WebSearchBackendConfig {
|
||||
WebSearchBackendConfig {
|
||||
backend: akode_protocol::config_types::WebSearchBackendKind::Searxng,
|
||||
url: "http://192.168.40.57:8080".to_string(),
|
||||
max_results: 8,
|
||||
fetch,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn searxng_backend_contributes_web_search_and_web_fetch() {
|
||||
for mode in [None, Some(WebSearchMode::Cached), Some(WebSearchMode::Live)] {
|
||||
assert_eq!(
|
||||
registry_tool_names(config_with(Some(searxng(true)), false), mode),
|
||||
vec![
|
||||
ToolName::plain(crate::searxng::WEB_SEARCH_TOOL_NAME),
|
||||
ToolName::plain(crate::searxng::WEB_FETCH_TOOL_NAME),
|
||||
]
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
registry_tool_names(config_with(Some(searxng(false)), false), None),
|
||||
vec![ToolName::plain(crate::searxng::WEB_SEARCH_TOOL_NAME)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_backend_means_no_web_tools() {
|
||||
for mode in [None, Some(WebSearchMode::Cached), Some(WebSearchMode::Live)] {
|
||||
assert_eq!(
|
||||
registry_tool_names(config_with(None, false), mode),
|
||||
Vec::new()
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
registry_tool_names(
|
||||
config_with(Some(searxng(true)), false),
|
||||
Some(WebSearchMode::Disabled)
|
||||
),
|
||||
Vec::new()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn searxng_tools_are_plain_function_tools() {
|
||||
let tools = crate::searxng::searxng_tools(&searxng(true)).expect("tools");
|
||||
for tool in tools {
|
||||
let akode_extension_api::ToolSpec::Function(spec) = tool.spec() else {
|
||||
panic!("expected a function tool");
|
||||
};
|
||||
assert!(spec.name == "web_search" || spec.name == "web_fetch");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user