UniGenAI 1.0.0

dotnet add package UniGenAI --version 1.0.0
                    
NuGet\Install-Package UniGenAI -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="UniGenAI" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="UniGenAI" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="UniGenAI" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add UniGenAI --version 1.0.0
                    
#r "nuget: UniGenAI, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package UniGenAI@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=UniGenAI&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=UniGenAI&version=1.0.0
                    
Install as a Cake Tool

UniGenAI 🚀

Build Status ONNX Runtime LiteRT License

UniGenAI 是一个基于 C# 开发的跨平台、高性能生成式 AI 与计算机视觉推理引擎。项目旨在通过统一的接口封装底层复杂的非托管推理框架,使 .NET 开发者能够以极低的开发成本,快速将尖端的深度学习模型(如大语言模型 LLM、多模态视觉模型 VLM 和实时目标检测模型 RT-DETR)集成到自己的业务系统中。


📌 项目描述

在传统的 AI 应用落地中,使用 C#/.NET 直接运行最新的 AI 模型往往伴随着底层 API 复杂、内存管理困难以及预处理逻辑繁琐等痛点。UniGenAI 针对这些问题提供了开箱即用的解决方案:

  • 大语言模型推理 (LLM):基于 Microsoft.ML.OnnxRuntimeGenAI 封装,提供词表编解码(Tokenization)、缓存管理(KV Caching)和推理循环控制。支持同步文本生成及低延迟的异步流式输出(Streaming)。
  • 多模态视觉聊天 (VLM):封装 MultiModalProcessor,支持图像-文本混合对齐输入,可轻松适配 Phi-3-Vision 等视觉大模型,实现对图像内容的智能分析和多轮对话。
  • 实时目标检测 (RT-DETR):支持 Roboflow 等平台发布的最新 RT-DETR (Realtime Detection Transformer) 模型。内置自适应 Letterbox 预处理、标准化处理、多线程/CUDA 硬件加速推理,以及自适应渲染边界框(BBox),并支持中文字体阴影防干扰视觉效果。
  • 端侧轻量级大模型 (LiteRT-LM):深度集成 Google 的 LiteRT-LM (原 TensorFlow Lite 针对大模型的端侧优化方案)。提供原生的 C++ 动态库封装与 C# P/Invoke 绑定,支持在端侧设备以极低资源占用运行轻量大模型,支持多轮会话(Conversation)的上下文管理及异步流式响应。

项目的核心接口均实现了 IDisposable,并对底层的 C++ 指针进行显式生命周期管理,确保高并发下的显存与系统内存安全释放。


🛠️ 技术清单

1. 开发框架

  • UniGenAI 核心库.NET Standard 2.1(具备极强的跨平台适配性,支持在 .NET Core 3.1+ 以及现代 .NET 5/6/7/8/9/10 中直接引用)
  • UniGenAITest 测试工程.NET 8.0 控制台应用程序
  • UniGenAI.LiteLm.Core 动态链接库:基于 C++ 17 编写的 native 动态链接库,提供对 Google LiteRT-LM C++ 引擎的 C-API 导出。

2. 核心依赖项

项目严格依赖最新、经过工程验证的 NuGet 库:


📦 安装与配置

1. 克隆与打开项目

# 克隆仓库
git clone https://github.com/your-username/UniGenAI.git

# 进入目录
cd UniGenAI

# 使用 IDE 打开解决方案
dotnet restore UniGenAI.sln

2. 编译 Native C++ 动态链接库 (UniGenAI.LiteLm.Core)

如果在其他平台上运行 Google LiteRT-LM,可以通过项目内置的自动化构建脚本直接编译 native 库并发布到 C# 测试项目的输出目录中:

在 macOS / Linux 上:

cd LiteLm.Core
# 脚本会自动清理 build 缓存、运行 CMake 进行编译并拷贝 .dylib 或 .so 文件到输出目录
bash build_core.sh

在 Windows (PowerShell) 上:

cd LiteLm.Core
.\build_core.ps1

📖 使用文档与代码示例

1. Google LiteRT-LM 文本生成与流式会话 (LiteRtEngine)

LiteRtEngine 负责加载经过 TFLite 优化的轻量大模型。通过 LiteRtConversation 来建立一个状态可追踪的多轮会话,并原生支持函数调用(Tool Calling / Function Calling)。

基础文本生成与流式问答
using System;
using System.Threading.Tasks;
using UniGenAI.Core;

// 1. 初始化 LiteRT-LM 引擎
string modelPath = @"/path/to/google_litert_lm_model";
using var engine = new LiteRtEngine(modelPath, 0); // 0 is CPU

// 2. 创建一个会话实例
using var conversation = engine.CreateConversation();

// 3. 同步发送消息
string response = await conversation.SendChatAsync("What is LiteRT-LM?");
Console.WriteLine($"Model: {response}");

