在等待后端 API 准备就绪之前, 你被阻挡了多少次? 或者你花了多少小时来维持那些在需求改变时变得僵化的虚伪数据?
输入 mostlylucid.mockllmapi - ASP.NET核心模拟平台,该平台使用大语言模型来产生现实的、符合背景的在空中的API反应。你没有维护JSON装置,而是获得智能模型,以适应你的要求,并记住每通电话的状态。
它所支持的是: 您需要的每一项协议 — — REST、图形QL、GRPC、信号R、服务器启动事件和 OpenAPI 。 与静态固定装置不同,响应是根据您的请求动态生成的,这使得多步工作流程和复杂的测试情景变得微不足道。
您可以以三种方式使用 mockllmapi mostlucid. mockllmapi, 取决于您希望您的 dev 环境有多孤立 :
完整的指南 : APPI 参考文件
传统的模拟API有一个致命的缺陷: 每一个请求都是独立的。 给一个有42号身份证的用户, 然后去取他们的订单, 然后你就会收到99号身份证的订单。 没有一致性 。
AIPI 背景 在相关请求中共享内存来解决这个问题:
// Request 1: Get a user
// Note: 'context' is a simple query parameter - no cookies or sessions needed
fetch('/api/users/123?context=checkout-session')
// Response: { id: 42, name: "Alice Smith", email: "[email protected]" }
// Request 2: Get orders (same context parameter)
fetch('/api/orders?userId=42&context=checkout-session')
// Response: { userId: 42, customerName: "Alice Smith", items: [...] }
// Perfect! Same user, consistent data
专卖局长在同一背景下看待以前的请求,并得出一致的数据。 这是多步工作流程的游戏变换器 。
特点:
生命周期:
行为 :
安全性 :
使用案例:
dotnet add package mostlylucid.mockllmapi
// Program.cs
builder.Services.AddLLMockApi(builder.Configuration);
app.MapLLMockApi("/api/mock");
# Download from https://github.com/scottgal/LLMApi/releases
llmock serve --port 5000
完整的指南 : doccker 部署指南
git clone https://github.com/scottgal/LLMApi.git
cd LLMApi
docker compose up -d
你需要 一号Ollama、OpenAI或LM工作室:
# Recommended: Ollama with ministral-3:3b (ultra-fast, accurate JSON generation)
ollama pull ministral-3:3b
见见 《奥亚马示范指南》 供所有示范建议和比较之用。
一旦运行中, 请提出您的第一个请求 :
curl http://localhost:5000/api/mock/users
# Response: [{"id": 1, "name": "Alice Johnson", "email": "[email protected]"}, ...]
就是这样,你现在有一个工作模拟API 产生现实的需求数据。
这是这个博客上的实际搜索代码 这是未变的生产前端代码无需对模拟作任何调整:
// typeahead.js from mostlylucid.net
export function typeahead() {
return {
query: '',
results: [],
search() {
fetch(`/api/search/${encodeURIComponent(this.query)}`)
.then(response => response.json())
.then(data => { this.results = data; });
}
}
}
嘲笑它:
# Using CLI
llmock serve --port 5000
# Query returns contextual results
curl http://localhost:5000/api/search/markdown
# LLM generates blog posts about Markdown
curl http://localhost:5000/api/search/docker
# LLM generates blog posts about Docker
每种答复都是独特和现实的,符合查询要求。
除了生成随机数据之外, 您通常还需要精确控制 JSON 结构 。 形状控制可以让您告诉 LLM 确切地告诉 LLM 要生成什么结构 — 最强大的前端开发功能 。
# Without shape - random structure
curl http://localhost:5000/api/mock/users
# Response: { "userId": 1, "fullName": "Alice" }
# With shape - you control it
curl "http://localhost:5000/api/mock/users" \
-H 'X-Response-Shape: {"id":0,"name":"string","email":"string"}'
# Response: { "id": 1, "name": "Alice", "email": "[email protected]" }
指定形状的三种方式 :
?shape={...}X-Response-Shape: {...} (建议){"shape": {...}}const shape = {
company: {
id: 0,
name: "string",
employees: [{
id: 0,
firstName: "string",
department: { id: 0, name: "string" },
projects: [{ id: 0, title: "string" }]
}]
}
};
fetch('/api/mock/company', {
headers: { 'X-Response-Shape': JSON.stringify(shape) }
});
interface User {
id: number;
name: string;
email: string;
}
const USER_SHAPE: Partial<User> = { id: 0, name: "", email: "" };
// Shape becomes your type definition AND mock schema!
现在让我们将形状控制与 API 环境结合起来处理复杂、多步骤的工作流程。 记得早些时候的上下文内存特征吗 ? 这是它如何在现实世界的无序操作中闪耀的。
例如,Mostlucid.net的翻译服务显示,LLM如何在整个同步工作流程中保持状态:
# Step 1: Start translation
curl -X POST http://localhost:5000/api/translate/start?context=translate-session \
-d '{"language": "es", "markdown": "# Hello World"}'
# Response: { "taskId": "abc-123", "status": "processing" }
# Step 2: Check status (LLM remembers the task)
curl http://localhost:5000/api/translate/status/abc-123?context=translate-session
# Response: { "taskId": "abc-123", "status": "complete" }
# Step 3: Get result (same taskId!)
curl http://localhost:5000/api/translate/result/abc-123?context=translate-session
# Response: { "taskId": "abc-123", "translatedText": "# Hola Mundo" }
通知如何 taskId 所有要求均一致。 背景使这一点成为可能。
到目前为止,我们一直关注REST,但现代应用需要更多。无论你是与GreagQL一起建造,还是与信号R一起安装实时功能,还是与GRPC服务公司合作,大多数都是Lucid.mockllmapi由你负责。
支持的协议 :
指南: 图图QL部分
curl -X POST http://localhost:5000/api/mock/graphql \
-d '{"query": "{ users { id name email } }"}'
查询是形状 - 不需要单独的计划 。
完整的指南 : gRPPC 支持
# Upload .proto file
curl -X POST http://localhost:5116/api/grpc-protos \
--data-binary "@user_service.proto"
# Call via JSON or binary Protobuf
curl -X POST http://localhost:5116/api/grpc/userservice/UserService/GetUser \
-d '{"user_id": 123}'
指南: 信号R演示指南
const connection = new signalR.HubConnectionBuilder()
.withUrl("/hub/mock")
.build();
connection.on("DataUpdate", (message) => {
console.log(message.data); // Live generated data
});
await connection.start();
await connection.invoke("SubscribeToContext", "stock-prices");
完美的仪表板原型设计。
指南: SSE 流模式
const eventSource = new EventSource('/api/mock/stream/users');
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('Token:', data.chunk); // Progressive generation
};
完整的指南 : OpenAPI 特征
# CLI: Load any OpenAPI spec
llmock serve --spec https://petstore3.swagger.io/api/v3/openapi.json
# All endpoints become live mocks automatically
curl http://localhost:5000/petstore/pet/123
完整的指南 : 工具与动作
有时,您需要一种混合方法 — 生产中的真实数据与生成的模拟数据相结合。 插入工具系统允许您在模拟生成时使用实际的 API , 从而创建出令人难以置信的现实的测试情景 。
{
"Tools": [{
"Name": "getUserData",
"Type": "http",
"HttpConfig": {
"Endpoint": "https://api.production.com/users/{userId}",
"Headers": { "Authorization": "Bearer ${PROD_API_KEY}" }
}
}]
}
curl "http://localhost:5000/api/mock/orders?useTool=getUserData&userId=123"
模拟获取真正的用户数据,然后LLM生成使用它的命令。 对以混合模拟/实际工作流程进行现实测试极为有用。
如果您正在与 ASP.NET 核心一起建设, 整合是无缝的。 这个方法的美丽之处在于 零代码修改 您的服务 - 简单配置 HttpClient 在开发过程中和生产的实际消费物价指数中指向模型。
// Real code from mostlylucid.net
builder.Services.AddHttpClient<IMarkdownTranslatorService, MarkdownTranslatorService>(
client => {
var baseUrl = builder.Configuration["TranslationService:BaseUrl"]
?? "http://localhost:5000"; // Mock during dev
client.BaseAddress = new Uri(baseUrl);
}
);
开发.json:
{
"TranslationService": {
"BaseUrl": "http://localhost:5000" // Mock
}
}
应用。 production.json:
{
"TranslationService": {
"BaseUrl": "https://api.production.com" // Real
}
}
此模式适用于任何 HttpClient 在您的申请中 - 翻译服务、付款网关、外部API, 您可点名 。
在我们潜入先进功能之前, 让我们先弄清楚这个工具 何时对你的工作流程有意义。
完美于 :
不理想的有:
现在你知道它适合哪里了 我们来探索一下先进的能力
这些特质是可选的 — — 你可以从基础中单独获得巨大的价值。 但是当你需要规模的生产级现实主义时,这些工具就在这里。
指南: 多个 LLM 后端
# Fast for dev
curl http://localhost:5000/api/mock/users
# High quality for demos
curl "http://localhost:5000/api/mock/users?backend=quality"
# Cloud AI for production-like
curl "http://localhost:5000/api/mock/users?backend=openai"
指南: 节率限制和节拍
测试您的应用程序如何处理利率限制 :
{
"EnableRateLimiting": true,
"RateLimitDelayRange": "500-2000"
}
# Test 429 rate limiting
curl "http://localhost:5000/api/mock/users?error=429&errorMessage=Rate%20limit%20exceeded"
# Test 503 unavailable
curl "http://localhost:5000/api/mock/users?error=503"
支持所有4xx和5xx代码。
# Generate and cache 10 variants
curl "http://localhost:5000/api/mock/users?shape={\"$cache\":10,\"id\":0,\"name\":\"string\"}"
随后的请求得到即时缓存答复。
套件 : 大多为mockllmapi。 测试
上述所有特征对于发展来说都是巨大的,但是自动化测试呢?配套测试软件包提供了流流利的API,使整合测试成为微风 — 配置模拟行为。 HttpClient 其余的做。
dotnet add package mostlylucid.mockllmapi.Testing
using mostlylucid.mockllmapi.Testing;
// Create a client with a single endpoint configuration
var client = HttpClientExtensions.CreateMockLlmClient(
baseAddress: "http://localhost:5116",
pathPattern: "/users",
configure: endpoint => endpoint
.WithShape(new { id = 0, name = "", email = "" })
.WithCache(5)
);
// Make requests - configuration is automatically applied
var response = await client.GetAsync("/users");
var users = await response.Content.ReadFromJsonAsync<User[]>();
var client = HttpClientExtensions.CreateMockLlmClient(
"http://localhost:5116",
configure: handler => handler
.ForEndpoint("/users", config => config
.WithShape(new { id = 0, name = "", email = "" })
.WithCache(10))
.ForEndpoint("/posts", config => config
.WithShape(new { id = 0, title = "", content = "", authorId = 0 })
.WithCache(20))
.ForEndpoint("/error", config => config
.WithError(404, "Resource not found"))
);
// Each endpoint automatically uses its configuration
var usersResponse = await client.GetAsync("/users");
var postsResponse = await client.GetAsync("/posts");
var errorResponse = await client.GetAsync("/error"); // Returns 404
形状配置 :
// Using anonymous objects
.WithShape(new { id = 0, name = "", active = true })
// Using JSON strings
.WithShape("{ \"id\": 0, \"name\": \"\", \"tags\": [] }")
// Complex nested structures
.WithShape(new
{
user = new { id = 0, name = "" },
posts = new[] { new { id = 0, title = "" } }
})
错误模拟 :
// Simple error
.WithError(404)
// With custom message
.WithError(404, "User not found")
// With details
.WithError(422, "Validation failed", "Email address is invalid")
串流 :
// Enable streaming with token-by-token output
.WithStreaming()
.WithSseMode("LlmTokens")
// Stream complete objects
.WithStreaming()
.WithSseMode("CompleteObjects")
// Stream array items individually
.WithStreaming()
.WithSseMode("ArrayItems")
输入的客户端 :
services.AddMockLlmHttpClient<IUserApiClient>(
baseApiPath: "/api/mock",
configure: handler => handler
.ForEndpoint("/users", config => config
.WithShape(new { id = 0, name = "", email = "" }))
);
命名客户端 :
services.AddMockLlmHttpClient(
name: "MockApi",
baseApiPath: "/api/mock",
configure: handler => handler
.ForEndpoint("/data", config => config
.WithShape(new { value = 0 }))
);
// Usage
var client = httpClientFactory.CreateClient("MockApi");
[Fact]
public async Task Should_Handle_User_Creation()
{
// Arrange
var client = HttpClientExtensions.CreateMockLlmClient(
"http://localhost:5116",
"/users",
config => config
.WithMethod("POST")
.WithShape(new { id = 0, name = "", email = "", createdAt = "" })
);
// Act
var newUser = new { name = "John Doe", email = "[email protected]" };
var response = await client.PostAsJsonAsync("/users", newUser);
// Assert
response.EnsureSuccessStatusCode();
var created = await response.Content.ReadFromJsonAsync<User>();
Assert.NotNull(created);
Assert.NotEqual(0, created.Id);
}
[Fact]
public async Task Should_Handle_Not_Found_Error()
{
// Arrange
var client = HttpClientExtensions.CreateMockLlmClient(
"http://localhost:5116",
"/users/999",
config => config.WithError(404, "User not found")
);
// Act
var response = await client.GetAsync("/users/999");
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
缩略 MockLlmHttpHandler 是 a 是 DelegatingHandler 并且:
这允许您使用真实的 HttpClient 在测试中,在不修改应用代码的情况下,很容易控制模拟API行为。
与这个工具合作后, 在多个项目中, 以下是最有效的模式:
ministral-3:3b (3B参数,32K上下文) - 杀杰森的凶手! 超快、高度准确、最低记录和档案管理llama3 (8B参数,8K上下文) -- -- 最佳质量和业绩平衡mistral-nemo (12B参数,128K上下文) -- -- 复杂模型和大型数据集gemma3:4b 或 phi3 - 较轻替代品前端开发不需要等待后端 APIs。 mostlylucid.mockllmapi 给予您 :
这与传统嘲笑的区别? 您的前端对从第一天开始的现实的、有背景意识的数据起作用。 没有更多的“它用模拟数据工作,但用真实数据失败了 ” 惊喜。
无论你正在建立一个简单的博客还是一个复杂的企业应用程序, 你都会更快速,更彻底地测试, 并且有信心地航行。
准备好开始了吗?
docker compose up -d
就是这样,不需要后端
© 2026 Scott Galloway — Unlicense — All content and source code on this site is free to use, copy, modify, and sell.