Files
crank/crates/crank-import/src/rest/recommendations.rs
T

242 lines
7.9 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
use crank_schema::{Schema, SchemaKind};
use crate::rest::model::{ImportFinding, ImportFindingSeverity, RestImportOperation};
pub fn document_finding(code: &str, message: impl Into<String>) -> ImportFinding {
ImportFinding {
code: code.to_owned(),
severity: ImportFindingSeverity::Warning,
message: message.into(),
operation_key: None,
source_location: None,
}
}
pub fn document_blocker(code: &str, message: impl Into<String>) -> ImportFinding {
ImportFinding {
code: code.to_owned(),
severity: ImportFindingSeverity::Error,
message: message.into(),
operation_key: None,
source_location: None,
}
}
pub fn operation_finding(
operation_key: &str,
code: &str,
message: impl Into<String>,
) -> ImportFinding {
ImportFinding {
code: code.to_owned(),
severity: ImportFindingSeverity::Warning,
message: message.into(),
operation_key: Some(operation_key.to_owned()),
source_location: None,
}
}
pub fn operation_info(
operation_key: &str,
code: &str,
message: impl Into<String>,
) -> ImportFinding {
ImportFinding {
code: code.to_owned(),
severity: ImportFindingSeverity::Info,
message: message.into(),
operation_key: Some(operation_key.to_owned()),
source_location: None,
}
}
pub fn operation_recommendations(operation: &RestImportOperation) -> Vec<ImportFinding> {
let mut findings = operation.findings.clone();
if operation
.operation_id
.as_deref()
.unwrap_or_default()
.trim()
.is_empty()
&& !findings
.iter()
.any(|finding| finding.code == "missing_operation_id")
{
findings.push(operation_finding(
&operation.key,
"missing_operation_id",
"У метода нет operationId, имя инструмента будет сгенерировано из метода и пути.",
));
}
if operation
.summary
.as_deref()
.unwrap_or_default()
.trim()
.is_empty()
{
findings.push(operation_finding(
&operation.key,
"missing_summary",
"У метода нет summary, отображаемое имя будет сгенерировано автоматически.",
));
}
if operation
.description
.as_deref()
.unwrap_or_default()
.trim()
.is_empty()
{
findings.push(operation_finding(
&operation.key,
"missing_description",
"У метода нет description. Перед публикацией лучше описать, когда агенту стоит вызывать этот инструмент.",
));
}
if operation.response_schema.is_none() {
findings.push(operation_finding(
&operation.key,
"missing_response_schema",
"У метода не найдена схема успешного ответа, результат будет описан как общий объект.",
));
}
if operation.parameters.len() > 12 {
findings.push(operation_finding(
&operation.key,
"too_many_inputs",
"У метода много входных параметров. Проверьте, не стоит ли разделить инструмент на более узкие сценарии.",
));
}
let undocumented_parameters = operation
.parameters
.iter()
.filter(|parameter| {
parameter
.description
.as_deref()
.unwrap_or_default()
.trim()
.is_empty()
})
.count();
if undocumented_parameters > 0 {
findings.push(operation_finding(
&operation.key,
"parameter_descriptions_missing",
format!(
"У {undocumented_parameters} входных параметров нет описания. Модели будет сложнее понять, какие значения туда передавать."
),
));
}
with_operation_location(findings, operation)
}
pub fn candidate_recommendations(
operation: &RestImportOperation,
suggested_name: &str,
description: &str,
input_schema: &Schema,
output_schema: &Schema,
) -> Vec<ImportFinding> {
let mut findings = Vec::new();
let input_fields = field_count(input_schema);
let output_fields = field_count(output_schema);
if input_fields == 0 {
findings.push(operation_info(
&operation.key,
"no_input_fields",
"У инструмента нет входных параметров. Это нормально для справочных методов, но проверьте, что агенту не нужно передавать фильтры.",
));
}
if output_fields == 0 {
findings.push(operation_finding(
&operation.key,
"empty_output_schema",
"В ответе не найдено отдельных полей. Перед публикацией проверьте схему ответа и маппинг результата.",
));
}
if output_fields > 12 {
findings.push(operation_finding(
&operation.key,
"too_many_output_fields",
format!(
"В ответ инструмента попадает много полей: {output_fields}. Лучше вернуть только данные, которые нужны агенту для ответа пользователю."
),
));
}
if is_weak_description(operation, description) {
findings.push(operation_finding(
&operation.key,
"weak_tool_description",
"Описание инструмента слишком короткое или техническое. Перед публикацией добавьте, когда агент должен вызывать инструмент и что будет в успешном ответе.",
));
}
if weak_name(suggested_name) {
findings.push(operation_finding(
&operation.key,
"weak_tool_name",
format!(
"Имя инструмента `{suggested_name}` выглядит слишком общим. Лучше использовать имя с конкретным действием и объектом."
),
));
}
with_operation_location(findings, operation)
}
fn with_operation_location(
mut findings: Vec<ImportFinding>,
operation: &RestImportOperation,
) -> Vec<ImportFinding> {
for finding in &mut findings {
if finding.source_location.is_none() {
finding.source_location = operation.source_location.clone();
}
}
findings
}
fn is_weak_description(operation: &RestImportOperation, description: &str) -> bool {
let normalized = description.trim();
if normalized.chars().count() < 40 {
return true;
}
if normalized.starts_with("Выполняет ") {
return true;
}
operation
.summary
.as_deref()
.map(|summary| summary.trim() == normalized)
.unwrap_or(false)
}
fn weak_name(name: &str) -> bool {
let parts = name
.split('_')
.filter(|part| !part.is_empty())
.collect::<Vec<_>>();
if parts.len() < 2 {
return true;
}
let weak_terms = [
"api",
"data",
"item",
"items",
"object",
"operation",
"request",
];
parts.iter().any(|part| weak_terms.contains(part))
}
fn field_count(schema: &Schema) -> usize {
match schema.kind {
SchemaKind::Object => schema.fields.len(),
_ => 0,
}
}