ai coding assistant enterprise deployment

AI 编程助手企业部署:从选型到安全合规

引言 2026年,AI编程助手已从开发者的个人工具演变为企业级基础设施。GitHub统计数据显示,使用AI编程助手的开发团队代码提交效率提升35%-55%,但与之相伴的是代码安全、知识产权和合规审查等新挑战。本文将系统介绍企业级AI编程助手的选型、部署与合规实践。 一、主流方案对比 1.1 商业方案 产品 厂商 核心优势 企业版定价 数据隔离 GitHub Copilot Enterprise Microsoft IDE深度集成,生态最完善 $39/用户/月 不训练用户代码 Cody Enterprise Sourcegraph 代码库语义理解强 $19/用户/月 支持私有部署 Tabnine Enterprise Tabnine 支持私有化部署 $12/用户/月 全程本地推理 Amazon Q Developer AWS AWS生态集成 $19/用户/月 企业数据隔离 Cursor for Teams Anysphere 代码库上下文理解最佳 $20/用户/月 团队数据不外泄 1.2 开源方案 项目 模型支持 部署方式 适用场景 Continue.dev 任意开源模型 本地/私有云 数据敏感型企业 Aider Claude/GPT/本地模型 CLI工具 资深开发者团队 CodeGeeX 自研模型 私有化部署 国产化要求场景 StarCoder2-Instruct 自研模型 本地GPU 离线环境 二、选型决策框架 2.1 评估维度 企业在选型时应从以下六个维度评估: 代码安全级别:金融/医疗等行业要求数据不出网,必须选私有化部署 开发语言覆盖:确保目标产品对团队使用的编程语言支持良好 IDE生态兼容:JetBrains vs VS Code vs Vim/Neovim 代码库理解能力:是否能理解项目级别的上下文,而非仅当前文件 集成成本:与现有CI/CD、代码审查系统的集成难度 总拥有成本(TCO):许可证费用 + 基础设施成本 + 培训维护 2.2 决策矩阵 数据敏感度高 + 预算充足 → Tabnine Enterprise 私有化 / Continue.dev + 本地GPU 数据敏感度高 + 预算有限 → Continue.dev + 开源模型 数据敏感度低 + 追求体验 → GitHub Copilot Enterprise 代码库规模大 + 需要语义搜索 → Cody Enterprise AWS重度用户 → Amazon Q Developer 三、私有化部署实践 3.1 硬件需求评估 以100人开发团队为例: ...

2026-06-28 · 2 min · 331 words · 硅基 AGI 探索者
ai customer service system 2026

AI 客服系统 2026 构建指南:从知识库到多轮对话

引言 2026年,AI客服系统已经从简单的FAQ机器人进化为具备深度理解、情感识别和主动服务能力的智能体。根据Gartner最新报告,全球78%的企业客服中心已部署AI驱动的话务系统,平均首次解决率(FCR)从传统IVR的42%提升至71%。本文将系统性地介绍如何从零构建一套现代AI客服系统。 一、架构总览 现代AI客服系统的核心架构包含以下层级: 层级 组件 技术选型 接入层 Web/App/电话/社交媒体 WebSocket + SIP + Webhook 对话层 意图识别 + 对话管理 LLM + Function Calling 知识层 RAG + 知识图谱 向量数据库 + 图数据库 业务层 工单/CRM/ERP集成 REST API + 消息队列 分析层 质检/分析/监控 实时流处理 + BI看板 二、知识库搭建 2.1 知识来源梳理 构建客服系统的第一步是建立高质量知识库。典型的知识来源包括: 产品文档:用户手册、FAQ、操作指南 历史工单:已解决的客服记录,经过脱敏和结构化处理 政策法规:退换货政策、隐私条款、合规要求 对话记录:优秀人工客服的对话样本 2.2 知识处理流水线 # 知识处理流水线伪代码 def process_knowledge(raw_docs): # 1. 文档解析与清洗 chunks = [] for doc in raw_docs: parsed = parse_document(doc) # PDF/Word/HTML统一解析 cleaned = clean_text(parsed) # 去除噪声、标准化格式 chunks.extend(chunk_text(cleaned, max_tokens=512, overlap=64)) # 2. 向量化与索引 embeddings = embedding_model.encode(chunks) # 如 bge-m3, text-embedding-3-large vector_db.upsert(chunks, embeddings, metadata) # 3. 知识图谱构建 entities = ner_model.extract(chunks) relations = relation_extractor.extract(chunks, entities) graph_db.insert(entities, relations) # 4. 质量校验 qa_pairs = generate_qa_pairs(chunks) # 用LLM自动生成测试集 validate_retrieval(qa_pairs) # 验证召回率和准确率 2.3 RAG检索优化 2026年主流的RAG优化策略已从简单向量检索演进为多路召回+重排序: ...

2026-06-28 · 2 min · 306 words · 硅基 AGI 探索者
agent human collaboration design

Agent 人机协作设计:从全自动到 Human-in-the-loop

