使用 AI 在 .NET 10 中提取汽车列表的结构化数据
Source: Dev.to
请提供您希望翻译的文章正文(除代码块、URL 和标题之外的文字),我将把它翻译成简体中文并保持原有的 Markdown 格式。谢谢!
为什么这很重要
汽车列表形态各异。无论您是在构建价格比较网站、市场聚合平台,还是库存管理系统,都需要:
- 提取关键细节(品牌、型号、年份、里程、价格)
- 处理不同的形式(出售、租赁、租用)
- 优雅地处理缺失信息
- 大规模处理数据
手动解析这些数据既繁琐又费时。让 AI 来完成繁重的工作吧! 💪
我们将使用的工具
- GitHub Models – 免费访问强大的 AI 模型(无需信用卡)
- Microsoft.Extensions.AI – .NET 的统一 AI 抽象层
- .NET 10 – 最新最强
设置
创建一个新的控制台应用程序
dotnet new console -n TextExtraction cd TextExtraction添加所需的包
dotnet add package Microsoft.Extensions.AI.OpenAI dotnet add package Microsoft.Extensions.Configuration.UserSecrets
安全存储你的 GitHub 令牌
dotnet user-secrets init
dotnet user-secrets set "GitHubModels:Token" "your-github-token"定义提取模型
Create CarDetails.cs:
using System.Text.Json.Serialization;
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum AvailabilityType
{
Sale,
Lease,
Rent
}
public class CarDetails
{
public string Make { get; set; } = string.Empty;
public string Model { get; set; } = string.Empty;
public int? Year { get; set; }
public double? Mileage { get; set; }
public double? Price { get; set; }
public AvailabilityType? AvailabilityType { get; set; }
public double? PricePerMonth { get; set; }
public double? PricePerDay { get; set; }
public string[]? Features { get; set; }
public string? Location { get; set; }
public string ShortSummary { get; set; } = string.Empty;
public int? OwnerCount { get; set; }
}注: 可空类型让我们能够优雅地处理缺失的数据!✨
核心提取逻辑 (Program.cs)
using Microsoft.Extensions.AI;
using OpenAI;
using System.ClientModel;
using System.Text.Json;
// -------------------------------------------------
// 1️⃣ Configure the client
// -------------------------------------------------
var configuration = new ConfigurationBuilder()
.AddUserSecrets()
.Build();
var credential = new ApiKeyCredential(
configuration["GitHubModels:Token"]
?? throw new InvalidOperationException("Token not found")
);
IChatClient chatClient = new OpenAIClient(credential, new OpenAIClientOptions
{
Endpoint = new Uri("https://models.inference.ai.azure.com")
})
.GetChatClient("gpt-4o-mini")
.AsIChatClient();
// -------------------------------------------------
// 2️⃣ Prompt (schema)
// -------------------------------------------------
var prompt = @"Extract the following details from the car listing and return **ONLY** a valid JSON object:
{
""Make"": ""string - car manufacturer/brand"",
""Model"": ""string - car model name"",
""Year"": number - manufacturing year,
""Mileage"": number - kilometers driven,
""Price"": number - price in lakhs,
""AvailabilityType"": ""string - one of: Sale, Lease, Rent"",
""Features"": ""array of strings - notable features"",
""ShortSummary"": ""string - brief summary in 10‑15 words"",
""OwnerCount"": number - previous owners (null if not mentioned)
}
Return only the JSON object, no additional text.";
// -------------------------------------------------
// 3️⃣ Sample listings
// -------------------------------------------------
var carListings = new List<string>
{
"Honda City 2018 for sale, only 30,000 km! Single owner, showroom condition. ₹6.5 lakh.",
"Hyundai Creta SX 2020 — premium SUV with sunroof. Monthly lease at ₹22,000.",
"Toyota Innova Crysta 2019 — spacious 7‑seater, 40,000 km, rent at ₹2,500/day."
};
// -------------------------------------------------
// 4️⃣ Process each listing
// -------------------------------------------------
foreach (var listing in carListings)
{
var response = await chatClient.GetResponseAsync(
$"{prompt}\n\nCar Listing:\n{listing}"
);
// The model should deserialize the JSON into this POCO:
// (Define `CarDetails` elsewhere in the project.)
if (response.TryGetResult(out CarDetails? carDetails) && carDetails != null)
{
Console.WriteLine($"✅ Extracted: {carDetails.Make} {carDetails.Model}");
Console.WriteLine(
JsonSerializer.Serialize(
carDetails,
new JsonSerializerOptions { WriteIndented = true }
)
);
}
}运行应用
dotnet run示例输出
Processing car listings...
✅ Extracted: Honda City
{
"Make": "Honda",
"Model": "City",
"Year": 2018,
"Mileage": 30000,
"Price": 6.5,
"AvailabilityType": "Sale",
"Features": [
"Single owner",
"Showroom condition"
],
"OwnerCount": 1
}
✅ Extracted: Hyundai Creta
{
"Make": "Hyundai",
"Model": "Creta SX",
"Year": 2020,
"AvailabilityType": "Lease",
"PricePerMonth": 22000,
"Features": [
"Premium SUV",
"Sunroof"
]
}扩展解决方案
添加更多字段 – 燃料类型、变速箱、颜色
public string? FuelType { get; set; } // Petrol / Diesel / Electric public string? Transmission { get; set; } // Manual / Automatic public string? Color { get; set; }处理实时数据 – 从 API 或 RSS 源获取列表
var listings = await FetchListingsFromApi("https://api.carmarket.com/listings");验证数据
if (carDetails.Year > DateTime.Now.Year) { Console.WriteLine("⚠️ Invalid year detected"); }持久化到数据库
await dbContext.CarListings.AddAsync(carDetails); await dbContext.SaveChangesAsync();切换到更强大的模型
var client = chatService.GetChatClient("gpt-4o"); // Higher accuracy, slightly slower
最佳实践
- 保持温度低 – 默认设置通常能产生最一致的提取结果。
- 在提示中明确 – 指定所需的确切 JSON 结构。
- 使用可空类型 – 并非每个列表都有所有字段。
- 批量处理 – 高效处理大量列表。
- 监控 token 使用 – 通过
response.Usage跟踪成本。
🎯 准备好将混乱的汽车广告转化为干净、结构化的数据了吗?
试一试,根据你的需求调整模式,让 AI 完成繁重的工作! 🚀
全球应用
🚀 使用案例
- 🏪 Marketplace Aggregation – 整合来自多个来源的列表
- 💰 Price Intelligence – 跟踪各市场的价格趋势
- 📊 Analytics Dashboards – 从非结构化数据中构建洞察
- 🤖 Chatbots – 为汽车推荐机器人提供动力
- 📱 Mobile Apps – 解析用户提交的列表
获取完整的工作示例
从 GitHub 获取:
genai-dotnet-basic_llm_tasks/TextExtraction仓库包含
- ✅ 带注释的完整源代码
- ✅ 9 个示例汽车列表
- ✅ 配置设置指南
- ✅ 详细的 README
What You’ll Learn
- 使用 GitHub Models API 于 .NET
- 使用
GetResponseAsync获取强类型 AI 响应 - 使用 AI 进行基于模式的提取
- 优雅地处理非结构化数据
- 构建面向生产的文本提取
尝试提取
- 📄 简历数据 – 姓名、技能、工作经历
- 🧾 发票 – 供应商、金额、日期
- 📧 电子邮件 – 发件人、主题、要点
- 🏠 房地产列表
- 🍕 餐厅菜单 – 菜品、价格、配料
同样的模式适用于 任何 文本提取任务!
你将构建什么?
在下面留下评论! 👇
👍 喜欢这样吗?
觉得这有帮助吗?点个 ❤️ 并关注以获取更多 .NET + AI 内容!
标签: #dotnet #ai #machinelearning #csharp #github #opensource #textextraction #nlp #automation
GitHub 仓库: https://github.com/your‑org/genai-dotnet-basic_llm_tasks/tree/main/TextExtraction