
知识时效性:训练数据截止后无法获取新知识(如GPT-4截止至2023年4月)
数学推理:复杂运算错误率高达37%(GSM8K测试集)
实时交互:无法直接调用外部API/数据库
精确控制:输出格式随机性难以消除(temperature参数敏感)
能力扩展原理:将自然语言指令转换为可执行代码
典型应用场景:
实时天气查询
数据库CRUD操作
数学公式计算
多系统API串联
技术架构:
[用户输入] → [意图识别] → [函数选择] → [参数解析] → [函数执行] → [结果整合]
关键技术点:
意图分类器:BERT微调模型(准确率92%)
参数提取:基于正则表达式与命名实体识别
安全沙箱:Docker容器隔离执行环境
用户输入:"北京明天会下雨吗?"
→ 模型解析生成JSON:
{
"function": "get_weather",
"params": {
"city": "北京",
"date": "2024-06-20"
}
}
→ 调用气象API获取数据
→ 生成自然语言回复:
"北京明日多云转阴,降水概率35%,建议携带雨具"JSON Schema示例:
{
"name": "calculate_loan",
"description": "计算商业贷款还款计划",
"parameters": {
"type": "object",
"properties": {
"principal": {"type": "number", "description": "贷款本金"},
"rate": {"type": "number", "description": "年利率(%)"},
"term": {"type": "integer", "description": "贷款期限(月)"}
},
"required": ["principal", "rate", "term"]
}
}
错误分类处理:
try:
result = function_call.execute()
except APIError as e:
handle_api_error(e)
except TimeoutError:
retry(3)
except ValidationError:
return {"error": "参数校验失败"}
Ollama部署命令:
curl -fsSL https://ollama.com/install.sh | sh ollama run llama2:7b
环境配置:
conda create -n llm python=3.10 pip install openai==1.12.0 tiktoken==0.5.0
API调用示例:
from openai import OpenAI
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
response = client.chat.completions.create(
model="gpt-4-turbo",
messages=[{"role": "user", "content": "解释量子力学测不准原理"}]
)
print(response.choices[0].message.content)状态管理类:
class Conversation:
def __init__(self, max_history=5):
self.history = []
self.max_history = max_history
def add_message(self, role, content):
self.history.append({"role": role, "content": content})
if len(self.history) > self.max_history:
self.history = self.history[-self.max_history:]
def get_messages(self):
return self.history.copy()
# 使用示例
conv = Conversation()
conv.add_message("user", "推荐北京的美食")
conv.add_message("assistant", "推荐尝试烤鸭,全聚德是知名老店")
conv.add_message("user", "人均消费多少?")KV缓存复用:减少重复计算(速度提升40%)
量化部署:FP16→INT8量化(显存占用降低50%)
批处理优化:动态合并请求(吞吐量提升3倍)
输入过滤:正则表达式拦截恶意指令
权限控制:
FUNCTIONS_WHITELIST = {
"user_level_1": ["get_weather", "search_info"],
"user_level_2": ["calculate_finance"]
}审计日志:Elasticsearch存储完整调用记录