// 4. 流式接收响应
await foreach (var token in conversation.SendMessageStream("Explain the benefits of on-device AI."))
{
    Console.Write(token); // 实时输出生成的文本 Token
}
函数调用 / 工具调用 (Tool Calling) 自动闭环与实时状态反馈
using System;
using System.Threading.Tasks;
using UniGenAI.Core;
using UniGenAI.Attributes;
using UniGenAI.Entities.Data;

// 1. 定义工具类,并标记 [LiteLmToolClass] 特性,方法使用 [LiteLmTool] 标记
[LiteLmToolClass]
public class MyTools
{
    [LiteLmTool("Returns the weather forecast for a given location.", name: "get_weather")]
    public string GetWeather(
        [LiteLmParameter("The city name, e.g. Paris, France")] string location)
    {
        return $"Sunny in {location}, 22C";
    }
}

// 2. 一键创建 Conversation 会话并开启工具调用(传 true)
using var conversation = engine.CreateConversation(
    enableTools: true,
    systemInstruction: "You are a helpful assistant with weather tools."
);

// 3. 定义进度报告回调,用于捕获 AI 实时反馈动作(如思考中、调用函数、函数调用成功)
var progressReporter = new Progress<LiteLmChatProgress>(p =>
{
    switch (p.Status)
    {
        case LiteLmChatStatus.Thinking:
            Console.WriteLine("[AI] 正在思考中...");
            break;
        case LiteLmChatStatus.InvokingTool:
            Console.WriteLine($"[AI] 正在调用本地工具: {p.Detail}");
            break;
        case LiteLmChatStatus.ToolCompleted:
            Console.WriteLine($"[AI] 本地工具执行完毕: {p.Detail}");
            break;
        case LiteLmChatStatus.Completed:
            Console.WriteLine("[AI] 任务已完成。");
            break;
    }
});

// 4. 执行 SendChatAsync 异步闭环对话流程并传入进度报告
string finalReply = await conversation.SendChatAsync("How is the weather in Paris?", progressReporter);
Console.WriteLine($"AI Final Reply: {finalReply}");

2. 大语言模型文本生成 (LlmEngine)

LlmEngine 负责加载经过 ONNX 优化的 LLM 模型(如 Phi-3-mini-onnx)。支持同步生成和打字机式的流式生成。

using System;
using UniGenAI.Core;

// 1. 初始化引擎
string modelPath = @"D:\Models\Phi3-mini-onnx-cpu";
using var llm = new LlmEngine(modelPath);

string prompt = "请简述什么是人工智能?";

// 示例:流式文本生成
Console.Write("AI: ");
foreach (var chunk in llm.GenerateStream(prompt, maxLength: 512))
{
    Console.Write(chunk);
}

3. 多模态视觉提问 (VisionChatEngine)

VisionChatEngine 允许输入多张图片,并针对图片内容发起复杂的自然语言提问。

using System;
using UniGenAI.Core;

string modelPath = @"D:\Models\phi3-vision-onnx-cpu";
using var visionEngine = new VisionChatEngine(modelPath);

// 输入本地图片路径及提示词
string[] images = new[] { @"D:\Images\chart.png" };
string prompt = "请帮我分析这张图表中的核心趋势。";

Console.Write("AI 分析结果: ");
foreach (var chunk in visionEngine.AskStream(images, prompt, maxLength: 512))
{
    Console.Write(chunk);
}

4. RT-DETR 实时目标检测 (RtDetrPredictor)

RtDetrPredictor 提供高效的单图预测、渲染、批量并发预测等功能。

using System;
using System.Collections.Generic;
using UniGenAI.Core;

// 1. 定义类别字典
var classNames = new Dictionary<int, string> { { 0, "person" }, { 1, "bicycle" }, { 2, "car" } };

// 2. 初始化预测器
using var predictor = new RtDetrPredictor("models/rtdetr_r50vd_640.onnx", classNames, useCuda: false);

// 3. 单图预测并自动唤起系统看图软件预览
string savedPath = await predictor.PreviewAndOpenAsync("images/test.jpg", threshold: 0.5f);

📂 项目结构