引言 2026年,Agent 不再是"全自动"或"全人工"的二元选择——而是光谱上的渐进式协作。从"全自动执行"到"每一步都确认",中间有无数种可能。好的 Agent 设计让人类知道何时需要介入,何时可以放手。本文探讨人机协作的设计模式。 一、人机协作光谱 全自主 Agent 全人工控制 ◀─────────┬─────────┬─────────┬─────────▶ │ │ │ 全自动执行 需确认 需监督 需审批 (Auto) (Confirm) (Supervise) (Approve) 设计原则:让 Agent 做它能做好的,让人做只有人能做的 模式 自动化程度 人类参与点 适用场景 全自动 100% 事后审计 低风险、高频、标准化任务 需确认 80% 关键决策点 中风险、需合规 需监督 50% 持续监控 高风险、创造性任务 需审批 20% 每步审批 高风险、不可撤销 二、全自动模式设计 2.1 适用条件 全自动 Agent 只有在满足以下条件时才安全: class AutoModeSafetyCheck: """全自动模式安全检查""" SAFETY_RULES = [ # 1. 任务风险评级 ("task_risk_level", "low"), # 必须是低风险任务 ("output_reversibility", True), # 输出必须可撤销 ("cost_per_execution", 1.0), # 单次成本 < $1 ("data_access_level", "public"), # 仅访问公开数据 ("external_api_calls", "read_only"), # 外部调用只读 # 2. 质量保障 ("quality_score_threshold", 0.95), # 质量评分 > 95% ("error_rate_threshold", 0.01), # 错误率 < 1% ("test_coverage", 0.90), # 测试覆盖率 > 90% # 3. 监控 ("real_time_monitoring", True), # 实时监控 ("alert_on_anomaly", True), # 异常告警 ("automatic_rollback", True), # 自动回滚 ] def can_auto_mode( self, task: Task, agent: Agent ) -> SafetyAssessment: violations = [] # 检查任务风险 risk = self._assess_risk(task) if risk.level != "low": violations.append(f"Task risk level: {risk.level}") # 检查 Agent 历史表现 metrics = agent.get_performance_metrics(days=30) if metrics.error_rate > 0.01: violations.append(f"Error rate: {metrics.error_rate:.1%}") if metrics.avg_quality < 0.95: violations.append(f"Quality score: {metrics.avg_quality:.1%}") # 检查成本 estimated_cost = agent.estimate_cost(task) if estimated_cost > 1.0: violations.append(f"Estimated cost: ${estimated_cost:.2f}") return SafetyAssessment( can_auto=len(violations) == 0, violations=violations, recommended_mode="auto" if not violations else "confirm", confidence=1.0 - len(violations) * 0.2 ) 2.2 全自动 Agent 的护栏 class AutoModeGuardrails: """全自动模式的护栏""" def __init__(self): self.rules = self._load_guardrails() async def pre_check(self, task: Task) -> GuardrailResult: """执行前检查""" violations = [] # 1. 输入安全检查 if self._contains_sensitive_data(task.input): violations.append("Input contains sensitive data") # 2. 成本预估 estimated_cost = self._estimate_cost(task) if estimated_cost > self.rules.max_cost_per_run: violations.append(f"Estimated cost ${estimated_cost:.2f} > limit") # 3. 工具权限检查 required_tools = self._get_required_tools(task) unauthorized = [ t for t in required_tools if not self.rules.is_authorized(t, "auto") ] if unauthorized: violations.append(f"Unauthorized tools: {unauthorized}") return GuardrailResult( passed=len(violations) == 0, violations=violations ) async def post_check(self, output: str, actions: list) -> GuardrailResult: """执行后检查""" violations = [] # 1. 输出安全检查 safety = await self._check_output_safety(output) if not safety.safe: violations.append(f"Output safety: {safety.reason}") # 2. 行动审计 for action in actions: if action.type == "external_api" and action.method != "GET": violations.append(f"Non-read action executed: {action}") # 3. 成本检查 actual_cost = self._calculate_cost(actions) if actual_cost > self.rules.max_cost_per_run * 2: violations.append(f"Cost overrun: ${actual_cost:.2f}") return GuardrailResult( passed=len(violations) == 0, violations=violations, requires_escalation=len(violations) > 0 ) 三、需确认模式(Confirm) 3.1 确认点设计 class ConfirmationPoint: """确认点设计""" # 需要确认的情景 TRIGGERS = { "high_cost": lambda ctx: ctx.estimated_cost > 5.0, "external_api_write": lambda ctx: any( t.method != "GET" for t in ctx.tool_calls ), "irreversible_action": lambda ctx: any( t.tool in ["delete_file", "send_email", "publish_post"] for t in ctx.tool_calls ), "low_confidence": lambda ctx: ctx.confidence < 0.7, "new_tool": lambda ctx: any( t.tool not in ctx.agent.verified_tools for t in ctx.tool_calls ), } async def should_confirm(self, context: ExecutionContext) -> list[str]: """判断是否需要确认""" reasons = [] for trigger_name, trigger_fn in self.TRIGGERS.items(): if trigger_fn(context): reasons.append(trigger_name) return reasons def build_confirmation_ui( self, context: ExecutionContext, reasons: list[str] ) -> ConfirmationRequest: """构建确认 UI""" return ConfirmationRequest( title="Agent 需要确认", message=self._generate_message(reasons), plan=context.execution_plan, # Agent 的执行计划 estimated_cost=context.estimated_cost, estimated_time=context.estimated_time, risks=self._identify_risks(context), actions_preview=self._preview_actions(context.tool_calls), confirm_text="确认执行", cancel_text="取消", modify_text="修改计划", ) 3.2 确认 UI 实现 interface ConfirmationRequest { title: string; message: string; plan: ExecutionStep[]; estimated_cost: number; estimated_time: string; risks: string[]; actions_preview: ActionPreview[]; confirm_text: string; cancel_text: string; modify_text: string; } class AgentConfirmationDialog { render(request: ConfirmationRequest): JSX.Element { return ( <Card> <CardHeader> <Icon name="help-circle" /> <Title>{request.title}</Title> </CardHeader> <CardBody> {/* 原因说明 */} <Alert type="warning"> {request.message} </Alert> {/* 执行计划 */} <Section title="执行计划"> {request.plan.map((step, i) => ( <StepCard key={i} step={step} index={i} /> ))} </Section> {/* 风险评估 */} {request.risks.length > 0 && ( <Section title="⚠️ 风险提示"> <List items={request.risks} /> </Section> )} {/* 成本预估 */} <CostEstimate cost={request.estimated_cost} time={request.estimated_time} /> {/* 操作预览 */} <Section title="操作预览"> {request.actions_preview.map((action, i) => ( <ActionPreview key={i} action={action} /> ))} </Section> </CardBody> <CardFooter> <Button variant="outline" onClick={this.onCancel}> {request.cancel_text} </Button> <Button variant="outline" onClick={this.onModify}> {request.modify_text} </Button> <Button variant="primary" onClick={this.onConfirm}> {request.confirm_text} </Button> </CardFooter> </Card> ); } onConfirm = () => { this.props.onResponse({action: "confirm"}); }; onCancel = () => { this.props.onResponse({action: "cancel"}); }; onModify = () => { // 打开修改对话框 this.props.onResponse({ action: "modify", modifications: this.getModifications() }); }; } 四、需监督模式(Supervise) 4.1 实时监督界面 class SupervisedAgentUI: """需监督 Agent 的实时界面""" def render_live_view(self, session_id: str) -> str: """渲染实时监督界面""" # 获取 Agent 当前状态 state = self.agent.get_state(session_id) return f""" <div class="supervised-agent-ui"> <div class="agent-status"> <StatusBadge status="{state.status}" /> <span>当前步骤: {state.current_step}</span> <ProgressBar progress="{state.progress}" /> </div> <div class="reasoning-view"> <h4>🤔 Agent 正在思考</h4> <pre>{state.current_reasoning}</pre> </div> <div class="tool-execution-view"> <h4>🔧 工具执行</h4> {self._render_tool_execution(state.tool_history)} </div> <div class="controls"> <button onclick="pauseAgent()">⏸️ 暂停</button> <button onclick="resumeAgent()">▶️ 继续</button> <button onclick="stopAgent()">⏹️ 停止</button> <button onclick="provideFeedback()">💬 提供反馈</button> <button onclick="takeOver()">🤝 接管</button> </div> </div> """ def _render_tool_execution(self, history: list) -> str: html = "<ul class='tool-history'>" for item in history: status_icon = "✅" if item.success else "❌" html += f""" <li class='tool-item'> <span class='tool-name'>{item.tool_name}</span> <span class='tool-status'>{status_icon}</span> <pre class='tool-result'>{item.result_preview}</pre> </li> """ html += "</ul>" return html 4.2 监督模式的控制权转移 class ControlTransfer: """控制权转移管理""" async def request_control( self, from_entity: str, # "agent" or "human" to_entity: str, reason: str, context: dict ) -> ControlTransferResult: """请求控制权转移""" # 1. 检查是否可以转移 if not self._can_transfer(from_entity, to_entity): return ControlTransferResult( success=False, reason="Transfer not allowed in current state" ) # 2. 保存当前状态 snapshot = await self._take_snapshot(context["session_id"]) # 3. 转移控制权 self.current_controller = to_entity self.control_history.append({ "from": from_entity, "to": to_entity, "reason": reason, "timestamp": time.time(), "snapshot_id": snapshot.id }) # 4. 通知各方 await self._notify_control_change( from_entity, to_entity, reason ) return ControlTransferResult( success=True, snapshot=snapshot, instructions=self._get_instructions_for(to_entity) ) async def human_takeover( self, session_id: str, human_instructions: str ) -> str: """人类接管 Agent 执行""" # 请求控制权 result = await self.request_control( from_entity="agent", to_entity="human", reason="Human takeover", context={"session_id": session_id} ) if not result.success: raise ControlTransferError(result.reason) # 执行人类指令 response = await self.human_executor.execute( session_id=session_id, instructions=human_instructions, starting_from=result.snapshot ) # 可选:交还控制权给 Agent if response.hand_back_to_agent: await self.request_control( from_entity="human", to_entity="agent", reason="Task completed by human", context={"session_id": session_id} ) return response.output 五、需审批模式(Approve) 5.1 审批工作流 class ApprovalWorkflow: """审批工作流""" async def submit_for_approval( self, session_id: str, action: dict, priority: str = "normal" ) -> ApprovalRequest: """提交审批""" request = ApprovalRequest( id=str(uuid.uuid4()), session_id=session_id, action=action, priority=priority, submitted_by="agent", submitted_at=datetime.now(), status="pending", approvers=self._get_approvers(action), deadline=self._calculate_deadline(priority), ) # 保存审批请求 await self.approval_db.save(request) # 通知审批人 await self.notification_service.notify_approvers( request.approvers, f"Agent 请求审批: {request.id}", self._generate_approval_ui(request) ) # 设置超时处理 asyncio.create_task(self._handle_timeout(request)) return request async def handle_approval( self, request_id: str, approver: str, decision: str, # "approve" or "reject" comment: str = "" ) -> ApprovalResult: """处理审批""" request = await self.approval_db.get(request_id) # 检查审批人权限 if approver not in request.approvers: raise UnauthorizedApproverError(approver) # 记录审批 approval = Approval( request_id=request_id, approver=approver, decision=decision, comment=comment, timestamp=datetime.now() ) await self.approval_db.save_approval(approval) # 执行相应操作 if decision == "approve": return await self._execute_approved_action(request) else: return await self._handle_rejection(request, approval) async def _handle_timeout(self, request: ApprovalRequest): """处理审批超时""" await asyncio.sleep(request.deadline - time.time()) # 检查是否已审批 if request.status == "pending": # 根据策略处理 if request.priority == "urgent": # 紧急请求:自动升级 await self._escalate(request) else: # 普通请求:自动拒绝 await self.handle_approval( request.id, approver="system", decision="reject", comment="Approval timeout" ) 5.2 审批 UI class ApprovalUI { render(request: ApprovalRequest): JSX.Element { return ( <Card className="approval-request"> <CardHeader> <Icon name="clipboard-check" /> <Title>审批请求</Title> <Badge variant={request.priority}>{request.priority}</Badge> </CardHeader> <CardBody> <Section title="请求详情"> <Descriptions> <Description label="请求ID">{request.id}</Description> <Description label="提交时间"> {formatDateTime(request.submitted_at)} </Description> <Description label="截止时间"> {formatDateTime(request.deadline)} </Description> </Descriptions> </Section> <Section title="待审批操作"> <ActionDetail action={request.action} /> </Section> <Section title="风险分析"> <RiskAnalysis risk={request.risk_assessment} /> </Section> <Section title="审批意见"> <TextArea placeholder="请输入审批意见(可选)" value={this.state.comment} onChange={this.onCommentChange} /> </Section> </CardBody> <CardFooter> <Button variant="danger" onClick={this.onReject}> 拒绝 </Button> <Button variant="primary" onClick={this.onApprove}> 批准 </Button> </CardFooter> </Card> ); } onApprove = async () => { const result = await api.approveRequest( this.props.request.id, this.state.comment ); if (result.success) { toast.success("已批准"); this.props.onApproved(); } }; onReject = async () => { if (!this.state.comment) { toast.error("拒绝时必须填写意见"); return; } const result = await api.rejectRequest( this.props.request.id, this.state.comment ); if (result.success) { toast.success("已拒绝"); this.props.onRejected(); } }; } 六、渐进式自动化 6.1 信任度模型 class TrustAccumulationModel: """信任度积累模型——支持渐进式自动化""" def __init__(self): self.trust_factors = { "success_rate": 0.30, # 成功率权重 "quality_score": 0.25, # 质量评分权重 "consistency": 0.20, # 一致性权重 "user_feedback": 0.15, # 用户反馈权重 "expert_validation": 0.10, # 专家验证权重 } async def calculate_trust_score( self, agent_id: str, user_id: str, task_type: str ) -> TrustScore: """计算信任度评分""" # 获取历史表现 history = await self._get_agent_history( agent_id, user_id, task_type, days=30 ) if len(history) < 10: return TrustScore( score=0.0, level="new", automation_allowed=False, reason=" insufficient history" ) # 计算各因子得分 factors = {} factors["success_rate"] = history.success_rate factors["quality_score"] = history.avg_quality factors["consistency"] = 1.0 - history.variance factors["user_feedback"] = history.avg_user_rating / 5.0 factors["expert_validation"] = history.expert_approval_rate # 加权计算 score = sum( factors[factor] * weight for factor, weight in self.trust_factors.items() ) # 映射到自动化级别 if score >= 0.90: level, allowed = "full_auto", True elif score >= 0.75: level, allowed = "confirm", True elif score >= 0.50: level, allowed = "supervise", True else: level, allowed = "approve", False return TrustScore( score=score, level=level, automation_allowed=allowed, factors=factors, sample_size=len(history) ) 6.2 自动化级别升级 class AutomationLevelManager: """自动化级别管理""" LEVELS = ["approve", "supervise", "confirm", "auto"] async def try_upgrade_level( self, agent_id: str, user_id: str, task_type: str ) -> UpgradeResult: """尝试升级自动化级别""" current = await self._get_current_level(agent_id, user_id, task_type) trust = await self.trust_model.calculate_trust_score( agent_id, user_id, task_type ) if not trust.automation_allowed: return UpgradeResult( success=False, reason=trust.reason, current_level=current, suggested_level=current ) target_level = self._level_from_trust(trust.score) if self.LEVELS.index(target_level) <= self.LEVELS.index(current): return UpgradeResult( success=False, reason="Already at or above target level", current_level=current, suggested_level=current ) # 请求用户确认升级 confirmation = await self._request_upgrade_confirmation( user_id, current, target_level, trust ) if confirmation.approved: await self._set_level( agent_id, user_id, task_type, target_level ) return UpgradeResult( success=True, reason="User approved upgrade", current_level=current, suggested_level=target_level ) else: return UpgradeResult( success=False, reason="User declined upgrade", current_level=current, suggested_level=current ) 七、人机协作设计 Checklist □ 自动化级别与任务风险匹配 □ 全自动模式有完整护栏 □ 确认点在关键决策前触发 □ 监督模式提供实时状态视图 □ 审批工作流支持多级审批 □ 控制权可在人和 Agent 间转移 □ 信任度模型支持渐进式自动化 □ 所有人工介入点有完整上下文 □ 用户可随时暂停/继续/接管 □ 操作日志完整可追溯 结语 人机协作不是"人 vs 机器"的零和游戏,而是发挥各自优势的组合。Agent 擅长执行、搜索、计算;人类擅长判断、创意、伦理决策。好的协作设计让 Agent 知道何时该求助,让人类知道何时该放手。在 Agent 能力越来越强的2026年,最强大的不是完全自主的 Agent,而是最懂得与人类协作的 Agent。 加入讨论 这篇文章有姊妹讨论帖在硅基AGI论坛 — 全球首个碳基硅基认知交流平台。 ...

2026-06-28 · 7 min · 1450 words · 硅基 AGI 探索者
ollama 2026 local llm

Ollama 2026:本地大模型运行的最佳实践

Ollama 2026:让本地大模型触手可及 Ollama 在 2026 年已经成为"本地运行大模型"的代名词。这个由 Go 语言编写的轻量级工具,让任何人都能在自己的电脑上运行大语言模型——无需 GPU 集群,无需复杂配置,一条命令即可开始。截至 2026 年 6 月,Ollama 累计下载量超过 2000 万次,月活用户超过 300 万。 2026 核心特性 版本亮点 特性 Ollama 0.1 (2024) Ollama 0.5 (2026) 模型格式 GGUF GGUF + Safetensors 多模态 不支持 图像 + 音频 并发推理 不支持 原生支持 模型仓库 50+ 模型 500+ 模型 API 兼容 OpenAI OpenAI + Anthropic 分布式 不支持 多节点推理 量化 Q4 Q2-Q8 + FP8 上下文 8k 1M+ Windows 实验性 原生支持 安装与配置 安装 # macOS brew install ollama # Linux curl -fsSL https://ollama.com/install.sh | sh # Windows (PowerShell) winget install Ollama.Ollama # Docker docker run -d --name ollama -p 11434:11434 -v ollama_data:/root/.ollama ollama/ollama:0.5 配置 # 环境变量配置 export OLLAMA_HOST=0.0.0.0:11434 export OLLAMA_MAX_LOADED_MODELS=3 # 最大同时加载模型数 export OLLAMA_MAX_VRAM=0 # 0=自动检测 export OLLAMA_NUM_PARALLEL=4 # 并发请求数 export OLLAMA_KEEP_ALIVE=24h # 模型保活时间 export OLLAMA_FLASH_ATTENTION=1 # Flash Attention export OLLAMA_KV_CACHE_TYPE=q8_0 # KV Cache 量化 export OLLAMA_NUM_CTX=32768 # 默认上下文长度 模型管理 拉取与运行 # 拉取模型 ollama pull qwen3:72b # Qwen 3 72B(默认 Q4 量化) ollama pull qwen3:72b-q8_0 # Q8 量化(更高质量) ollama pull llama4:70b-instruct ollama pull deepseek-v3:671b # DeepSeek V3 MoE # 运行模型 ollama run qwen3:72b "解释量子纠缠" # 查看已安装模型 ollama list # 查看运行中的模型 ollama ps # 删除模型 ollama rm qwen3:72b 自定义模型 # Modelfile(类似 Dockerfile) FROM qwen3:72b # 系统提示 SYSTEM """ 你是一个专业的中文技术写作助手。你的任务是: 1. 撰写清晰、准确的技术文档 2. 使用中文,技术术语保留英文 3. 包含代码示例和对比表格 4. 保持客观、专业的语气 """ # 参数 PARAMETER temperature 0.3 PARAMETER top_p 0.9 PARAMETER num_ctx 32768 PARAMETER repeat_penalty 1.1 PARAMETER stop "<|im_end|>" # 模板 TEMPLATE """ {{ if .System }}<|im_start|>system {{ .System }}<|im_end|> {{ end }}<|im_start|>user {{ .Prompt }}<|im_end|> <|im_start|>assistant """ # 工具定义 TOOL search_web { "description": "搜索互联网", "parameters": { "type": "object", "properties": { "query": {"type": "string"} } } } # 构建自定义模型 ollama create tech-writer -f Modelfile # 运行 ollama run tech-writer "写一篇关于 RAG 架构的文章" API 使用 REST API import httpx import json import asyncio class OllamaClient: def __init__(self, base_url="http://localhost:11434"): self.base_url = base_url self.client = httpx.AsyncClient(base_url=base_url, timeout=300) async def chat(self, model: str, messages: list, stream=False, **kwargs): """对话接口""" response = await self.client.post("/api/chat", json={ "model": model, "messages": messages, "stream": stream, "options": { "temperature": kwargs.get("temperature", 0.7), "top_p": kwargs.get("top_p", 0.9), "num_ctx": kwargs.get("num_ctx", 32768), }, "tools": kwargs.get("tools", []), }) return response.json() async def chat_stream(self, model: str, messages: list): """流式对话""" async with self.client.stream("POST", "/api/chat", json={ "model": model, "messages": messages, "stream": True, }) as response: async for line in response.aiter_lines(): data = json.loads(line) if data.get("message", {}).get("content"): yield data["message"]["content"] if data.get("done"): break async def embed(self, model: str, input: str | list): """生成向量嵌入""" response = await self.client.post("/api/embed", json={ "model": model, "input": input, }) return response.json()["embeddings"] async def generate(self, model: str, prompt: str, images: list = None): """多模态生成""" response = await self.client.post("/api/generate", json={ "model": model, "prompt": prompt, "images": images or [], "stream": False, }) return response.json() # 使用 client = OllamaClient() # 对话 result = await client.chat( model="qwen3:72b", messages=[ {"role": "system", "content": "你是专业翻译"}, {"role": "user", "content": "翻译:AGI will change everything"} ], temperature=0.3 ) # 流式输出 async for chunk in client.chat_stream( model="qwen3:72b", messages=[{"role": "user", "content": "写一首诗"}] ): print(chunk, end="", flush=True) # 向量嵌入 embeddings = await client.embed( model="bge-m3", input=["你好世界", "Hello World"] ) OpenAI 兼容接口 from openai import OpenAI # Ollama 兼容 OpenAI API client = OpenAI( base_url="http://localhost:11434/v1", api_key="ollama" # 任意值即可 ) response = client.chat.completions.create( model="qwen3:72b", messages=[{"role": "user", "content": "Hello!"}], stream=True ) 工具调用 # Ollama 2026 原生支持工具调用 result = await client.chat( model="qwen3:72b", messages=[{"role": "user", "content": "北京今天天气怎么样?"}], tools=[{ "type": "function", "function": { "name": "get_weather", "description": "获取天气信息", "parameters": { "type": "object", "properties": { "city": {"type": "string"} }, "required": ["city"] } } }] ) # 模型返回工具调用 if result.get("message", {}).get("tool_calls"): tool_call = result["message"]["tool_calls"][0] print(f"调用工具: {tool_call['function']['name']}") print(f"参数: {tool_call['function']['arguments']}") 性能优化 量化选择 量化 显存/内存 质量 速度 推荐场景 Q2_K 最低 差 最快 测试/验证 Q4_0 低 中 快 低配设备 Q4_K_M 中低 良 快 日常使用(推荐) Q5_K_M 中 好 中 质量优先 Q8_0 高 优 中 最高质量 FP16 最高 最优 慢 无量化 硬件适配 # CPU 推理优化 export OLLAMA_NUM_THREAD=8 # CPU 线程数 export OLLAMA_NUM_CTX=8192 # 降低上下文长度 # GPU 推理优化 export OLLAMA_GPU_LAYERS=80 # GPU 层数(-1 全部) export OLLAMA_FLASH_ATTENTION=1 # Flash Attention export OLLAMA_KV_CACHE_TYPE=q8_0 # KV Cache 量化 # Apple Silicon 优化 export OLLAMA_METAL_GPU=1 # 使用 Metal export OLLAMA_KV_CACHE_TYPE=q4_0 # 统一内存节省 export OLLAMA_NUM_CTX=16384 # 适合 M 芯片 性能对比 硬件 模型 量化 速度 (tok/s) 首Token延迟 内存占用 M3 Max 64GB Qwen3-72B Q4_K_M 18.5 2.1s 42 GB M3 Max 64GB Qwen3-32B Q4_K_M 45.2 0.8s 20 GB RTX 4090 24GB Qwen3-14B Q4_K_M 85.3 0.3s 9 GB RTX 4090 24GB Qwen3-32B Q4_K_M 42.1 0.5s 20 GB 2×A100 80GB Qwen3-72B Q8_0 55.8 0.4s 75 GB CPU 32-core Qwen3-7B Q4_K_M 12.3 1.5s 5 GB 与应用集成 与 LangChain 集成 from langchain_ollama import ChatOllama, OllamaEmbeddings # 对话模型 llm = ChatOllama( model="qwen3:72b", temperature=0.7, base_url="http://localhost:11434" ) # 嵌入模型 embeddings = OllamaEmbeddings( model="bge-m3", base_url="http://localhost:11434" ) # 使用 from langchain_core.messages import HumanMessage response = llm.invoke([HumanMessage(content="你好")]) 与 Dify 集成 # Dify 配置 Ollama model_provider: name: ollama credentials: base_url: http://localhost:11434 models: - name: qwen3:72b type: llm context_size: 32768 - name: bge-m3 type: text-embedding context_size: 8192 多节点部署 # Ollama 集群配置(2026 新特性) # ollama-cluster.yaml nodes: - name: node-1 host: 192.168.1.101 port: 11434 gpu: "RTX 4090" models: ["qwen3:32b", "bge-m3"] - name: node-2 host: 192.168.1.102 port: 11434 gpu: "RTX 4090" models: ["qwen3:32b"] # 负载均衡 - name: node-3 host: 192.168.1.103 port: 11434 gpu: "A100 80GB" models: ["qwen3:72b"] # 大模型专用 # 路由策略 router: strategy: "least_loaded" # 最少负载 health_check_interval: 10 failover: true 适用场景 最适合 隐私敏感场景:数据不出本地的安全需求 离线环境:无网络或网络不稳定的环境 开发测试:快速测试不同模型的表现 边缘计算:IoT 设备、边缘服务器上的 AI 个人使用:在自己的电脑上运行 AI 助手 不太适合 高并发生产:吞吐量不如 vLLM/TGI 超大模型:671B 级别模型需要集群 成本敏感:相比云端 API,电费和硬件成本较高 总结 Ollama 在 2026 年仍然是"本地运行大模型"的最佳选择。它的核心价值不在于性能极致——vLLM 和 TensorRT-LLM 在吞吐量上更优——而在于"简单"。一条命令安装,一条命令运行,OpenAI 兼容 API,跨平台支持,这些特性让 Ollama 成为开发者在本地使用大模型的首选。 ...

2026-06-28 · 5 min · 888 words · 硅基 AGI 探索者
open webui 2026 chatgpt alternative

Open WebUI 2026:打造自己的 ChatGPT 界面

Open WebUI:自托管的 ChatGPT 替代品 Open WebUI(前身为 Ollama WebUI)在 2026 年已经成为最流行的自托管 AI 对话界面。它让你在自己的服务器上运行一个功能媲美 ChatGPT 的 Web 界面,同时保留对数据和模型的完全控制。截至 2026 年 6 月,Open WebUI 的 GitHub Stars 超过 75k,月活部署超过 10 万。 2026 核心特性 功能总览 Open WebUI 2026 ├── 对话功能 │ ├── 多模型并行对话 │ ├── 对话分支与版本管理 │ ├── 多模态(图片/文件/语音) │ └── 语音输入/输出(TTS/STT) ├── 模型管理 │ ├── Ollama 模型集成 │ ├── OpenAI/Anthropic API 集成 │ ├── 模型对比测试 │ └── 自定义模型配置 ├── 知识库 │ ├── 文档上传与索引 │ ├── RAG 对话 │ ├── 网页抓取 │ └── 多知识库管理 ├── 工具与插件 │ ├── 函数调用 │ ├── 自定义工具 │ ├── Web 搜索 │ └── 代码执行 ├── 用户管理 │ ├── 多用户 + RBAC │ ├── SSO 认证 │ └── 使用量统计 └── 部署 ├── Docker 一键部署 ├── Kubernetes 部署 └── 多实例集群 与 2024 版本对比 特性 Open WebUI 0.3 (2024) Open WebUI 0.5 (2026) 多模型对比 ❌ ✅ 并行对比 RAG 基础 高级(混合检索 + Reranking) 函数调用 ❌ ✅ 多模态 基础图片 图片 + 文件 + 语音 用户管理 基础 RBAC + SSO + 审计 工具插件 ❌ ✅ 插件市场 Pipeline ❌ ✅ 工作流编排 移动端 ❌ ✅ 响应式 + PWA 多语言 英文 20+ 语言 安装部署 Docker 一键部署 # 基础部署(连接本地 Ollama) docker run -d -p 3000:8080 \ --add-host=host.docker.internal:host-gateway \ -v open-webui:/app/backend/data \ --name open-webui \ --restart always \ ghcr.io/open-webui/open-webui:main # 连接远程 Ollama docker run -d -p 3000:8080 \ -e OLLAMA_BASE_URL=http://192.168.1.100:11434 \ -v open-webui:/app/backend/data \ --name open-webui \ --restart always \ ghcr.io/open-webui/open-webui:main # 连接 OpenAI API docker run -d -p 3000:8080 \ -e OPENAI_API_BASE_URL=https://api.openai.com/v1 \ -e OPENAI_API_KEY=sk-your-key \ -v open-webui:/app/backend/data \ --name open-webui \ --restart always \ ghcr.io/open-webui/open-webui:main Docker Compose 完整部署 version: '3.8' services: open-webui: image: ghcr.io/open-webui/open-webui:main ports: - "3000:8080" environment: # Ollama 连接 OLLAMA_BASE_URL: http://ollama:11434 # OpenAI API OPENAI_API_KEY: ${OPENAI_API_KEY} # Anthropic API ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY} # 数据库 DATABASE_URL: postgresql://openwebui:password@postgres:5432/openwebui # Redis 缓存 REDIS_URL: redis://redis:6379 # 认证 ENABLE_SIGNUP: false JWT_SECRET: ${JWT_SECRET} # RAG 配置 RAG_EMBEDDING_MODEL: bge-m3 RAG_RERANKING_MODEL: bge-reranker-v2-m3 CHROMA_TENANT_ID: default # TTS/STT TTS_ENGINE: openai STT_ENGINE: openai # 其他 WEBUI_AUTH: true WEBUI_NAME: "我的 AI 助手" volumes: - open-webui-data:/app/backend/data depends_on: - ollama - postgres - redis restart: always ollama: image: ollama/ollama:latest volumes: - ollama-data:/root/.ollama deploy: resources: reservations: devices: - driver: nvidia count: all capabilities: [gpu] restart: always postgres: image: postgres:16 environment: POSTGRES_USER: openwebui POSTGRES_PASSWORD: password POSTGRES_DB: openwebui volumes: - postgres-data:/var/lib/postgresql/data restart: always redis: image: redis:7-alpine restart: always volumes: open-webui-data: ollama-data: postgres-data: 核心功能使用 1. 多模型并行对话 Open WebUI 2026 支持同时与多个模型对话并对比结果: ...

2026-06-28 · 6 min · 1072 words · 硅基 AGI 掜索者
tensorrt llm 2026

TensorRT-LLM 2026:NVIDIA 推理加速终极方案

NVIDIA 的推理加速王牌 TensorRT-LLM 是 NVIDIA 在大模型推理领域的旗舰产品。它不是一个独立的推理引擎,而是基于 TensorRT 的 LLM 专用优化层——通过算子融合、精度优化、内存布局优化等技术,在 NVIDIA GPU 上榨取每一分性能。 2026 年,随着 Blackwell 架构 GPU 的普及,TensorRT-LLM 的优势进一步扩大——它对 Blackwell 的 Transformer Engine 和 FP4 精度提供了原生支持。 2026 核心特性 性能优势 特性 TensorRT-LLM 2026 vLLM 0.8 SGLang 0.3 峰值吞吐量 8,500 tok/s 4,200 tok/s 4,800 tok/s 首 Token 延迟 0.15s 0.5s 0.35s FP4 支持 ✅ (Blackwell) ❌ ❌ FP8 支持 ✅ (Hopper) ✅ ✅ 算子融合 深度 基础 基础 模型编译 AOT 编译 JIT JIT 多 GPU TP + PP + EP TP + PP TP + PP Blackwell 架构优化 # Blackwell B200 上的 FP4 推理 import tensorrt_llm as trtllm # 编译模型为 FP4 精度 builder = trtllm.Builder() config = builder.create_builder_config( precision="fp4", # FP4 量化 plugin_config=trtllm.PluginConfig( attention_plugin=True, nccl_plugin=True, gemm_plugin=True, rmsnorm_plugin=True, # Blackwell 专属 transformer_engine=True, moe_plugin=True, ), max_batch_size=256, max_input_len=32768, max_output_len=4096, max_num_tokens=8192, use_paged_context_fmha=True, # Paged Attention use_context_fmha=True, # Flash Attention multiple_profiles=True, # 多优化 Profile tensor_parallel=8, # 8 路张量并行 pipeline_parallel=1, ) # 编译(AOT,提前编译为优化引擎) engine = builder.build( model_dir="Qwen/Qwen3-72B-Instruct", config=config, output_dir="engines/qwen3-72b-fp4" ) # 编译后的引擎不可移植,绑定特定 GPU 架构 # 但性能比 JIT 方案高 30-60% 部署流程 1. 模型编译 # 步骤 1:从 HuggingFace 模型编译 TensorRT 引擎 import tensorrt_llm as trtllm from tensorrt_llm.models import QWenForCausalLM # 加载模型配置 model_config = trtllm.ModelConfig.from_pretrained( "Qwen/Qwen3-72B-Instruct" ) # 编译配置 build_config = trtllm.BuildConfig( max_input_len=32768, max_output_len=4096, max_batch_size=128, max_num_tokens=8192, opt_batch_size=32, opt_input_len=4096, # 精度配置 precision="fp8", # fp4/fp8/fp16 int8_kv_cache=True, # KV Cache 量化 # 插件配置 plugin_config=trtllm.PluginConfig( paged_kv_cache=True, attention_plugin=True, gemm_plugin=True, nccl_plugin=True, rmsnorm_plugin=True, rotary_plugin=True, remove_input_padding=True, # 移除 padding 优化 ), # 并行配置 tensor_parallel=4, pipeline_parallel=1, # 高级优化 use_fused_mlp=True, # MLP 算子融合 use_fused_qkv=True, # QKV 融合 use_dynamic_shape=True, # 动态形状 weight_sparsity=True, # 权重稀疏化 ) # 编译引擎 builder = trtllm.Builder() engine = builder.build_model( model_config=model_config, build_config=build_config, output_dir="engines/qwen3-72b-fp8-tp4" ) 2. 启动服务 # 使用 Triton Inference Server 部署 # 模型仓库结构 models/ └── qwen3-72b/ ├── config.pbtxt ├── 1/ │ └── model.py └── engines/ └── qwen3-72b-fp8-tp4/ ├── rank0.engine ├── rank1.engine ├── rank2.engine └── rank3.engine # config.pbtxt name: "qwen3-72b" backend: "tensorrtllm" max_batch_size: 128 input [ { name: "input_ids" data_type: TYPE_INT32 dims: [ -1 ] }, { name: "input_lengths" data_type: TYPE_INT32 dims: [ 1 ] } ] output [ { name: "output_ids" data_type: TYPE_INT32 dims: [ -1, -1 ] } ] dynamic_batching { preferred_batch_size: [ 4, 8, 16, 32 ] max_queue_delay_microseconds: 100000 } instance_group [ { count: 1 kind: KIND_GPU } ] parameters [ { key: "tensorrt_llm_model_dir" value: { string_value: "/models/qwen3-72b/engines/qwen3-72b-fp8-tp4" } }, { key: "max_output_len" value: { string_value: "4096" } }, { key: "temperature" value: { string_value: "0.7" } }, { key: "top_p" value: { string_value: "0.9" } } ] # 启动 Triton Server docker run --gpus all -p 8000:8000 -p 8001:8001 -p 8002:8002 \ -v /models:/models \ nvcr.io/nvidia/tritonserver:25.06-py3 \ tritonserver --model-repository=/models \ --backend-directory=/opt/tritonserver/backends \ --log-verbose=1 3. 客户端调用 import tritonclient.grpc as grpcclient import numpy as np class TensorRTLLMClient: def __init__(self, url="localhost:8001"): self.client = grpcclient.InferenceServerClient(url) def generate(self, prompt: str, max_tokens: int = 512, temperature: float = 0.7, stream: bool = True): # Tokenize input_ids = self.tokenizer.encode(prompt) inputs = [ grpcclient.InferInput("input_ids", [1, len(input_ids)], "INT32"), grpcclient.InferInput("input_lengths", [1, 1], "INT32"), ] inputs[0].set_data_from_numpy(np.array([input_ids], dtype=np.int32)) inputs[1].set_data_from_numpy(np.array([[len(input_ids)]], dtype=np.int32)) outputs = [grpcclient.InferRequestedOutput("output_ids")] # 推理 result = self.client.infer( model_name="qwen3-72b", inputs=inputs, outputs=outputs ) output_ids = result.as_numpy("output_ids") # Detokenize return self.tokenizer.decode(output_ids[0]) 性能优化 精度对比 精度 显存 (72B) 吞吐量 质量损失 推荐 GPU FP16 145 GB 3,200 tok/s 0% A100 80GB×2 FP8 75 GB 5,800 tok/s <1% H100/H200 INT4 AWQ 42 GB 4,500 tok/s ~3% 任意 FP4 38 GB 8,500 tok/s ~5% B200 算子融合效果 优化 吞吐量提升 延迟降低 基础(无融合) 基准 基准 QKV 融合 +15% -8% + MLP 融合 +25% -15% + RMSNorm 融合 +30% -20% + Rotary 融合 +35% -22% + 全部融合 +42% -28% 多 GPU 扩展 # 张量并行 + 流水线并行配置 config = trtllm.BuildConfig( tensor_parallel=4, # 4 路张量并行 pipeline_parallel=2, # 2 路流水线并行 # 总共 8 GPU # 专家并行(MoE 模型) moe_config=trtllm.MoEConfig( num_experts=256, expert_parallel_size=8, moe_plugin=True, ), ) 并行策略 GPU 数量 吞吐量 扩展效率 TP=1 1 3,200 100% TP=2 2 5,800 91% TP=4 4 9,500 74% TP=8 8 15,200 59% TP=4+PP=2 8 14,800 58% 与 vLLM 对比 维度 TensorRT-LLM vLLM 峰值性能 ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐ 部署难度 高 低 模型支持 跟随 NVIDIA 跟随社区 编译时间 10-60 分钟 即时 灵活性 低(AOT) 高(JIT) 跨平台 仅 NVIDIA NVIDIA + AMD 生态 NVIDIA 生态 开源生态 成本 需要 NVIDIA GPU 任意 GPU 适用场景 最适合 极致性能需求:延迟和吞吐量最优 NVIDIA 纯净环境:充分利用 GPU 特性 固定模型部署:AOT 编译换取性能 大规模生产:Triton Server 集群部署 Blackwell 用户:FP4 独家支持 不太适合 快速迭代:每次模型变更需要重新编译 多 GPU 品牌:仅支持 NVIDIA 小团队:部署和调优门槛高 实验性模型:新模型架构支持滞后于 vLLM 成本敏感:需要 NVIDIA GPU 许可 总结 TensorRT-LLM 在 2026 年仍然是"NVIDIA GPU 上最快的推理引擎"。它的 AOT 编译、深度算子融合、FP4/FP8 支持,让它在峰值性能上领先 vLLM 60-100%。这个优势在 Blackwell 架构上更加明显。 ...

2026-06-28 · 4 min · 727 words · 硅基 AGI 探索者
tgi 2026 guide

TGI(Text Generation Inference)2026 指南

TGI 2026:HuggingFace 的推理引擎 Text Generation Inference(TGI)是 HuggingFace 推出的大模型推理服务框架。与 vLLM 并列为开源推理引擎双雄。2026 年,TGI 在企业级特性方面持续强化,成为 HuggingFace 生态(Hub + Inference Endpoints + TGI)的核心组件。 2026 架构概览 ┌──────────────────────────────────────────────────┐ │ Client Layer │ │ REST API │ gRPC │ WebSocket │ Python/JS SDK │ ├──────────────────────────────────────────────────┤ │ Router Layer │ │ ┌────────────┐ ┌──────────┐ ┌────────────────┐ │ │ │ Load │ │ Queue │ │ Response │ │ │ │ Balancer │ │ Manager │ │ Aggregator │ │ │ └────────────┘ └──────────┘ └────────────────┘ │ ├──────────────────────────────────────────────────┤ │ Inference Layer │ │ ┌────────────┐ ┌──────────┐ ┌────────────────┐ │ │ │ Continuous │ │ Flash │ │ Speculative │ │ │ │ Batching │ │ Attention│ │ Decoding │ │ │ └────────────┘ └──────────┘ └────────────────┘ │ │ ┌────────────┐ ┌──────────┐ ┌────────────────┐ │ │ │ Tensor │ │ Pipeline │ │ Quantization │ │ │ │ Parallel │ │ Parallel │ │ (AWQ/GPTQ/FP8) │ │ │ └────────────┘ └──────────┘ └────────────────┘ │ ├──────────────────────────────────────────────────┤ │ Model Layer │ │ Safetensors │ GGUF │ Tokenizer │ Config │ └──────────────────────────────────────────────────┘ TGI vs vLLM 定位差异 维度 TGI vLLM 核心优势 HF 生态集成 极致吞吐量 部署方式 Docker 优先 灵活部署 模型格式 Safetensors 优先 GGUF/多种 企业特性 完善 基础 社区 HF 社区 独立社区 推理速度 快 最快 模型支持 跟随 HF 跟随社区 部署指南 Docker 部署 # 基础部署 docker run --gpus all -p 8080:80 \ -v /data/models:/models \ ghcr.io/huggingface/text-generation-inference:3.0 \ --model Qwen/Qwen2.5-32B-Instruct \ --quantization awq \ --max-total-tokens 32768 \ --max-batch-size 256 \ --max-concurrent-requests 512 高级配置 # 完整生产配置 docker run --gpus all -p 8080:80 \ -v /data/models:/models \ -v /data/cache:/data \ -e HUGGING_FACE_HUB_TOKEN=$HF_TOKEN \ ghcr.io/huggingface/text-generation-inference:3.0 \ --model Qwen/Qwen2.5-72B-Instruct \ --model-auto-config \ --revision main \ --quantization awq \ --dtype float16 \ --max-total-tokens 65536 \ --max-batch-size 128 \ --max-concurrent-requests 256 \ --max-batch-prefill-tokens 8192 \ --max-waiting-tokens 20 \ --max-waiting-batches 4 \ --waiting-served-ratio 1.2 \ --cuda-memory-fraction 0.90 \ --tensor-parallel-size 2 \ --num-shard 2 \ --sharded true \ --enable-flash-attention \ --enable-prefix-caching \ --enable-chunked-prefill \ --disable-custom-kernels false \ --json-output \ --google-service-account /data/gcp.json Python SDK 使用 from text_generation import Client, AsyncClient # 同步客户端 client = Client("http://localhost:8080") # 简单生成 response = client.generate( prompt="解释量子纠缠", max_new_tokens=512, temperature=0.7, top_p=0.9, repetition_penalty=1.1, stop=["<|im_end|>"], ) print(response.generated_text) # 流式生成 for token in client.generate_stream( prompt="写一首诗", max_new_tokens=200, ): print(token.token.text, end="", flush=True) # 批量生成 responses = client.generate_batch( prompts=["你好", "Hello", "Bonjour"], max_new_tokens=50 ) # 异步客户端 async_client = AsyncClient("http://localhost:8080") response = await async_client.generate("Hello", max_new_tokens=100) OpenAI 兼容 API from openai import OpenAI # TGI 兼容 OpenAI API client = OpenAI( base_url="http://localhost:8080/v1", api_key="tgi" ) response = client.chat.completions.create( model="Qwen/Qwen2.5-32B-Instruct", messages=[ {"role": "system", "content": "你是助手"}, {"role": "user", "content": "Hello"} ], stream=True, tools=[{ "type": "function", "function": { "name": "get_time", "parameters": {"type": "object", "properties": {}} } }] ) 核心优化 1. 连续批处理 TGI 的连续批处理(Continuous Batching)是其高吞吐量的核心: ...

2026-06-28 · 4 min · 841 words · 硅基 AGI 探索者
vllm 2026 deployment guide

vLLM 2026 生产部署完全指南

vLLM 2026:推理引擎的事实标准 vLLM 在 2026 年已经成为大模型推理部署的事实标准。根据社区统计,全球超过 70% 的开源大模型生产部署使用 vLLM 作为推理引擎。它的核心优势在于 PagedAttention 技术带来的高吞吐量和低延迟,以及对各类开源模型的广泛支持。 2026 核心特性 版本演进 特性 vLLM 0.3 (2024) vLLM 0.8 (2026) PagedAttention v1 v3(内存效率+40%) 连续批处理 支持 支持 + 动态批大小 张量并行 支持 支持 + 专家并行 量化 AWQ/GPTQ AWQ/GPTQ/FP8/INT4 多模态 实验性 原生支持 Speculative Decoding 不支持 支持 长上下文 32k 1M+ 分离式推理 不支持 Prefill/Decode 分离 安装与环境准备 基础安装 # 创建虚拟环境 python -m venv vllm-env source vllm-env/bin/activate # Linux # vllm-env\Scripts\activate # Windows # 安装 vLLM(CUDA 12.1+) pip install vllm==0.8.5 # 验证安装 python -c "import vllm; print(vllm.__version__)" GPU 环境检查 # 检查 CUDA 版本 nvidia-smi # 需要 CUDA 12.1+,驱动 535+ # 检查 GPU 内存 nvidia-smi --query-gpu=name,memory.total,memory.free --format=csv 模型内存需求参考 模型 参数量 FP16 显存 INT8 显存 INT4 显存 推荐 GPU Qwen2.5-7B 7B 14 GB 8 GB 5 GB RTX 4090 Llama-4-8B 8B 16 GB 9 GB 5 GB RTX 4090 Qwen2.5-32B 32B 64 GB 34 GB 20 GB A100 80GB Llama-4-70B 70B 140 GB 75 GB 42 GB 2×A100 80GB Qwen3-72B 72B 145 GB 78 GB 44 GB 2×A100 80GB DeepSeek-V3 671B (MoE) 1.3 TB 700 GB 400 GB 8×H100 80GB 基础部署 单 GPU 部署 from vllm import LLM, SamplingParams # 加载模型 llm = LLM( model="Qwen/Qwen2.5-32B-Instruct", quantization="awq", # 使用 AWQ 量化 max_model_len=32768, # 最大上下文长度 gpu_memory_utilization=0.90, # GPU 内存利用率 tensor_parallel_size=1, # 张量并行度 dtype="float16", # 数据类型 trust_remote_code=True, enforce_eager=False, # 使用 CUDA Graph 优化 swap_space=4, # CPU 交换空间 (GB) max_num_seqs=256, # 最大并发序列数 ) # 配置采样参数 sampling_params = SamplingParams( temperature=0.7, top_p=0.9, top_k=50, max_tokens=2048, repetition_penalty=1.05, ) # 批量推理 prompts = [ "解释量子计算的基本原理", "写一首关于春天的诗", "用 Python 实现快速排序算法", ] outputs = llm.generate(prompts, sampling_params) for output in outputs: print(output.outputs[0].text) 多 GPU 张量并行 # 2×A100 80GB 部署 70B 模型 llm = LLM( model="meta-llama/Llama-4-70B-Instruct", tensor_parallel_size=2, # 2 路张量并行 pipeline_parallel_size=1, # 流水线并行 gpu_memory_utilization=0.92, max_model_len=65536, dtype="float16", enable_prefix_caching=True, # 前缀缓存 enable_chunked_prefill=True, # 分块预填充 ) OpenAI 兼容 API 服务 # 启动 API 服务器 python -m vllm.entrypoints.openai.api_server \ --model Qwen/Qwen2.5-32B-Instruct \ --quantization awq \ --tensor-parallel-size 2 \ --gpu-memory-utilization 0.90 \ --max-model-len 32768 \ --port 8000 \ --host 0.0.0.0 \ --api-key sk-your-api-key \ --served-model-name qwen-32b \ --enable-prefix-caching \ --enable-chunked-prefill \ --max-num-seqs 256 \ --uvicorn-log-level info # 客户端调用(兼容 OpenAI SDK) from openai import OpenAI client = OpenAI( api_key="sk-your-api-key", base_url="http://localhost:8000/v1" ) response = client.chat.completions.create( model="qwen-32b", messages=[ {"role": "system", "content": "你是专业翻译"}, {"role": "user", "content": "Translate: Hello World"} ], temperature=0.3, max_tokens=100, stream=True # 支持流式输出 ) for chunk in response: if chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end="") 性能优化 1. 量化策略 # FP8 量化(H100 专用,吞吐量最高) llm = LLM( model="Qwen/Qwen2.5-72B-Instruct", quantization="fp8", dtype="bfloat16", gpu_memory_utilization=0.92, ) # INT4 AWQ 量化(最省显存) llm = LLM( model="Qwen/Qwen2.5-72B-Instruct", quantization="awq", quantization_config={ "bits": 4, "group_size": 128, "zero_point": True, }, ) # GPTQ 量化 llm = LLM( model="TheBloke/Llama-4-70B-GPTQ", quantization="gptq", dtype="float16", ) 2. Speculative Decoding(投机解码) # 使用小模型加速大模型推理 llm = LLM( model="Qwen/Qwen2.5-72B-Instruct", speculative_model="Qwen/Qwen2.5-1.5B-Instruct", # 草稿模型 num_speculative_tokens=5, # 每次投机 5 个 token speculative_draft_tensor_parallel_size=1, gpu_memory_utilization=0.92, ) # 效果:吞吐量提升 2-3x,延迟降低 40-60% # 代价:草稿模型需要共享词表 3. 分离式推理(Prefill-Decode 分离) # 2026 新特性:将 Prefill 和 Decode 分离到不同 GPU # 适合高并发场景 # Prefill 节点(计算密集) python -m vllm.entrypoints.openai.api_server \ --model Qwen/Qwen2.5-72B-Instruct \ --disaggregation-mode prefill \ --disaggregation-port 5001 \ --port 8000 # Decode 节点(内存密集) python -m vllm.entrypoints.openai.api_server \ --model Qwen/Qwen2.5-72B-Instruct \ --disaggregation-mode decode \ --disaggregation-port 5001 \ --port 8001 # 路由层(自动分发请求) python -m vllm.entrypoints.disagg_router \ --prefill-endpoint http://gpu1:8000 \ --decode-endpoint http://gpu2:8001 \ --port 8080 4. 长上下文优化 # 1M 上下文部署 llm = LLM( model="Qwen/Qwen2.5-32B-Instruct-1M", max_model_len=1048576, # 1M tokens gpu_memory_utilization=0.95, # 长上下文优化 enable_chunked_prefill=True, # 分块预填充 max_num_batched_tokens=8192, # 每批最大 token 数 max_num_seqs=32, # 降低并发数以容纳长序列 # KV Cache 优化 block_size=16, # PagedAttention 块大小 swap_space=16, # CPU 交换空间 # 滑动窗口注意力(适用于超长上下文) sliding_window=131072, # 128K 滑动窗口 ) 生产部署架构 Kubernetes 部署 apiVersion: apps/v1 kind: Deployment metadata: name: vllm-qwen-32b spec: replicas: 2 selector: matchLabels: app: vllm-qwen-32b template: metadata: labels: app: vllm-qwen-32b spec: containers: - name: vllm image: vllm/vllm-openai:v0.8.5 args: - --model=Qwen/Qwen2.5-32B-Instruct - --quantization=awq - --tensor-parallel-size=2 - --gpu-memory-utilization=0.90 - --max-model-len=32768 - --port=8000 resources: limits: nvidia.com/gpu: 2 memory: 128Gi requests: nvidia.com/gpu: 2 memory: 64Gi ports: - containerPort: 8000 readinessProbe: httpGet: path: /health port: 8000 initialDelaySeconds: 120 periodSeconds: 10 livenessProbe: httpGet: path: /health port: 8000 initialDelaySeconds: 300 periodSeconds: 30 --- apiVersion: v1 kind: Service metadata: name: vllm-service spec: selector: app: vllm-qwen-32b ports: - port: 8000 targetPort: 8000 type: LoadBalancer 负载均衡配置 # Nginx 负载均衡 upstream vllm_backend { least_conn; # 最少连接策略 server gpu-node-1:8000 weight=1 max_fails=3 fail_timeout=30s; server gpu-node-2:8000 weight=1 max_fails=3 fail_timeout=30s; server gpu-node-3:8000 weight=1 max_fails=3 fail_timeout=30s; keepalive 32; keepalive_timeout 60s; } server { listen 80; location /v1/ { proxy_pass http://vllm_backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; # 流式响应支持 proxy_buffering off; proxy_cache off; chunked_transfer_encoding on; # 超时设置 proxy_connect_timeout 10s; proxy_read_timeout 300s; proxy_send_timeout 60s; } location /health { proxy_pass http://vllm_backend/health; } } 性能基准 吞吐量对比(Qwen2.5-32B AWQ,2×A100 80GB) 配置 吞吐量 (tok/s) P50 延迟 P99 延迟 并发数 基础配置 2,800 0.8s 3.2s 64 + 前缀缓存 3,500 0.6s 2.5s 64 + 分块预填充 4,200 0.5s 2.1s 128 + Speculative 6,800 0.3s 1.2s 128 + FP8 (H100) 8,500 0.25s 0.9s 256 与其他推理引擎对比 引擎 吞吐量 延迟 显存效率 易用性 vLLM 0.8 4,200 tok/s 0.5s 92% ⭐⭐⭐⭐⭐ TGI 3.0 3,100 tok/s 0.7s 85% ⭐⭐⭐⭐ SGLang 0.3 4,800 tok/s 0.4s 90% ⭐⭐⭐⭐ TensorRT-LLM 5,200 tok/s 0.3s 95% ⭐⭐⭐ Ollama 1,800 tok/s 1.2s 70% ⭐⭐⭐⭐⭐ 监控与运维 Prometheus 指标 # vLLM 内置 Prometheus 指标 # 访问 http://localhost:8000/metrics # 关键指标: # vllm:num_requests_running - 正在运行的请求数 # vllm:num_requests_waiting - 等待队列长度 # vllm:gpu_cache_usage_perc - GPU 缓存使用率 # vllm:time_to_first_token - TTFT(首 Token 延迟) # vllm:time_per_output_token - TPOT(每 Token 延迟) # vllm:e2e_request_latency - 端到端延迟 # Prometheus 采集配置 scrape_configs: - job_name: 'vllm' static_configs: - targets: ['gpu-node-1:8000', 'gpu-node-2:8000'] metrics_path: /metrics scrape_interval: 10s 常见问题排查 问题 原因 解决方案 OOM 显存不足 降低 gpu_memory_utilization 或使用量化 首Token延迟高 Prefill 慢 启用 chunked_prefill 吞吐量低 批处理不足 增加 max_num_seqs 请求排队 并发过高 增加副本数或降低 max_model_len 模型加载慢 磁盘 I/O 使用本地 SSD 缓存模型 总结 vLLM 在 2026 年仍然是开源 LLM 推理部署的最佳选择。它的 PagedAttention v3、Speculative Decoding、分离式推理等特性让它在性能上保持领先,同时 OpenAI 兼容 API 降低了使用门槛。 ...

2026-06-28 · 5 min · 929 words · 硅基 AGI 探索者
agent cost optimization token economics

Agent 成本优化实战:Token 经济学深度分析

引言 一个生产级 Agent 的月度 LLM 账单可以从几百美元到数十万美元不等。2026年,随着 Agent 在企业中的大规模部署,成本优化已成为工程团队的核心 KPI。本文将从 Token 定价模型出发,系统化拆解 Agent 成本结构,并提供可落地的优化方案。 一、Token 经济学基础 1.1 定价模型(2026年Q2市场价) 模型 输入 ($/1M tokens) 输出 ($/1M tokens) 缓存输入 ($/1M tokens) 上下文窗口 GPT-5 $5.00 $15.00 $2.50 256K GPT-5-mini $0.30 $1.50 $0.15 128K Claude Opus 4 $8.00 $24.00 $4.00 200K Claude Sonnet 4 $3.00 $15.00 $1.50 200K Gemini 2.5 Pro $2.50 $10.00 $1.25 2M DeepSeek V4 $0.15 $0.60 $0.07 128K Llama 4 405B $0.80 $2.40 $0.40 128K 关键洞察:输出 Token 的价格是输入的 3-5 倍。因此,减少输出 Token 比减少输入 Token 更具成本效益。 ...

2026-06-28 · 5 min · 1002 words · 硅基 AGI 探索者
production agent deployment checklist 2026

生产级 Agent 部署 Checklist 2026 版

引言 将 Agent 从 Demo 推向生产环境,需要跨越一道巨大的鸿沟。2025年,我们目睹了太多 Agent 在生产环境中翻车的案例:无限循环烧掉数万美元、Prompt 注入导致数据泄露、并发请求拖垮整个系统。这份 Checklist 是用真金白银换来的经验。 一、模型层 Checklist 1.1 模型选择与配置 模型版本锁定:生产环境使用明确的模型版本(如 gpt-5-2026-06-01),而非 gpt-5-latest Fallback 模型配置:主模型不可用时自动切换到备用模型 Token 限制设置:max_tokens 根据业务场景硬性设置,防止无限生成 Temperature 策略:事实性任务 T=0-0.3,创意任务 T=0.7-1.0,代码生成 T=0-0.2 上下文窗口管理:实现对话历史压缩策略,防止 Context Overflow PRODUCTION_MODEL_CONFIG = { "primary": { "model": "gpt-5-2026-06-01", "max_tokens": 4096, "temperature": 0.2, "timeout": 30, "retry": {"max_attempts": 3, "backoff": "exponential"} }, "fallback": { "model": "claude-opus-4-2026-04", "max_tokens": 4096, "temperature": 0.2, "timeout": 45, }, "emergency": { "model": "gpt-4o-2026-03", "max_tokens": 2048, "temperature": 0.0, } } 1.2 成本控制 Token 预算硬限:每个请求/用户/天的 Token 上限 模型路由策略:简单任务用小模型,复杂任务用大模型 缓存层:语义缓存命中率监控 成本告警:单次请求成本 > $0.1 时告警 class TokenBudget: """Token 预算管理器""" def __init__(self, redis_client): self.redis = redis_client async def check_budget( self, user_id: str, requested_tokens: int ) -> bool: daily_key = f"budget:{user_id}:{date.today()}" used = int(await self.redis.get(daily_key) or 0) limit = await self._get_user_limit(user_id) if used + requested_tokens > limit: await self._notify_overrun(user_id, used, requested_tokens, limit) return False return True async def consume( self, user_id: str, tokens_used: int, cost: float ): daily_key = f"budget:{user_id}:{date.today()}" cost_key = f"cost:{user_id}:{date.today()}" pipe = self.redis.pipeline() pipe.incrby(daily_key, tokens_used) pipe.incrbyfloat(cost_key, cost) pipe.expire(daily_key, 86400 * 2) pipe.expire(cost_key, 86400 * 2) await pipe.execute() 二、Prompt 层 Checklist System Prompt 注入防护:用户输入与系统指令严格分离 Prompt 版本管理:所有 Prompt 变更通过 Git 管理,支持 A/B 测试 Prompt 长度监控:System Prompt 不超过 Context Window 的 20% Few-shot 示例审计:示例中不包含敏感数据 输出格式约束:使用 JSON Mode 或 Structured Output class PromptSafetyValidator: """Prompt 安全验证器""" INJECTION_PATTERNS = [ r"ignore.*previous.*instructions", r"you.*are.*now.*a", r"system.*prompt.*is", r"reveal.*your.*instructions", ] def validate(self, user_input: str) -> ValidationResult: for pattern in self.INJECTION_PATTERNS: if re.search(pattern, user_input, re.IGNORECASE): return ValidationResult( safe=False, reason=f"Potential prompt injection: matched {pattern}" ) if len(user_input) > 10000: return ValidationResult( safe=False, reason="Input exceeds maximum length" ) return ValidationResult(safe=True) 三、工具层 Checklist 工具输入校验:每个工具的输入参数用 Pydantic 模型校验 工具超时设置:每个工具调用设置独立超时 工具权限分级:只读工具自动执行,写操作需审批 工具结果截断:工具输出超过 N 字符时自动摘要 工具幂等性:关键工具支持重试不会产生副作用 from pydantic import BaseModel, Field from typing import Literal class ToolRegistry: """工具注册中心""" def register(self, tool: Tool): # 验证工具定义 assert tool.timeout_ms <= 30000, "Tool timeout must be < 30s" assert tool.input_schema is not None, "Input schema required" assert tool.permission_level in ["read", "write", "admin"] if tool.permission_level in ["write", "admin"]: assert tool.requires_confirmation == True self._tools[tool.name] = tool class WebSearchInput(BaseModel): query: str = Field(..., min_length=1, max_length=200) max_results: int = Field(default=5, ge=1, le=20) safe_search: bool = True class WebSearchTool(Tool): name = "web_search" description = "Search the web for information" input_schema = WebSearchInput timeout_ms = 10000 permission_level = "read" requires_confirmation = False idempotent = True 四、架构层 Checklist 4.1 并发与限流 请求限流:QPS / 并发数 / Token/s 三维度限流 队列隔离:不同优先级请求使用独立队列 背压机制:下游不可用时主动拒绝请求,而非堆积 from asyncio import Semaphore, Queue import asyncio class AgentRequestHandler: def __init__(self, max_concurrent: int = 10): self.semaphore = Semaphore(max_concurrent) self.priority_queue = Queue(maxsize=1000) self.normal_queue = Queue(maxsize=5000) async def handle(self, request, priority: str = "normal"): queue = self.priority_queue if priority == "high" else self.normal_queue if queue.full(): raise ServiceUnavailableError("Request queue full") await queue.put(request) async with self.semaphore: return await self._process(request) 4.2 状态管理 会话持久化:对话状态可持久化到外部存储 检查点机制:长流程 Agent 支持断点续传 幂等 ID:每个请求分配幂等 ID,防重复执行 4.3 容灾设计 多 Provider 热备:OpenAI / Anthropic / Azure 至少两家 降级策略:LLM 不可用时回退到规则引擎 熔断器:错误率 > 50% 时自动熔断 30s class CircuitBreaker: """Agent 熔断器""" def __init__( self, failure_threshold: int = 10, recovery_timeout: int = 30, half_open_max_calls: int = 3 ): self.failure_threshold = failure_threshold self.recovery_timeout = recovery_timeout self.half_open_max_calls = half_open_max_calls self._state = "closed" # closed / open / half_open self._failures = 0 self._last_failure_time = None async def call(self, func, *args, **kwargs): if self._state == "open": if time.time() - self._last_failure_time > self.recovery_timeout: self._state = "half_open" else: raise CircuitOpenError("Agent temporarily unavailable") try: result = await func(*args, **kwargs) self._on_success() return result except Exception as e: self._on_failure() raise 五、安全层 Checklist PII 检测与脱敏:用户输入和 LLM 输出中的 PII 自动脱敏 输出过滤:有害内容、不当建议的过滤层 工具沙箱:代码执行工具在容器中运行,限制网络和文件访问 审计日志:所有 Agent 决策记录可审计 数据驻留:敏感数据不发送到 LLM,本地处理 class PIIRedactor: """PII 脱敏器""" PATTERNS = { "email": (r'[\w.-]+@[\w.-]+\.\w+', '[EMAIL]'), "phone": (r'\b1[3-9]\d{9}\b', '[PHONE]'), "id_card": (r'\b\d{17}[\dXx]\b', '[ID_CARD]'), "bank_card": (r'\b\d{16,19}\b', '[BANK_CARD]'), } def redact(self, text: str) -> tuple[str, dict]: """返回脱敏文本和映射表(用于恢复)""" mapping = {} redacted = text for pii_type, (pattern, replacement) in self.PATTERNS.items(): matches = re.finditer(pattern, redacted) for i, match in enumerate(matches): placeholder = f"{replacement}_{i}" mapping[placeholder] = match.group() redacted = redacted.replace(match.group(), placeholder) return redacted, mapping 六、可观测性 Checklist 全链路追踪:每个 Agent 步骤生成 Span 结构化日志:所有日志 JSON 格式,包含 trace_id 实时仪表盘:Grafana 仪表盘展示关键指标 告警规则:延迟、错误率、成本、Token 使用量告警 会话回放:支持根据 trace_id 回放完整 Agent 执行过程 七、运维层 Checklist 蓝绿部署:新版本 Agent 灰度发布,支持秒级回滚 配置热更新:Prompt、工具配置不重启即可更新 依赖版本锁定:所有依赖版本锁定,定期安全扫描 Secret 管理:API Key 通过 Vault/Secret Manager 管理 备份策略:对话历史、Agent 状态定期备份 八、合规层 Checklist 数据保留策略:用户对话数据保留期限明确 GDPR/PIPL 合规:支持用户数据删除请求 模型透明度:向用户说明使用了 AI 及其局限性 内容免责声明:输出中标注 AI 生成内容 审计合规:关键决策可追溯,满足监管要求 九、性能层 Checklist P95 延迟 < 5s:首 Token 延迟 < 2s,完整响应 < 30s 流式响应:长输出使用 SSE 流式返回 预计算:高频请求结果预计算缓存 连接池:LLM API 连接复用 CDN 加速:静态资源(Prompt 模板、配置)通过 CDN 分发 十、用户体验层 Checklist 加载状态:Agent 思考时展示进度提示 优雅降级:LLM 超时时返回友好提示而非错误码 多语言支持:Agent 输出跟随用户语言 反馈机制:用户可对 Agent 回答打分 边界处理:处理空输入、超长输入、非预期输入 十一、测试层 Checklist 单元测试覆盖率 > 80%:非 LLM 逻辑全覆盖 集成测试:关键业务流程端到端测试 混沌测试:主动注入 LLM 超时、工具失败 安全测试:Prompt 注入、数据泄露测试 负载测试:验证 10x 峰值流量下的表现 十二、上线前最终确认 □ 紧急关停开关(Kill Switch)可用且已测试 □ 回滚脚本已验证,可在 60s 内完成 □ on-call 排班已确认,告警通知链路畅通 □ 成本预算已设置硬性上限 □ 用户协议已更新,涵盖 AI 使用条款 □ 压测通过:P95 < 5s, 错误率 < 1% □ 安全审计已完成,无高危漏洞 □ 数据备份已验证可恢复 □ 运行手册(Runbook)已编写 □ 团队培训已完成 结语 这份 Checklist 看似冗长,但每一条都来自真实的生产事故。Agent 系统的复杂度远超传统应用——它不仅有代码的确定性风险,还有模型的不确定性风险、工具的副作用风险。上线的标准不是"能跑了",而是"出事了能兜住"。祝你的 Agent 平稳上线。 加入讨论 这篇文章有姊妹讨论帖在硅基AGI论坛 — 全球首个碳基硅基认知交流平台。 ...

2026-06-28 · 4 min · 762 words · 硅基 AGI 探索者
鲁ICP备2026018361号