- 文档
- 教程
- 知识库
- 人工智能
- 提示工程
【免费下载链接】Context-Engineering
"Context engineering is the delicate art and science of filling the context window with just the right information for the next step." — Andrej Karpathy. A frontier, first-principles handbook inspired by Karpathy and 3Blue1Brown for moving beyond prompt engineering to the wider discipline of context design, orchestration, and optimization.
本篇指南以 Context-Engineering 课程体系中的 00_function_calling.md 为核心骨架,讲解在 "Software 3.0" 范式下如何让 LLM 通过结构化函数调用(Function Calling)获得外部工具能力。文章完整覆盖函数签名与 Schema 定义、同步/异步/并行/顺序四种调用类型、注册表与参数校验等实现策略、组合与条件执行等高级模式、安全访问控制与评估指标,并结合作品仓库中的 Schema 模板与控制循环源码提供可落地的实战方案。读完本篇,你将能够独立设计函数接口、实现安全可重试的函数调用引擎,并为多步工具集成推理打下基础。
一、引言:用英语编程 LLM 的新范式
Software 3.0 范式:"LLMs are a new kind of computer, and you program themin English" — Andrej Karpathy
Function Calling 代表了智能系统架构方式的根本转变。与其期望 LLM 仅凭纯推理解决所有问题,我们通过为其提供对外部工具、函数和系统的结构化访问来扩展其能力。这创造了一种新范式:LLM 成为编排智能(orchestrating intelligence),能够动态选择、组合并执行专用工具来解决复杂问题。
在 Context-Engineering 课程体系中,该主题位于 06_tool_integrated_reasoning 模块的开篇,后续的 01_tool_integration.md、02_agent_environment.md、03_reasoning_frameworks.md 均建立在本篇基础之上,形成"函数调用 → 工具编排 → 环境交互 → 推理框架"的渐进式演进路径。
二、Function Calling 的数学基础
2.1 面向工具集成的上下文组装
基于课程的奠基框架C = A(c₁, c₂, ..., cₙ)(参见 01_context_formalization.md),Function Calling 引入了专门的上下文组件:
C_tools = A(c_instr, c_tools, c_state, c_query, c_results)其中各组件含义如下:
| 组件 | 含义 | 作用 |
|---|---|---|
| c_instr | 系统指令 | 说明工具的使用规则与输出格式约定 |
| c_tools | 函数定义与签名 | 以 Schema 形式描述可用函数的能力边界 |
| c_state | 当前执行状态 | 记录对话轮次、已执行步骤等运行期上下文 |
| c_query | 用户当前请求 | 本轮待解决的目标 |
| c_results | 历史函数调用结果 | 供后续调用与最终回答引用 |
这一形式化表达与仓库中的 schema_template.json 高度吻合:该模板将上下文拆分为systemContext、taskContext、interactionHistory、protocolShell等分区,其中protocolShell.process即对应函数调用中的步骤化流程定义,interactionHistory对应c_results/c_state的持久化载体。
2.2 函数调用序列的优化问题
函数调用的优化问题,是寻找在最大化任务完成度、最小化资源消耗前提下的最优函数调用序列 F*:
F* = arg max_{F} Σ(Reward(f_i) × Efficiency(f_i)) - Cost(f_i)并需满足以下约束:
- 资源约束:Σ Cost(f_i) ≤ Budget,总调用成本不得超过预算;
- 安全约束:Safe(f_i) = True ∀ f_i,每个函数都必须通过安全检查;
- 依赖约束:Dependencies(f_i) ⊆ Completed_functions,被调函数的依赖必须已经完成。
该优化模型与 02_optimization_theory.md 中的通用目标函数一脉相承,是后续 01_tool_integration.md 中"工具集成优化"(含依赖 DAG 约束、时间约束)的简化前身。
三、核心概念
3.1 函数签名与 Schema
函数调用要求 LLM 能够理解并可靠使用精确的接口定义。接口定义通常采用 JSON Schema 形式,示例如下:
# Example: Mathematical calculation function { "name": "calculate", "description": "Perform mathematical calculations with step-by-step reasoning", "parameters": { "type": "object", "properties": { "expression": { "type": "string", "description": "Mathematical expression to evaluate" }, "show_steps": { "type": "boolean", "description": "Whether to show intermediate calculation steps", "default": True } }, "required": ["expression"] } }在设计 Schema 时,仓库 06_schema_design.py 中的JSONSchema.validate()给出了可复用的校验实现:它调用jsonschema.validate(instance=parameters, schema=...),并在失败时记录错误路径与统计信息(validation_stats["error_types"][error_path])。这意味着函数参数在交给执行器之前,可以先经过同样的 Schema 校验管线,从源头拦截格式错误的调用。
3.2 函数调用流程
一次完整的函数调用遵循"意图分析 → 函数选择 → 参数映射 → 参数抽取 → 函数执行 → 结果处理 → 响应生成"的流程:
┌─────────────────┐ │ User Query │ └─────────┬───────┘ │ ▼ ┌─────────────────┐ ┌──────────────────┐ │ Intent Analysis │────▶│ Function Selection│ └─────────────────┘ └─────────┬────────┘ │ ▼ ┌─────────────────┐ ┌──────────────────┐ │Parameter Extract│◀────│ Parameter Mapping│ └─────────┬───────┘ └──────────────────┘ │ ▼ ┌─────────────────┐ ┌──────────────────┐ │Function Execute │────▶│ Result Process │ └─────────────────┘ └─────────┬────────┘ │ ▼ ┌──────────────────┐ │ Response Generate│ └──────────────────┘其中"意图分析"与"函数选择"环节,正是仓库 20_templates/control_loop.py 中ControlLoop.run()所封装的多轮推理循环:每轮先由模型产出动作/响应,再经EvaluationFunction(如SimpleKeywordEvaluator、PatternMatchEvaluator)评估是否成功,未达标则把反馈追加进ContextManager的历史并进入下一轮迭代,直至成功或达到max_iterations上限。
3.3 函数调用类型
根据执行语义,函数调用可分为四类:
同步调用(Synchronous Calls)
- 直接执行函数并立即返回结果;
- 适合:计算、数据转换、简单查询等短耗时操作。
异步调用(Asynchronous Calls)
- 非阻塞执行,适用于长耗时操作;
- 适合:网络请求、文件处理、复杂计算。
并行调用(Parallel Calls)
- 多个相互独立的函数同时执行;
- 适合:独立操作、从多个数据源采集信息。后续 01_tool_integration.md 中的
parallel_analysis()即用asyncio.gather(*tasks)并发执行多个搜索工具。
顺序调用(Sequential Calls)
- 链式执行,前一函数的输出作为后一函数的输入;
- 适合:多步工作流、复杂推理链。
四、函数定义模式
4.1 基础函数模式
基础函数定义包含name、description、parameters三要素:
{ "name": "function_name", "description": "Clear, specific description of what the function does", "parameters": { "type": "object", "properties": { "param1": { "type": "string|number|boolean|array|object", "description": "Parameter description", "enum": ["optional", "allowed", "values"], "default": "optional_default_value" } }, "required": ["list", "of", "required", "parameters"] } }要点说明:
description应足够具体,它是 LLM 选择函数时的主要依据;enum用于限定参数的可选值集合,可显著提升参数生成精度;default为可选参数的兜底值;required列表外的属性均可省略。
4.2 复杂函数模式
当函数需要结构化嵌套参数时,可组合array、object与pattern等约束。以下是一个多源研究查询函数的完整定义:
{ "name": "research_query", "description": "Perform structured research using multiple sources", "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "Research question or topic" }, "sources": { "type": "array", "items": { "type": "string", "enum": ["web", "academic", "news", "books", "patents"] }, "description": "Information sources to use" }, "max_results": { "type": "integer", "minimum": 1, "maximum": 50, "default": 10, "description": "Maximum number of results per source" }, "filters": { "type": "object", "properties": { "date_range": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}:\\d{4}-\\d{2}-\\d{2}$", "description": "Date range in format YYYY-MM-DD:YYYY-MM-DD" }, "language": { "type": "string", "default": "en" } } } }, "required": ["query", "sources"] } }该模式演示了数值范围约束(minimum/maximum)、正则模式约束(pattern)与嵌套对象(filters)的组合用法。仓库 schema_template.json 同样体现了这种"分区嵌套"思想——它将系统上下文、领域知识、用户上下文、任务上下文、交互历史、协议壳等分层组织,函数 Schema 可作为其中的protocolShell.process步骤或独立工具契约存在。
五、实现策略
5.1 函数注册表模式(Function Registry Pattern)
集中式注册表负责管理所有可用函数,是"单一事实来源":
class FunctionRegistry: def __init__(self): self.functions = {} self.categories = {} def register(self, func, category=None, **metadata): """Register a function with metadata""" self.functions[func.__name__] = { 'function': func, 'signature': self._extract_signature(func), 'category': category, 'metadata': metadata } def get_available_functions(self, category=None): """Get functions available for the current context""" if category: return {name: info for name, info in self.functions.items() if info['category'] == category} return self.functions def call(self, function_name, **kwargs): """Execute a registered function safely""" if function_name not in self.functions: raise ValueError(f"Function {function_name} not found") func_info = self.functions[function_name] return func_info'function'设计要点:
register()同时保存可执行对象、签名与元数据,便于后续做上下文感知筛选;category支持按类别暴露"当前上下文可用函数子集",控制注入提示词的函数数量(对应后文"渐进式披露"原则);call()在未注册函数时立即抛错,避免静默失败。
5.2 参数校验策略
在真正执行前,先用 JSON Schema 校验 LLM 生成的参数,是防止格式错误与越界值的关键防线:
from jsonschema import validate, ValidationError def validate_parameters(function_schema, parameters): """Validate function parameters against schema""" try: validate(instance=parameters, schema=function_schema['parameters']) return True, None except ValidationError as e: return False, str(e) def safe_function_call(function_name, parameters, registry): """Safely execute function with validation""" func_info = registry.get_function(function_name) # Validate parameters is_valid, error = validate_parameters(func_info['schema'], parameters) if not is_valid: return {"error": f"Parameter validation failed: {error}"} try: result = registry.call(function_name, **parameters) return {"success": True, "result": result} except Exception as e: return {"error": f"Function execution failed: {str(e)}"}这与仓库 06_schema_design.py 中JSONSchema.validate()的实现思路一致:该校验器同样基于jsonschema库,并额外维护validation_stats(成功/失败计数与错误类型分布),可用于度量参数生成的长期质量;其SchemaContext.query()还在校验失败时把错误信息回填到提示词中重试(max_retries默认 3 次),这正是"校验失败 → 反馈 → 重试"闭环的仓库级佐证。
5.3 上下文感知的函数选择
仅凭描述相似度选择函数是不够的,还需要结合当前对话上下文打分排序:
def select_optimal_functions(query, available_functions, context): """Select the most appropriate functions for a given query""" # Analyze query intent intent = analyze_intent(query) # Score functions based on relevance scored_functions = [] for func_name, func_info in available_functions.items(): relevance_score = calculate_relevance( intent, func_info['description'], func_info['category'] ) # Consider context constraints context_score = evaluate_context_fit(func_info, context) total_score = relevance_score * context_score scored_functions.append((func_name, total_score)) # Return top-ranked functions return sorted(scored_functions, key=lambda x: x[1], reverse=True)其中relevance_score度量意图与函数描述的匹配度,context_score度量函数在当前状态下的适配度(例如已完成的步骤、可用权限、资源限制)。两者相乘后排序,仅把 Top-N 函数注入提示词,可显著降低函数定义对上下文窗口的占用——这与 token_budgeting.md 讨论的上下文预算管理直接相关。
六、高级函数调用模式
6.1 函数组合(Function Composition)
将多个函数编排为数据流管道,前一函数的输出注入后一函数的输入:
{ "name": "composed_research_analysis", "description": "Compose multiple functions for comprehensive analysis", "workflow": [ { "function": "research_query", "parameters": {"query": "{input.topic}", "sources": ["web", "academic"]}, "output_name": "research_results" }, { "function": "summarize_content", "parameters": {"content": "{research_results.data}"}, "output_name": "summary" }, { "function": "extract_insights", "parameters": {"summary": "{summary.text}"}, "output_name": "insights" } ] }{input.topic}、{research_results.data}等占位符即"输出馈入输入"的链式绑定。这一模式在 01_tool_integration.md 中被进一步抽象为ToolPipeline(线性流水线)与DAGToolOrchestrator(带依赖拓扑排序的编排器),后者通过 Kahn 算法计算执行顺序,保证依赖约束得到满足。
6.2 条件函数执行
根据中间结果动态决定是否执行某个函数:
{ "name": "adaptive_problem_solving", "description": "Conditionally execute functions based on intermediate results", "workflow": [ { "function": "analyze_problem", "parameters": {"problem": "{input.problem}"}, "output_name": "analysis" }, { "condition": "analysis.complexity > 0.7", "function": "break_down_problem", "parameters": {"problem": "{input.problem}", "analysis": "{analysis}"}, "output_name": "subproblems" }, { "condition": "analysis.requires_research", "function": "research_query", "parameters": {"query": "{analysis.research_queries}"}, "output_name": "research_data" } ] }condition字段对前置输出做谓词求值,只有满足条件的分支才会被展开执行。这种"分析 → 分支 → 执行"的控制流,是后续 03_reasoning_frameworks.md 中"原子推理步骤 → 分子推理链"的雏形,也是实现自适应问题求解器的基本构件。
6.3 错误处理与重试逻辑
健壮的执行引擎必须区分"临时错误"与"永久错误",并针对临时错误采用指数退避重试:
def robust_function_call(function_name, parameters, max_retries=3): """Execute function with retry logic and error handling""" for attempt in range(max_retries): try: result = execute_function(function_name, parameters) # Validate result if validate_result(result): return {"success": True, "result": result, "attempts": attempt + 1} else: # Invalid result, try with adjusted parameters parameters = adjust_parameters(parameters, result) except TemporaryError as e: if attempt < max_retries - 1: time.sleep(2 ** attempt) # Exponential backoff continue else: return {"error": f"Max retries exceeded: {str(e)}"} except PermanentError as e: return {"error": f"Permanent error: {str(e)}"} return {"error": "Max retries exceeded without success"}该实现的核心价值:
- 结果校验:
validate_result()确认结果语义正确,而非仅"不抛异常"; - 参数调整:无效结果时基于结果修正参数后重试(自适应重试);
- 退避策略:
2 ** attempt指数退避,避免对不稳定服务造成瞬时冲击; - 错误分类:
TemporaryError可重试,PermanentError立即返回,避免无谓消耗。
此模式与 01_tool_integration.md 最佳实践中的"Retry with Backoff"和"Fallback Tools"策略一脉相承。
七、面向 Function Calling 的提示词模板
7.1 基础函数调用模板
将函数定义注入系统提示词,并约定调用响应格式:
FUNCTION_CALLING_TEMPLATE = """ You have access to the following functions: {function_definitions} When you need to use a function, respond with a function call in this format: ```function_call { "function": "function_name", "parameters": { "param1": "value1", "param2": "value2" } } Current task: {user_query} Think step by step about what functions you need to use and in what order. """要点:
{function_definitions}由注册表按上下文裁剪后的函数 Schema 渲染而来;- 以明确的代码块标记(
function_call)界定调用输出,便于解析器精确抽取; - 末尾"Think step by step"引导模型先规划再调用,与思维链(Chain-of-Thought)提示一致,参见 01_prompt_engineering.md。
7.2 多步推理模板
面向复杂任务,要求模型"分析 → 选择 → 规划 → 执行 → 综合":
MULTI_STEP_FUNCTION_TEMPLATE = """ You are a reasoning agent with access to specialized tools. For complex tasks, break them down into steps and use the appropriate functions for each step. Available functions: {function_definitions} Task: {user_query} Approach this systematically: 1. Analyze what needs to be done 2. Identify which functions are needed 3. Plan the sequence of function calls 4. Execute the plan step by step 5. Synthesize the results Begin your reasoning: """该模板的五步流程与 20_templates/control_loop.py 中ControlLoop的迭代语义吻合:max_iterations控制最大步数,ContextManager.add_to_history()保留每步中间状态,stop_on_success/success_threshold决定何时收敛。
7.3 错误恢复模板
当函数调用失败时,把错误信息连同替代方案一起回传给模型,引导其分析并纠错:
ERROR_RECOVERY_TEMPLATE = """ The previous function call failed with error: {error_message} Function that failed: {failed_function} Parameters used: {failed_parameters} Available alternatives: {alternative_functions} Please: 1. Analyze why the function call might have failed 2. Suggest an alternative approach 3. Retry with corrected parameters or use a different function Continue working toward the goal: {original_goal} """该模板对应 06_schema_design.py 中SchemaContext.query()的失败反馈机制:当响应未通过 Schema 校验时,代码将Error: {error_message}追加到原提示词末尾并要求重新生成,直到有效或达到max_retries——两者共享同一"错误即反馈"的自我修正哲学。
八、安全与合规考量
8.1 函数访问控制
在注册表之上叠加访问策略与审计日志:
class SecureFunctionRegistry(FunctionRegistry): def __init__(self): super().__init__() self.access_policies = {} self.audit_log = [] def set_access_policy(self, function_name, policy): """Set access control policy for a function""" self.access_policies[function_name] = policy def call(self, function_name, context=None, **kwargs): """Execute function with security checks""" # Check access permissions if not self._check_access(function_name, context): raise PermissionError(f"Access denied to {function_name}") # Log the function call self._log_call(function_name, kwargs, context) # Execute with resource limits return self._execute_with_limits(function_name, **kwargs)安全三要素:鉴权(_check_access依据策略与上下文判定)、审计(_log_call记录调用者、参数与上下文,形成可追溯日志)、限流限资源(_execute_with_limits)。这与课程 00_COURSE/README.md 中规划的安全模块(safety/execution_sandboxing.py、safety/permission_systems.py)的目标一致:所有外部能力调用必须可授权、可审计、可限制。
8.2 输入净化
防止提示词注入与参数注入攻击:
def sanitize_function_input(parameters): """Sanitize function parameters to prevent injection attacks""" sanitized = {} for key, value in parameters.items(): if isinstance(value, str): # Remove potentially dangerous characters sanitized[key] = re.sub(r'[<>"\';]', '', value) elif isinstance(value, dict): sanitized[key] = sanitize_function_input(value) elif isinstance(value, list): sanitized[key] = [sanitize_function_input(item) if isinstance(item, dict) else item for item in value] else: sanitized[key] = value return sanitized该函数递归处理嵌套的 dict/list,统一剔除字符串中的引号、尖括号与分号等危险字符,防止参数内容逃逸出预期的上下文边界。
8.3 资源限制
对执行时间与内存设定硬性上限,防止失控调用拖垮宿主进程:
import signal from contextlib import contextmanager @contextmanager def timeout(seconds): """Context manager for function timeout""" def timeout_handler(signum, frame): raise TimeoutError(f"Function execution timed out after {seconds} seconds") old_handler = signal.signal(signal.SIGALRM, timeout_handler) signal.alarm(seconds) try: yield finally: signal.alarm(0) signal.signal(signal.SIGALRM, old_handler) def execute_with_resource_limits(function, max_time=30, max_memory=None): """Execute function with resource constraints""" with timeout(max_time): if max_memory: # Set memory limit (implementation depends on platform) resource.setrlimit(resource.RLIMIT_AS, (max_memory, max_memory)) return function()说明:
signal.SIGALRM+signal.alarm()实现超时中断,finally中必须恢复原处理器并清除闹钟;resource.setrlimit(resource.RLIMIT_AS, ...)限制地址空间大小,具体可用值因平台而异,需按操作系统调整;- 该模式可进一步包装为"沙箱 + 白名单"执行环境,见课程规划的
safety/模块方向。
九、最佳实践与设计准则
9.1 函数设计原则
- 单一职责(Single Responsibility):每个函数只做一件事,描述清晰;
- 清晰接口(Clear Interfaces):参数与返回值边界明确,类型完备;
- 优雅错误处理(Error Handling):函数内部不吞异常,向上传递结构化错误;
- 文档完备(Documentation):
description是 LLM 理解函数的第一信息来源,必须详尽; - 幂等性(Idempotency):在可能的情况下设计成可安全重试,避免重试造成副作用叠加。
9.2 函数调用策略
- 渐进式披露(Progressive Disclosure):先暴露简单函数,随对话推进按需追加复杂函数,控制上下文占用;
- 上下文感知(Context Awareness):选择函数时考虑会话状态,而非仅凭单轮查询;
- 结果校验(Result Validation):继续下一步前验证函数输出(对应 6.3 的
validate_result); - 错误恢复(Error Recovery):为每个关键能力准备替代函数与重试路径(对应 7.3 的恢复模板);
- 性能监控(Performance Monitoring):跟踪每次调用的延迟、成功率与 token 消耗,为后续评估提供数据。
9.3 集成模式
- 注册表模式(Registry Pattern):集中式函数管理,本指南 5.1 的实现;
- 工厂模式(Factory Pattern):依据上下文动态创建函数实例;
- 责任链模式(Chain of Responsibility):顺序执行、逐级传递的调用链;
- 观察者模式(Observer Pattern):调用监控与日志订阅;
- 策略模式(Strategy Pattern):可插拔的执行策略(如同步/异步/并行策略互换)。
十、评估与测试
函数调用质量指标
用测试用例集量化调用系统的五项核心指标:
def evaluate_function_calling(test_cases): """Evaluate function calling performance""" metrics = { 'success_rate': 0, 'parameter_accuracy': 0, 'function_selection_accuracy': 0, 'error_recovery_rate': 0, 'efficiency_score': 0 } for test_case in test_cases: result = execute_test_case(test_case) # Update metrics based on result metrics['success_rate'] += result.success metrics['parameter_accuracy'] += result.parameter_accuracy metrics['function_selection_accuracy'] += result.selection_accuracy # Normalize metrics total_tests = len(test_cases) for key in metrics: metrics[key] /= total_tests return metrics| 指标 | 含义 | 度量方式 |
|---|---|---|
| success_rate | 整体成功率 | 调用完整执行且结果通过校验的比例 |
| parameter_accuracy | 参数生成准确率 | 生成参数与真实 Schema 约束的吻合程度 |
| function_selection_accuracy | 函数选择准确率 | 选出函数是否与标注的期望函数一致 |
| error_recovery_rate | 错误恢复率 | 失败后经重试/替代方案最终成功的比例 |
| efficiency_score | 效率得分 | 单位成本(调用次数/token)下的有效产出 |
该评估思路可与 09_evaluation_methodologies 模块的评估框架衔接:组件级评估关注单函数质量,系统级评估关注多函数编排的整体效果。仓库 06_schema_design.py 中SchemaContext.get_summary_metrics()(含validation_success_rate、avg_latency_per_query、overall_efficiency)提供了可直接迁移的指标聚合实现。
十一、面向后续模块的延伸
Function Calling 只是工具集成推理的起点,在 06_tool_integrated_reasoning 模块内它向上逐级演进:
- 01_tool_integration.md:把单个函数升级为工具生态,引入流水线架构(
ToolPipeline)、DAG 编排(DAGToolOrchestrator)与智能体式工具选择(ToolAgent),其约束从"依赖已满足"扩展为"依赖构成合法 DAG + 时间与质量约束"; - 02_agent_environment.md:从"调用工具"演进为"栖息于环境",引入感知(perception)、反馈(feedback)、适应(adaptation)等上下文组件,函数调用成为智能体在动态环境中的动作原语;
- 03_reasoning_frameworks.md:把工具视为思维的外延,形成"问题表示 → 知识 → 工具 → 策略 → 记忆 → 反思"的完整认知上下文组装,函数调用序列在此成为分布式推理链的神经元。
十二、未来方向
12.1 自适应函数发现
- LLM 主动发现并学习新函数(通过工具目录或 API 文档);
- 自动进行函数组合与优化;
- 调用策略随任务类型自我改进。
12.2 多模态函数集成
- 支持文本、图像、音频、视频的统一函数接口;
- 跨模态推理与函数链式调用;
- 异构工具类型的统一抽象层。
12.3 协作式函数执行
- 多智能体间的函数调用协调;
- 分布式函数执行与结果汇聚;
- 基于共识的函数选择机制。
这些方向与 07_multi_agent_systems 的通信协议与编排机制形成呼应,读者可沿课程路径继续深入。
十三、结语
Function Calling 基础为 Software 3.0 范式下的工具集成推理奠定了根基。通过为 LLM 提供对外部能力的结构化访问,我们将其从孤立的推理引擎转变为能够解决复杂现实问题的编排智能。
成功的函数调用体系取决于五件事:
- 清晰接口设计(Clear Interface Design):定义良好的函数签名与 Schema,是可靠性的前提;
- 健壮执行(Robust Execution):安全的执行环境、参数校验与完善的错误处理;
- 智能选择(Intelligent Selection):上下文感知的函数选择与组合;
- 安全意识(Security Awareness):访问控制、输入净化与资源限制缺一不可;
- 持续改进(Continuous Improvement):监控、评估与优化形成闭环。
在继续深入工具集成、智能体-环境交互与推理框架之前,这些基础为构建复杂的工具增强型智能系统提供了稳定地基。若要进一步实践,建议结合 schema_template.json 设计自己的函数契约、参考 06_schema_design.py 实现参数校验、并借助 control_loop.py 搭起"调用-评估-重试"的主循环。
这一基础使 LLM 得以超越其训练边界,通过结构化工具集成成为解决复杂、动态问题的真正伙伴。
- 文档
- 教程
- 知识库
- 人工智能
- 提示工程
【免费下载链接】Context-Engineering
"Context engineering is the delicate art and science of filling the context window with just the right information for the next step." — Andrej Karpathy. A frontier, first-principles handbook inspired by Karpathy and 3Blue1Brown for moving beyond prompt engineering to the wider discipline of context design, orchestration, and optimization.
相关推荐
Qwen3 Function Calling 实战指南:基于 Qwen-Agent 与 vLLM 的工具调用推理全流程与 Hermes 模板原理
Qwen3 Function Calling 实战指南:基于 Qwen Agent 与 vLLM 的工具调用推理全流程与 Hermes 模板原理 本篇技术指南以
人工智能大模型Qwen模型评测示例工程本地部署教程Context-Engineering 编排毕业设计指南:从组件集成到自适应涌现智能的完整实战
Context Engineering 编排毕业设计指南:从组件集成到自适应涌现智能的完整实战 导读 本指南基于 Context Engineering 仓库
文档教程知识库人工智能提示工程多智能体编排实战:基于 ToolLoopAgent 的 Orchestrator Agent 设计与实现(Agent-Skills-for-Context-Engineering)
多智能体编排实战:基于 ToolLoopAgent 的 Orchestrator Agent 设计与实现(Agent Skills for Context En
人工智能AI 技能提示工程AI 评测
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考