UniGenAI/
├── UniGenAI.sln                  # 解决方案入口
│
├── LiteLm.Core/                  # Native C++ 动态链接库项目 (C++ 17)
│   ├── include/
│   │   └── litelm_core.h         # C++ 接口导出头文件
│   ├── src/
│   │   └── litelm_core.cpp       # C++ 推理接口实现
│   ├── CMakeLists.txt            # CMake 配置文件
│   ├── build_core.sh             # Linux/macOS 自动化构建与分发脚本
│   └── build_core.ps1            # Windows 自动化构建与分发脚本
│
├── UniGenAI/                     # 核心类库项目 (Target: .NET Standard 2.1)
│   ├── Core/                     # 核心推理引擎实现
│   │   ├── GgufEngine.cs         # GGUF 格式推理逻辑 (LLamaSharp)
│   │   ├── LlmEngine.cs          # LLM 生成式推理逻辑 (Microsoft GenAI)
│   │   ├── VisionChatEngine.cs   # 多模态视觉推理逻辑 (Microsoft GenAI)
│   │   ├── RtDetrPredictor.cs    # RT-DETR 目标检测逻辑 (ONNX Runtime)
│   │   ├── LiteRtEngine.cs       # Google LiteRT-LM 引擎生命周期封装
│   │   └── LiteRtConversation.cs # Google LiteRT-LM 多轮会话追踪封装
│   │
│   ├── Entities/Data/            # 统一数据契约实体
│   │   ├── ChatMessage.cs
│   │   ├── ChatSession.cs
│   │   ├── DetectionResult.cs
│   │   ├── GenAIConfig.cs
│   │   ├── LetterboxResult.cs
│   │   ├── LiteLmChatProgress.cs
│   │   ├── LiteLmChatStatus.cs
│   │   ├── LiteLmTool.cs
│   │   ├── LiteLmToolCall.cs
│   │   ├── PredictJsonResponse.cs
│   │   └── PredictResult.cs
│   │
│   ├── Helper/                   # 辅助工具方法
│   │   ├── AsyncParallel.cs      # 自适应并发多任务批处理器
│   │   └── ToolScanner.cs        # 特性工具扫描与映射解析器
│   │
│   ├── LlmEngine.md              # LlmEngine 专属开发文档
│   ├── RtDetr.md                 # RtDetrPredictor 专属开发文档
│   └── VisionEngine.md           # VisionChatEngine 专属开发文档
│
└── UniGenAITest/                 # 测试与范例工程 (Target: .NET 8.0)
    ├── Examples/
    │   ├── LlmExample.cs         # LLM 功能使用样板代码
    │   ├── LiteRtLmExample.cs    # Google LiteRT-LM 推理样板代码
    │   ├── MyCustomTools.cs      # 反射工具类声明示例
    │   └── RagWebDemo.cs         # RAG 知识库 Web 服务宿主示例
    ├── Program.cs                # 测试套件交互式菜单入口
    └── UniGenAITest.csproj       # 测试项目配置文件

📅 更新与演进计划 (Roadmap)

🟩 已完成 (Completed)

  • Google LiteRT-LM (TFLite) 深度集成 🎉
    • 提供完备的 LiteLmEngineLiteLmConversation 高层接口,支持流式与非流式问答。
    • 构建跨平台一键编译 CMake 系统,完美兼容 Windows, macOS (arm64/x64) 以及 Linux。

🟦 中期计划 (Mid-Term)

  • RAG 知识库集成 (Retrieval-Augmented Generation) 🧠
    • 内置轻量级向量检索(Vector Search)或支持与常见向量数据库(如 Qdrant, Milvus, PGVector)的简易对接。
    • 提供基于 C# 的文档分块(Chunking)与 Embedding 提取管道(可接入 HuggingFace / ONNX 格式的 Embedding 模型)。
    • 实现完全本地化运行的“知识检索 → 提示词注入 → 大模型生成”的完整闭环。
  • RT-DETR 实时摄像头流支持
    • 添加基于 OpenCV / OpenCVSharp 的摄像头实时画面抓取,以及超低时延的 RtDetr 实线绘制预测流。

🟨 长期计划 (Long-Term)

  • ASP.NET Core Web API 深度整合
    • 提供一套基于 NuGet 的中间件,一键在 ASP.NET Core 应用中暴露符合 OpenAI API 格式的端点。
  • 混合设备调度 (Hybrid Engine Scheduling)
    • 支持多 GPU 轮询调度,自动根据负载在多张显卡或 CPU/GPU 之间进行推理负载均衡。

🤝 贡献指南

我们非常欢迎社区开发者的参与!如果您发现了 Bug 或有更好的功能建议,欢迎提交 Issue 或发起 Pull Request

  1. Fork 本项目。
  2. 创建您的特性分支 (git checkout -b feature/AmazingFeature)。
  3. 提交您的修改 (git commit -m 'Add some AmazingFeature')。
  4. 推送到该分支 (git push origin feature/AmazingFeature)。
  5. 提交 Pull Request。

📄 开源许可证

本项目基于 MIT License 开源。详情参见 [LICENSE] 文件。

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.1 is compatible. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on UniGenAI:

Package Downloads
UniGenAI.Rag

Retrieval-augmented generation (RAG) core for UniGenAI: document import, embeddings, vector search, chat history, and knowledge-base services.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0 66 7/30/2026