分类把文本归入预定义类别,例如情感、主题或垃圾信息;提取则从自由文本中取出结构化字段,例如命名实体、键值对。两者都适合使用 Rig 的 Extractor:用 Rust 类型定义结果,Rig 驱动 LLM 生成该类型的值,并进行类型安全的反序列化。
本指南从情感分类器开始,逐步构建一个在单次调用中同时完成分类与提取的分析器。
项目准备#
cargo new text_analysis
cd text_analysis[dependencies]
rig = "=0.46.0"
tokio = { version = "1", features = ["full"] }
anyhow = "1"
serde = { version = "1", features = ["derive"] }
schemars = "1"设置 OpenAI API Key:
export OPENAI_API_KEY=your_api_key_here文本分类#
提取器的目标类型必须派生 serde::Deserialize、serde::Serialize 和 schemars::JsonSchema。Rig 把类型转为 JSON Schema,模型填写内容,再由 Rig 反序列化回你的类型。
use anyhow::Result;
use rig::extractor::ExtractorBuilder;
use rig::prelude::*;
use rig::providers::openai::{self, OpenAI};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
enum Sentiment {
Positive,
Negative,
Neutral,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
struct SentimentClassification {
sentiment: Sentiment,
confidence: f32,
}
#[tokio::main]
async fn main() -> Result<()> {
let model = OpenAI::from_env()?.completion(openai::GPT_5_5);
let classifier = ExtractorBuilder::<SentimentClassification>::new(model)
.append_preamble("Classify the sentiment of the given text.")
.build();
let text = "I absolutely loved the new restaurant. The food was amazing!";
let result = classifier.extract(text).await?.output;
println!("Sentiment: {:?} ({:.2})", result.sentiment, result.confidence);
Ok(())
}ExtractorBuilder::<T>::new(model) 返回构建器。提取器有固定的系统提示词,要求模型通过 schema 为 T 的 submit 工具提交答案;.append_preamble(...) 在后面追加你的任务指令。.build() 生成提取器,.extract(text).await? 返回响应,其中 output 是 SentimentClassification,响应还携带 token usage。
说明
在系统提示词中加入少量标注示例,能明显提高准确率。展示希望得到的确切格式,例如“文本:‘……’ → 情感:Negative,置信度:0.9”,模型会照此输出。
提取结构化实体#
同一抽象也能处理提取任务,只需改变目标类型。下面将句子中的命名实体提取到 Vec<Entity>:
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
enum EntityType {
Person,
Organization,
Location,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
struct Entity {
text: String,
entity_type: EntityType,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
struct ExtractedEntities {
entities: Vec<Entity>,
}
let ner = ExtractorBuilder::<ExtractedEntities>::new(model)
.append_preamble("Identify and extract people, organizations, and locations from the text.")
.build();
let text = "Apple Inc., based in Cupertino, was founded by Steve Jobs and Steve Wozniak.";
let result = ner.extract(text).await?.output;
for entity in result.entities {
println!("{:?}: {}", entity.entity_type, entity.text);
}同时分类与提取#
由于目标是普通 Rust 类型,可以嵌套分类和提取结构体,在一次 API 调用中获得两种结果。相比运行两个提取器,这样成本更低、结果更一致:
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
struct TextAnalysis {
sentiment: SentimentClassification,
entities: Vec<Entity>,
}
let analyzer = ExtractorBuilder::<TextAnalysis>::new(model)
.append_preamble(
"For the given text: classify the overall sentiment with a confidence score, \
and extract named entities (Person, Organization, Location).",
)
.build();
let text = "I had a great time visiting Google's headquarters in Mountain View. \
Sundar Pichai's leadership has been impressive.";
let result = analyzer.extract(text).await?.output;
println!(
"Sentiment: {:?} ({:.2})",
result.sentiment.sentiment, result.sentiment.confidence
);
for entity in &result.entities {
println!("- {:?}: {}", entity.entity_type, entity.text);
}这种模式也能扩展到更丰富的 schema。例如分析新闻文章时,添加主题和要点字段,提取器会一次填完:
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
enum Topic {
Politics,
Technology,
Sports,
Entertainment,
Other(String),
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
struct NewsArticleAnalysis {
topic: Topic,
sentiment: SentimentClassification,
entities: Vec<Entity>,
key_points: Vec<String>,
}实用建议#
- 对可能不存在的字段使用
Option<T>,让模型能够明确省略。 - 保持结构体职责集中。 小而命名清晰的类型,比一个庞大复杂的 schema 更容易可靠提取。
- 用示例引导。 系统提示词中的少量标注示例可以显著提高一致性。
- 允许重试。 当模型没有调用
submit,或返回数据无法反序列化时,.retries(n)会重新提取。 - 选择合适模型。
gpt-5.5适合细致、多字段的分析;简单分类用小模型即可。
另请参阅#
- 结构化输出:
Extractor的内部工作方式。 - Agent:提取器本质上是通过
submit工具调用输出结果的 Agent。 - docs.rs 上的
rig::extractor:完整 API 参考。