| 版本 | 日期 | 描述 | 作者 |
|---|---|---|---|
| 3.0 | 2025-10-20 | 集团AI智能进销存系统AI服务集成 | Winston |
graph TD
A[业务系统] --> B[AI服务网关]
B --> C[销售预测服务]
B --> D[库存优化服务]
B --> E[供应商匹配服务]
B --> F[客户分析服务]
B --> G[产品推荐服务]
C --> H[历史销售数据]
C --> I[市场趋势数据]
D --> J[当前库存数据]
D --> K[需求预测数据]
E --> L[供应商数据库]
E --> M[采购需求数据]
F --> N[客户行为数据]
F --> O[交易历史数据]
G --> P[产品目录数据]
G --> Q[销售历史数据]
G --> R[客户偏好数据]
S[DeepSeek API] --> T[文本理解]
S --> U[数据分析]
S --> V[智能推荐]
C --> S
D --> S
E --> S
F --> S
G --> S
style A fill:#e1f5fe
style B fill:#f3e5f5
style S fill:#fff0f5
// DeepSeek API配置
interface DeepSeekConfig {
apiKey: string;
baseUrl: string; // https://api.deepseek.com
model: 'deepseek-chat' | 'deepseek-coder';
maxTokens: number;
temperature: number;
timeout: number;
}
// 统一的AI服务客户端
class DeepSeekAIClient {
constructor(private config: DeepSeekConfig) {}
async chatCompletion(messages: ChatMessage[]): Promise<ChatResponse> {
const response = await fetch(`${this.config.baseUrl}/chat/completions`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.config.apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: this.config.model,
messages,
max_tokens: this.config.maxTokens,
temperature: this.config.temperature
})
});
if (!response.ok) {
throw new Error(`DeepSeek API error: ${response.statusText}`);
}
return await response.json();
}
}
// 提示词模板
class PromptTemplates {
// 销售预测提示词
static salesForecast(data: SalesForecastData): ChatMessage[] {
return [
{
role: 'system',
content: `你是一个专业的销售预测AI助手。基于历史销售数据、市场趋势和季节性因素,为进销存系统提供准确的销售预测。请以JSON格式返回预测结果。`
},
{
role: 'user',
content: `请分析以下销售数据并预测未来${data.period}的销售情况:
历史销售数据:
${JSON.stringify(data.historicalData, null, 2)}
市场趋势:
${JSON.stringify(data.marketTrends, null, 2)}
季节性因素:
${JSON.stringify(data.seasonalityFactors, null, 2)}
请返回以下格式的JSON:
{
"forecasts": [
{
"productId": 1,
"productName": "产品名称",
"dailyForecasts": [
{
"date": "2025-10-21",
"predictedQuantity": 100,
"confidenceInterval": [80, 120],
"factors": ["季节性需求", "促销活动"]
}
],
"totalForecast": 1000,
"growthRate": 0.15,
"seasonality": 0.8
}
],
"confidence": 0.85,
"reasoning": "预测理由...",
"modelVersion": "deepseek-chat-v1"
}`
}
];
}
// 库存优化提示词
static inventoryOptimization(data: InventoryOptimizationData): ChatMessage[] {
return [
{
role: 'system',
content: `你是一个专业的库存优化AI助手。基于当前库存水平、需求预测和成本因素,为进销存系统提供最优的库存管理建议。请以JSON格式返回优化结果。`
},
{
role: 'user',
content: `请分析以下库存数据并提供优化建议:
当前库存状况:
${JSON.stringify(data.products, null, 2)}
需求预测:
${JSON.stringify(data.demandForecast, null, 2)}
成本因素:
${JSON.stringify(data.costFactors, null, 2)}
请返回以下格式的JSON:
{
"recommendations": [
{
"productId": 1,
"recommendedStock": 500,
"reorderPoint": 200,
"orderQuantity": 300,
"urgency": "medium",
"costBenefit": 1500,
"factors": ["需求增长", "库存成本"]
}
],
"totalCostSavings": 5000,
"serviceLevelImprovement": 0.1,
"reasoning": "优化理由...",
"modelVersion": "deepseek-chat-v1"
}`
}
];
}
// 供应商匹配提示词
static supplierMatching(data: SupplierMatchingData): ChatMessage[] {
return [
{
role: 'system',
content: `你是一个专业的供应商匹配AI助手。基于采购需求、供应商能力和历史表现,为进销存系统推荐最合适的供应商。请以JSON格式返回匹配结果。`
},
{
role: 'user',
content: `请分析以下采购需求并推荐合适的供应商:
采购需求:
${JSON.stringify(data.purchaseRequirements, null, 2)}
可选供应商:
${JSON.stringify(data.availableSuppliers, null, 2)}
约束条件:
${JSON.stringify(data.constraints, null, 2)}
请返回以下格式的JSON:
{
"matches": [
{
"supplierId": 1,
"supplierName": "供应商名称",
"overallScore": 0.85,
"priceScore": 0.9,
"qualityScore": 0.8,
"deliveryScore": 0.85,
"reliabilityScore": 0.9,
"totalCost": 10000,
"estimatedDelivery": "2025-10-25",
"riskFactors": ["交付延迟风险"]
}
],
"bestMatch": {...},
"confidence": 0.88,
"reasoning": "匹配理由...",
"modelVersion": "deepseek-chat-v1"
}`
}
];
}
// 客户分析提示词
static customerAnalysis(data: CustomerAnalysisData): ChatMessage[] {
return [
{
role: 'system',
content: `你是一个专业的客户分析AI助手。基于客户交易数据和行为模式,为进销存系统提供客户细分、价值评估和流失预测。请以JSON格式返回分析结果。`
},
{
role: 'user',
content: `请分析以下客户数据并提供深入洞察:
客户数据:
${JSON.stringify(data.customers, null, 2)}
交易历史:
${JSON.stringify(data.transactionHistory, null, 2)}
分析类型:${data.analysisType}
请返回以下格式的JSON:
{
"analyses": [
{
"customerId": 1,
"customerName": "客户名称",
"lifetimeValue": 50000,
"churnProbability": 0.15,
"segment": "高价值客户",
"behaviorPatterns": ["频繁购买", "偏好高端产品"],
"recommendations": ["个性化促销", "VIP服务"]
}
],
"segments": [
{
"segmentId": "high_value",
"segmentName": "高价值客户",
"customerCount": 50,
"characteristics": ["高消费", "高忠诚度"],
"valueScore": 0.9
}
],
"insights": ["客户流失率上升", "新客户增长强劲"],
"modelVersion": "deepseek-chat-v1"
}`
}
];
}
// 产品推荐提示词
static productRecommendation(data: ProductRecommendationData): ChatMessage[] {
return [
{
role: 'system',
content: `你是一个专业的产品推荐AI助手。基于客户历史购买行为、产品属性和市场趋势,为进销存系统提供个性化的产品推荐。请以JSON格式返回推荐结果。`
},
{
role: 'user',
content: `请基于以下数据为指定客户提供产品推荐:
客户信息:
${JSON.stringify(data.customer, null, 2)}
客户购买历史:
${JSON.stringify(data.purchaseHistory, null, 2)}
可选产品:
${JSON.stringify(data.availableProducts, null, 2)}
推荐场景:${data.scenario}
推荐数量:${data.recommendationCount}
请返回以下格式的JSON:
{
"recommendations": [
{
"productId": 1,
"productName": "产品名称",
"recommendationScore": 0.92,
"reasoning": "基于客户的购买历史和产品偏好",
"matchFactors": ["价格匹配", "功能相似", "品牌偏好"],
"expectedInterest": 0.85,
"crossSellProducts": [2, 3],
"upSellProducts": [4]
}
],
"personalizedMessage": "根据您的购买历史,我们为您推荐以下产品...",
"confidence": 0.88,
"modelVersion": "deepseek-chat-v1"
}`
}
];
}
}
// 销售预测请求
interface SalesForecastRequest {
companyId: number;
productIds: number[];
period: '7d' | '30d' | '90d';
historicalData: SalesHistory[];
marketTrends?: MarketTrendData;
seasonalityFactors?: SeasonalityFactors;
}
interface SalesHistory {
productId: number;
date: Date;
quantity: number;
price: number;
promotion: boolean;
}
// 销售预测响应
interface SalesForecastResponse {
forecasts: ProductForecast[];
confidence: number;
reasoning: string;
modelVersion: string;
timestamp: Date;
}
interface ProductForecast {
productId: number;
productName: string;
dailyForecasts: DailyForecast[];
totalForecast: number;
growthRate: number;
seasonality: number;
}
interface DailyForecast {
date: Date;
predictedQuantity: number;
confidenceInterval: [number, number];
factors: ForecastFactor[];
}
// 库存优化请求
interface InventoryOptimizationRequest {
companyId: number;
warehouseId: number;
products: ProductStockInfo[];
demandForecast: DemandForecast[];
leadTimes: LeadTimeData[];
costFactors: CostFactors;
}
interface ProductStockInfo {
productId: number;
currentStock: number;
minStock: number;
maxStock: number;
safetyStock: number;
unitCost: number;
holdingCost: number;
}
// 库存优化响应
interface InventoryOptimizationResponse {
recommendations: StockRecommendation[];
totalCostSavings: number;
serviceLevelImprovement: number;
reasoning: string;
timestamp: Date;
}
interface StockRecommendation {
productId: number;
recommendedStock: number;
reorderPoint: number;
orderQuantity: number;
urgency: 'low' | 'medium' | 'high' | 'critical';
costBenefit: number;
factors: OptimizationFactor[];
}
// 供应商匹配请求
interface SupplierMatchingRequest {
companyId: number;
purchaseRequirements: PurchaseRequirement[];
preferredSuppliers?: number[];
constraints: MatchingConstraints;
}
interface PurchaseRequirement {
productId: number;
quantity: number;
qualityRequirements: QualityRequirements;
deliveryDeadline: Date;
budget: number;
}
// 供应商匹配响应
interface SupplierMatchingResponse {
matches: SupplierMatch[];
bestMatch: SupplierMatch;
confidence: number;
reasoning: string;
timestamp: Date;
}
interface SupplierMatch {
supplierId: number;
supplierName: string;
overallScore: number;
priceScore: number;
qualityScore: number;
deliveryScore: number;
reliabilityScore: number;
totalCost: number;
estimatedDelivery: Date;
riskFactors: RiskFactor[];
}
// 客户分析请求
interface CustomerAnalysisRequest {
companyId: number;
customerIds: number[];
analysisType: 'segmentation' | 'lifetime_value' | 'churn_prediction' | 'behavior_analysis';
historicalPeriod: '30d' | '90d' | '365d';
}
// 客户分析响应
interface CustomerAnalysisResponse {
analyses: CustomerAnalysis[];
segments: CustomerSegment[];
insights: BusinessInsight[];
timestamp: Date;
}
interface CustomerAnalysis {
customerId: number;
customerName: string;
lifetimeValue: number;
churnProbability: number;
segment: string;
behaviorPatterns: BehaviorPattern[];
recommendations: CustomerRecommendation[];
}
interface CustomerSegment {
segmentId: string;
segmentName: string;
customerCount: number;
characteristics: SegmentCharacteristic[];
valueScore: number;
}
// 产品推荐请求
interface ProductRecommendationRequest {
companyId: number;
customerId: number;
scenario: 'cross_sell' | 'up_sell' | 'new_customer' | 'abandoned_cart';
recommendationCount: number;
availableProducts: AvailableProduct[];
customerPreferences?: CustomerPreferences;
constraints?: RecommendationConstraints;
}
interface AvailableProduct {
productId: number;
productName: string;
category: string;
brand: string;
price: number;
stock: number;
attributes: ProductAttribute[];
popularity: number;
}
interface CustomerPreferences {
priceRange: [number, number];
preferredBrands: string[];
preferredCategories: string[];
excludedProducts: number[];
}
interface RecommendationConstraints {
maxPrice: number;
minStock: number;
excludeOutOfStock: boolean;
includeOnlyAvailable: boolean;
}
// 产品推荐响应
interface ProductRecommendationResponse {
recommendations: ProductRecommendation[];
personalizedMessage: string;
confidence: number;
modelVersion: string;
timestamp: Date;
}
interface ProductRecommendation {
productId: number;
productName: string;
recommendationScore: number;
reasoning: string;
matchFactors: MatchFactor[];
expectedInterest: number;
crossSellProducts: number[];
upSellProducts: number[];
}
interface MatchFactor {
type: 'price_match' | 'feature_similarity' | 'brand_preference' | 'category_match';
score: number;
description: string;
}
// AI任务队列服务
class AITaskQueueService {
constructor(private redis: Redis, private aiService: AIService) {}
// 提交AI任务
async submitAITask<T>(taskType: string, request: any): Promise<string> {
const taskId = generateTaskId();
const task: AITask<T> = {
id: taskId,
type: taskType,
request,
status: 'pending',
createdAt: new Date(),
priority: 'normal'
};
// 存储任务到Redis
await this.redis.set(`ai_task:${taskId}`, JSON.stringify(task));
// 添加到任务队列
await this.redis.lpush(`ai_tasks:${taskType}`, taskId);
return taskId;
}
// 处理AI任务
async processAITasks(): Promise<void> {
while (true) {
const taskId = await this.redis.rpop(`ai_tasks:sales_forecast`);
if (!taskId) {
await sleep(1000);
continue;
}
const taskData = await this.redis.get(`ai_task:${taskId}`);
if (!taskData) continue;
const task: AITask = JSON.parse(taskData);
try {
// 执行AI任务
const result = await this.deepSeekClient.executeTask(task.type, task.request);
// 更新任务状态
task.status = 'completed';
task.result = result;
task.completedAt = new Date();
await this.redis.set(`ai_task:${taskId}`, JSON.stringify(task));
} catch (error) {
task.status = 'failed';
task.error = error.message;
await this.redis.set(`ai_task:${taskId}`, JSON.stringify(task));
}
}
}
}
// AI结果缓存服务
class AIResultCacheService {
constructor(private redis: Redis) {}
// 缓存AI结果
async cacheAIResult<T>(cacheKey: string, result: T, ttl: number = 3600): Promise<void> {
const cacheData: AICacheData<T> = {
data: result,
cachedAt: new Date(),
expiresAt: new Date(Date.now() + ttl * 1000)
};
await this.redis.setex(cacheKey, ttl, JSON.stringify(cacheData));
}
// 获取缓存结果
async getCachedResult<T>(cacheKey: string): Promise<T | null> {
const cached = await this.redis.get(cacheKey);
if (!cached) return null;
const cacheData: AICacheData<T> = JSON.parse(cached);
// 检查是否过期
if (new Date() > cacheData.expiresAt) {
await this.redis.del(cacheKey);
return null;
}
return cacheData.data;
}
// 生成缓存键
generateCacheKey(service: string, companyId: number, params: any): string {
const paramHash = createHash('md5').update(JSON.stringify(params)).digest('hex');
return `ai:${service}:${companyId}:${paramHash}`;
}
}
// AI服务降级策略
class AIDegradationService {
// 规则引擎作为AI降级方案
private ruleEngine = new RuleEngine();
async getSalesForecast(request: SalesForecastRequest): Promise<SalesForecastResponse> {
try {
// 使用DeepSeek API进行销售预测
const messages = PromptTemplates.salesForecast(request);
const response = await this.deepSeekClient.chatCompletion(messages);
// 解析DeepSeek返回的JSON
return JSON.parse(response.choices[0].message.content);
} catch (error) {
console.warn('DeepSeek API不可用,使用规则引擎降级处理');
// 使用规则引擎作为降级方案
return await this.ruleEngine.getSalesForecast(request);
}
}
async getSupplierRecommendations(request: SupplierMatchingRequest): Promise<SupplierMatchingResponse> {
try {
// 使用DeepSeek API进行供应商匹配
const messages = PromptTemplates.supplierMatching(request);
const response = await this.deepSeekClient.chatCompletion(messages);
// 解析DeepSeek返回的JSON
return JSON.parse(response.choices[0].message.content);
} catch (error) {
console.warn('DeepSeek API不可用,使用基于规则的供应商匹配');
// 基于历史表现和基本规则的供应商匹配
return await this.ruleBasedSupplierMatching(request);
}
}
private async ruleBasedSupplierMatching(request: SupplierMatchingRequest): Promise<SupplierMatchingResponse> {
// 基于价格、质量、交付时间的加权评分
const suppliers = await this.supplierService.findEligibleSuppliers(request);
const matches = suppliers.map(supplier => {
const score = this.calculateSupplierScore(supplier, request);
return {
supplierId: supplier.id,
supplierName: supplier.name,
overallScore: score,
priceScore: this.calculatePriceScore(supplier, request),
qualityScore: supplier.rating / 5,
deliveryScore: this.calculateDeliveryScore(supplier),
reliabilityScore: supplier.performance.deliveryRate,
totalCost: this.calculateTotalCost(supplier, request),
estimatedDelivery: this.estimateDelivery(supplier),
riskFactors: []
};
});
return {
matches: matches.sort((a, b) => b.overallScore - a.overallScore),
bestMatch: matches[0],
confidence: 0.7, // 规则引擎置信度较低
reasoning: '基于规则的供应商匹配',
timestamp: new Date()
};
}
}
// AI决策确认服务
class AIDecisionConfirmationService {
async confirmAIDecision<T>(
decision: T,
decisionType: string,
userId: number
): Promise<ConfirmedDecision<T>> {
// 记录AI决策
const aiDecision: AIDecision<T> = {
id: generateDecisionId(),
type: decisionType,
aiResult: decision,
confidence: decision.confidence || 0.8,
createdAt: new Date(),
status: 'pending_confirmation'
};
// 保存到数据库
await this.decisionRepository.save(aiDecision);
// 如果置信度低于阈值,需要人工确认
if (aiDecision.confidence < this.confirmationThreshold) {
await this.requireHumanConfirmation(aiDecision.id, userId);
return {
...decision,
requiresConfirmation: true,
decisionId: aiDecision.id
};
}
// 高置信度决策自动确认
await this.confirmDecision(aiDecision.id, userId, 'auto_confirmed');
return {
...decision,
requiresConfirmation: false,
decisionId: aiDecision.id
};
}
async confirmDecision(decisionId: string, userId: number, confirmationType: string): Promise<void> {
const decision = await this.decisionRepository.findOne(decisionId);
if (!decision) throw new Error('决策不存在');
decision.status = 'confirmed';
decision.confirmedBy = userId;
decision.confirmedAt = new Date();
decision.confirmationType = confirmationType;
await this.decisionRepository.save(decision);
}
}
// AI模型反馈服务
class AIModelFeedbackService {
async collectFeedback<T>(
decisionId: string,
actualOutcome: T,
userFeedback: UserFeedback
): Promise<void> {
const feedback: AIFeedback<T> = {
decisionId,
actualOutcome,
userFeedback,
collectedAt: new Date(),
modelVersion: userFeedback.modelVersion
};
// 存储反馈数据
await this.feedbackRepository.save(feedback);
// 定期批量发送到AI服务进行模型训练
await this.queueFeedbackForTraining(feedback);
}
async queueFeedbackForTraining(feedback: AIFeedback<any>): Promise<void> {
const trainingBatch: TrainingBatch = {
id: generateBatchId(),
feedbacks: [feedback],
status: 'pending',
createdAt: new Date()
};
await this.trainingQueue.add(trainingBatch);
// 当积累足够数据时触发模型训练
const pendingCount = await this.trainingQueue.getPendingCount();
if (pendingCount >= this.trainingThreshold) {
await this.triggerModelTraining();
}
}
async triggerModelTraining(): Promise<void> {
const pendingBatches = await this.trainingQueue.getPendingBatches();
// 准备训练数据
const trainingData = this.prepareTrainingData(pendingBatches);
// 使用DeepSeek API进行模型微调(如果支持)
// 或者将反馈数据用于改进提示词工程
await this.improvePromptTemplates(trainingData);
// 标记批次为已处理
await this.trainingQueue.markAsProcessed(pendingBatches.map(b => b.id));
}
}
interface AIServiceHealth {
service: string;
status: 'healthy' | 'degraded' | 'unhealthy';
responseTime: number;
errorRate: number;
lastCheck: Date;
modelVersion: string;
features: string[];
}
// AI服务监控
class AIServiceMonitor {
async checkServiceHealth(): Promise<AIServiceHealth[]> {
const services = ['sales_forecast', 'inventory_optimization', 'supplier_matching', 'customer_analysis', 'product_recommendation'];
const healthChecks = await Promise.all(
services.map(async service => {
try {
const startTime = Date.now();
await this.aiService.healthCheck(service);
const responseTime = Date.now() - startTime;
return {
service,
status: 'healthy',
responseTime,
errorRate: 0,
lastCheck: new Date(),
modelVersion: await this.getModelVersion(service),
features: await this.getSupportedFeatures(service)
};
} catch (error) {
return {
service,
status: 'unhealthy',
responseTime: -1,
errorRate: 1,
lastCheck: new Date(),
modelVersion: 'unknown',
features: []
};
}
})
);
return healthChecks;
}
}
这个基于DeepSeek API的统一AI服务集成架构确保了集团AI智能进销存系统的智能化决策能力,同时通过完善的降级策略、缓存机制和监控体系,保证了系统的稳定性和可靠性。