Add OpenAPI import backend
This commit is contained in:
1 parent
87cdb95b80
commit
a8aa3248c9
34 files changed
+2569
-27
No files matched your search
@@ -0,0 +1,213 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
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()),
|
||||
}
|
||||
}
|
||||
|
||||
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()),
|
||||
}
|
||||
}
|
||||
|
||||
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.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} входных параметров нет описания. Модели будет сложнее понять, какие значения туда передавать."
|
||||
),
|
||||
));
|
||||
}
|
||||
findings
|
||||
}
|
||||
|
||||
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}` выглядит слишком общим. Лучше использовать имя с конкретным действием и объектом."
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user