小壹按公开目录价格选择兼容线路
This commit is contained in:
parent
8fa26a111b
commit
8dd6e2e3c6
@ -308,12 +308,15 @@ pub fn select_model(m: &Value) -> Result<Value, String> {
|
||||
}
|
||||
// Multipart files carry their own type; an inline field must accept a JPEG data URL.
|
||||
let jpeg_references = multipart || nodes.iter().all(|n| accepts(&json!(["data:image/jpeg;base64,AA=="]), &n["properties"][field], 0));
|
||||
found.push(json!({"path":path,"route":id,"field":field,"multipart":multipart,"probe":probe,"maxImages":max,"schema":schema,
|
||||
"parameters":params,"jpegReferences":jpeg_references}));
|
||||
let price = route["pricing"]["effective_price"].as_f64().unwrap_or(f64::INFINITY);
|
||||
found.push((price, json!({"path":path,"route":id,"field":field,"multipart":multipart,"probe":probe,"maxImages":max,"schema":schema,
|
||||
"parameters":params,"jpegReferences":jpeg_references})));
|
||||
}
|
||||
}
|
||||
found.sort_by_key(|p| (p["probe"] == true, p["path"] != "/extensions/v1/tasks", p["multipart"] == true));
|
||||
found.into_iter().next().ok_or("此模型当前线路的参考图契约尚未适配;请更换模型,不会尝试其他线路".into())
|
||||
let preference = |p: &Value| (p["probe"] == true, p["path"] != "/extensions/v1/tasks", p["multipart"] == true);
|
||||
found.into_iter().min_by(|(a_price, a), (b_price, b)| {
|
||||
a_price.total_cmp(b_price).then_with(|| preference(a).cmp(&preference(b)))
|
||||
}).map(|(_, contract)| contract).ok_or("此模型当前线路的参考图契约尚未适配;请更换模型,不会尝试其他线路".into())
|
||||
}
|
||||
fn safe_parameter(name: &str, v: &Value) -> bool {
|
||||
let s = v.as_str().unwrap_or("");
|
||||
|
||||
@ -72,21 +72,40 @@ pub(super) fn reasoning_options<'a>(protocol: &str, properties: &'a Value) -> (b
|
||||
(enabled, levels)
|
||||
}
|
||||
|
||||
fn completion_capability(route: &Value) -> u8 {
|
||||
let capabilities = &route["chat_capabilities"];
|
||||
match capabilities["image_base64_streaming_tools"].as_str() {
|
||||
Some("verified") => 2,
|
||||
Some("disabled") => 0,
|
||||
_ if capabilities["image_base64"] == "verified" && capabilities["streaming_tools"] == "verified" => 1,
|
||||
_ => 0,
|
||||
}
|
||||
fn declares_image_input(row: &Value) -> bool {
|
||||
row["input_modes"].as_array().is_some_and(|modes| modes.iter()
|
||||
.any(|mode| matches!(mode.as_str(), Some("image" | "image_base64"))))
|
||||
}
|
||||
|
||||
fn allows_streaming_tools(route: &Value) -> bool {
|
||||
route["chat_capabilities"]["streaming_tools"] != "disabled"
|
||||
&& route["invocation"]["input_schema"]["properties"]["tools"]["maxItems"] != 0
|
||||
}
|
||||
|
||||
fn allows_image_tools(route: &Value) -> bool {
|
||||
["image_base64", "image_base64_streaming_tools"].iter()
|
||||
.all(|field| route["chat_capabilities"][*field] != "disabled")
|
||||
}
|
||||
|
||||
fn token_prices(route: &Value) -> (f64, f64) {
|
||||
let pricing = &route["pricing"];
|
||||
let base = pricing["token_intervals"].as_array().and_then(|tiers| {
|
||||
tiers.iter().min_by_key(|tier| tier["min_tokens"].as_u64().unwrap_or(0))
|
||||
});
|
||||
let price = |field: &str| base.and_then(|tier| tier[field].as_f64())
|
||||
.or_else(|| pricing[field].as_f64()).unwrap_or(f64::INFINITY);
|
||||
(price("input_price_per_million"), price("output_price_per_million"))
|
||||
}
|
||||
|
||||
pub(super) fn text_model(row: &Value, key: Option<&str>) -> Option<Value> {
|
||||
text_model_for(row, key, true)
|
||||
select_text_model(row, key, true, true)
|
||||
}
|
||||
|
||||
pub(super) fn text_model_for(row: &Value, key: Option<&str>, responses: bool) -> Option<Value> {
|
||||
select_text_model(row, key, responses, false)
|
||||
}
|
||||
|
||||
fn select_text_model(row: &Value, key: Option<&str>, responses: bool, prefer_image: bool) -> Option<Value> {
|
||||
let id = row["id"].as_str().filter(|id| !id.is_empty() && id.len() <= 200)?;
|
||||
if retired_text_model(id) || row["status"] != "available" || row["available"] != true
|
||||
|| !matches!(row["modality"].as_str(), Some("text" | "multimodal"))
|
||||
@ -94,17 +113,23 @@ pub(super) fn text_model_for(row: &Value, key: Option<&str>, responses: bool) ->
|
||||
return None;
|
||||
}
|
||||
|
||||
// A model cannot inherit a capability from a different route, even on the same API.
|
||||
let route = text_routes(row).filter_map(|route| {
|
||||
let protocol = text_protocol(&route["invocation"], responses)?;
|
||||
Some((route, protocol))
|
||||
}).max_by_key(|(route, _)| {
|
||||
let preferred = route["id"] == row["default_route_option_id"];
|
||||
(completion_capability(route), preferred)
|
||||
});
|
||||
let image_input = declares_image_input(row);
|
||||
let preferred = |route: &Value| route["is_default"] == true
|
||||
|| route["id"] == row["default_route_option_id"];
|
||||
let image_preference = |route: &Value| prefer_image && image_input && allows_image_tools(route);
|
||||
let route = text_routes(row).filter(|route| allows_streaming_tools(route))
|
||||
.filter_map(|route| Some((route, text_protocol(&route["invocation"], responses)?)))
|
||||
.min_by(|(a, _), (b, _)| {
|
||||
let (a_input, a_output) = token_prices(a);
|
||||
let (b_input, b_output) = token_prices(b);
|
||||
image_preference(b).cmp(&image_preference(a))
|
||||
.then(a_input.total_cmp(&b_input)).then(a_output.total_cmp(&b_output))
|
||||
.then_with(|| preferred(b).cmp(&preferred(a)))
|
||||
});
|
||||
let (contract, protocol, route_id) = match route {
|
||||
Some((route, protocol)) => (route, protocol, route["id"].as_str()),
|
||||
None if row["service_offers"].is_null() => (row, text_protocol(&row["invocation"], responses)?, None),
|
||||
None if row["service_offers"].is_null() && allows_streaming_tools(row) =>
|
||||
(row, text_protocol(&row["invocation"], responses)?, None),
|
||||
None => return None,
|
||||
};
|
||||
let path = contract["invocation"]["path"].as_str()?;
|
||||
@ -114,16 +139,11 @@ pub(super) fn text_model_for(row: &Value, key: Option<&str>, responses: bool) ->
|
||||
let require_single_tool = protocol == "openai-responses" && tool_choice["type"] == "string"
|
||||
&& tool_choice["enum"].as_array().is_some_and(|values| values.iter().any(|value| value == "required"));
|
||||
let capabilities = &contract["chat_capabilities"];
|
||||
let production = completion_capability(contract);
|
||||
let image_status = match capabilities["image_base64"].as_str() {
|
||||
Some("verified" | "disabled" | "unverified") => capabilities["image_base64"].as_str()?,
|
||||
_ if contract["input_modes"].as_array().is_some_and(|modes| modes.iter()
|
||||
.any(|mode| matches!(mode.as_str(), Some("image" | "image_base64")))) => "verified",
|
||||
_ => "unverified",
|
||||
};
|
||||
let image_status = capabilities["image_base64"].as_str().unwrap_or("unverified");
|
||||
let image_ready = image_input && allows_image_tools(contract);
|
||||
Some(json!({"key":key.unwrap_or(id),"id":id,"label":id,"protocol":protocol,"path":path,
|
||||
"routeId":route_id,"imageInputStatus":image_status,"supportsImageInput":production > 0 || image_status == "verified",
|
||||
"productionReady":production > 0,"productionVerified":production == 2,
|
||||
"routeId":route_id,"imageInputStatus":image_status,"supportsImageInput":image_ready,
|
||||
"productionReady":image_ready,"productionVerified":capabilities["image_base64_streaming_tools"] == "verified",
|
||||
"requireSingleTool":require_single_tool,"reasoning":reasoning,"reasoningEfforts":reasoning_efforts}))
|
||||
}
|
||||
|
||||
@ -448,44 +468,69 @@ mod tests {
|
||||
assert!(text_model(&published, None).is_none());
|
||||
}
|
||||
|
||||
fn priced_catalog() -> Value {
|
||||
serde_json::from_str(include_str!("testdata/public-priced-routes.json")).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_verified_combined_route_is_selected_without_crossing_line_capabilities() {
|
||||
let default = "a3830b3b-6fa5-4a2b-80d0-9e7a1c5cf61a";
|
||||
let alternative = "3d422446-59f2-4bab-ab31-9eddee1a10e1";
|
||||
let invocation = |route: &str, path: &str, input: &str| json!({
|
||||
"method":"POST","path":path,"content_type":"application/json",
|
||||
"headers":{"X-Relay-Route-Option":route},
|
||||
"authentication":{"type":"bearer","header":"Authorization"},
|
||||
"input_schema":{"properties":{"model":{},(input):{},"stream":{},"tools":{}}}
|
||||
});
|
||||
let chat = invocation(default,"/v1/chat/completions","messages");
|
||||
let responses = invocation(alternative,"/v1/responses","input");
|
||||
let mut row = json!({"id":"route-model","status":"available","available":true,"modality":"multimodal",
|
||||
"default_route_option_id":default,"invocation":chat,
|
||||
"service_offers":[{"route_options":[
|
||||
{"id":default,"available":true,"invocation":chat,
|
||||
"chat_capabilities":{"image_base64":"disabled","streaming_tools":"verified"}},
|
||||
{"id":alternative,"available":true,"invocation":responses,
|
||||
"chat_capabilities":{"image_base64":"verified","streaming_tools":"unverified"}}
|
||||
]}]});
|
||||
let current = text_model(&row,None).unwrap();
|
||||
assert_eq!(current["routeId"],default);
|
||||
assert_eq!(current["productionReady"],false);
|
||||
let routes = &mut row["service_offers"][0]["route_options"];
|
||||
routes[1]["chat_capabilities"]["streaming_tools"] = json!("verified");
|
||||
routes[1]["chat_capabilities"]["image_base64_streaming_tools"] = json!("disabled");
|
||||
assert_eq!(text_model(&row,None).unwrap()["routeId"],default);
|
||||
row["service_offers"][0]["route_options"][1]["chat_capabilities"]["image_base64_streaming_tools"] = json!("unverified");
|
||||
let trial = text_model(&row,None).unwrap();
|
||||
assert_eq!(trial["routeId"],alternative);
|
||||
assert_eq!(trial["productionReady"],true);
|
||||
assert_eq!(trial["productionVerified"],false);
|
||||
row["service_offers"][0]["route_options"][1]["chat_capabilities"]["image_base64_streaming_tools"] = json!("verified");
|
||||
let release = text_model(&row,None).unwrap();
|
||||
assert_eq!(release["routeId"],alternative);
|
||||
assert_eq!(release["protocol"],"openai-responses");
|
||||
assert_eq!(release["productionReady"],true);
|
||||
assert_eq!(release["productionVerified"],true);
|
||||
fn selects_the_cheapest_compatible_chat_route() {
|
||||
let catalog = priced_catalog();
|
||||
let mut row = catalog["data"]["sections"][0]["models"][0].clone();
|
||||
let settings = json!({"model":"gpt-6.1-sol"});
|
||||
let authorized = ["gpt-6.1-sol".to_owned()];
|
||||
let selected = |row: &Value| {
|
||||
detail_selection(&[text_model(row, None).unwrap()], &settings, &authorized).unwrap()
|
||||
};
|
||||
let chosen = selected(&row);
|
||||
assert_eq!(chosen["routeId"], "ec73a238-b634-429e-b137-6f7c925fbec6");
|
||||
assert_eq!(chosen["protocol"], "openai-chat");
|
||||
assert_eq!(chosen["imageInputStatus"], "unverified");
|
||||
assert_eq!(chosen["productionReady"], true);
|
||||
|
||||
for route in row["service_offers"].as_array_mut().unwrap().iter_mut()
|
||||
.flat_map(|offer| offer["route_options"].as_array_mut().unwrap())
|
||||
{
|
||||
if route["chat_capabilities"]["streaming_tools"] == "disabled" {
|
||||
route["pricing"]["token_intervals"][0]["input_price_per_million"] = json!(0.0);
|
||||
} else if route["id"] == chosen["routeId"] {
|
||||
route["chat_capabilities"]["image_base64_streaming_tools"] = json!("disabled");
|
||||
}
|
||||
}
|
||||
let alternative = selected(&row);
|
||||
assert!(alternative["routeId"].as_str().unwrap().starts_with("0d3749d6-"));
|
||||
assert_eq!(alternative["productionReady"], true);
|
||||
assert_eq!(text_model_for(&row, None, true).unwrap()["routeId"], chosen["routeId"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uses_the_default_chat_route_when_prices_match() {
|
||||
let catalog = priced_catalog();
|
||||
let mut row = catalog["data"]["sections"][0]["models"][0].clone();
|
||||
let routes = row["service_offers"].as_array_mut().unwrap();
|
||||
let default = routes.iter().flat_map(|offer| offer["route_options"].as_array().unwrap())
|
||||
.find(|route| route["is_default"] == true).unwrap().clone();
|
||||
for route in routes.iter_mut().flat_map(|offer| offer["route_options"].as_array_mut().unwrap()) {
|
||||
route["pricing"] = default["pricing"].clone();
|
||||
}
|
||||
routes.reverse();
|
||||
assert_eq!(text_model(&row, None).unwrap()["routeId"], default["id"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selects_the_lowest_priced_image_edit_route() {
|
||||
let mut catalog = priced_catalog();
|
||||
let route = crate::jiansun_image_protocol::select(&catalog, "gpt-image-2.6-sunburst").unwrap();
|
||||
assert_eq!(route["route"], "5f6271d9-55a2-444f-a999-5165d2230ab0");
|
||||
assert_eq!(route["path"], "/v1/images/edits");
|
||||
|
||||
let model = &mut catalog["data"]["sections"][0]["models"][1];
|
||||
let cheaper = model["service_offers"].as_array_mut().unwrap().iter_mut()
|
||||
.flat_map(|offer| offer["route_options"].as_array_mut().unwrap())
|
||||
.find(|route| route["invocation"]["path"] == "/v1/images/edits"
|
||||
&& route["pricing"]["effective_price"] == json!(0.18)).unwrap();
|
||||
cheaper["pricing"]["effective_price"] = json!(0.09);
|
||||
let expected = cheaper["id"].clone();
|
||||
assert_eq!(crate::jiansun_image_protocol::select_model(model).unwrap()["route"], expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
94
apps/detail-photocraft/apps/photocraft/src/testdata/public-priced-routes.json
vendored
Normal file
94
apps/detail-photocraft/apps/photocraft/src/testdata/public-priced-routes.json
vendored
Normal file
File diff suppressed because one or more lines are too long
Loading…
x
Reference in New Issue
Block a user