理解AI中的LLM、模型与函数:从概念到实战应用(后台ai会员,进行添加数据到mysql)
背景需求以及传统做法分析#
业务场景#
比如后台 ai 对话 ,让 ai 增加一个数据。
假设是商品,把名字详情图片,复制发给他。自动插入一个商品
最好是这样 不带 key,李璐璐
店长
lilu54444
江苏 徐州
20250325 下了订单。
购买豆腐 一盒 3 元
自动帮我创建会员订单。
传统做法#
Python 实现 (使用 pymysql)
import pymysql
import re
from datetime import datetime
def parse_order_text(text):
# 简单解析文本信息
customer_info = {}
order_info = {}
# 解析客户信息
lines = text.strip().split('\n')
if len(lines) >= 3:
customer_info['name'] = lines[0].strip()
customer_info['role'] = lines[1].strip()
customer_info['contact'] = lines[2].strip()
if len(lines) >= 4:
location_match = re.search(r'(.+)\s+(.+)', lines[3].strip())
if location_match:
customer_info['province'] = location_match.group(1)
customer_info['city'] = location_match.group(2)
# 解析订单信息
date_match = re.search(r'(\d{8})\s+下了订单', text)
if date_match:
date_str = date_match.group(1)
order_info['order_date'] = datetime.strptime(date_str, '%Y%m%d').strftime('%Y-%m-%d')
# 解析商品信息
product_match = re.search(r'购买\s+(.+?)\s+(.+?)\s+(\d+)元', text)
if product_match:
order_info['product_name'] = product_match.group(1)
order_info['quantity'] = product_match.group(2)
order_info['price'] = product_match.group(3)
return customer_info, order_info
def insert_order(text):
customer_info, order_info = parse_order_text(text)
# 数据库连接
conn = pymysql.connect(
host='localhost',
user='root',
password='password',
database='shop_db'
)
try:
with conn.cursor() as cursor:
# 1. 检查客户是否存在,不存在则创建
cursor.execute(
"SELECT id FROM customers WHERE contact = %s",
(customer_info.get('contact'),)
)
customer_id = cursor.fetchone()
if not customer_id:
cursor.execute(
"INSERT INTO customers (name, role, contact, province, city) VALUES (%s, %s, %s, %s, %s)",
(
customer_info.get('name', ''),
customer_info.get('role', ''),
customer_info.get('contact', ''),
customer_info.get('province', ''),
customer_info.get('city', '')
)
)
customer_id = cursor.lastrowid
else:
customer_id = customer_id[0]
# 2. 创建订单
cursor.execute(
"INSERT INTO orders (customer_id, order_date, total_amount) VALUES (%s, %s, %s)",
(
customer_id,
order_info.get('order_date', datetime.now().strftime('%Y-%m-%d')),
float(order_info.get('price', 0))
)
)
order_id = cursor.lastrowid
# 3. 添加订单商品
cursor.execute(
"INSERT INTO order_items (order_id, product_name, quantity, price) VALUES (%s, %s, %s, %s)",
(
order_id,
order_info.get('product_name', ''),
order_info.get('quantity', ''),
float(order_info.get('price', 0))
)
)
conn.commit()
return True, f"订单已成功添加,订单ID: {order_id}"
except Exception as e:
conn.rollback()
return False, f"添加订单失败: {str(e)}"
finally:
conn.close()
# 使用示例
order_text = """不带key,李璐璐
店长
lilu518888
江苏 徐州
20250325 下了订单。
购买豆腐 一盒 3元"""
success, message = insert_order(order_text)
print(message)
PHP 实现 (FastAdmin)
<?php
namespace app\admin\controller;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
class OrderAI extends Backend
{
protected $model = null;
public function _initialize()
{
parent::_initialize();
$this->model = model('Order');
}
public function parseAndInsert()
{
if ($this->request->isPost()) {
$text = $this->request->post('order_text');
try {
// 解析文本
$data = $this->parseOrderText($text);
Db::startTrans();
// 检查客户是否存在
$customer = Db::name('customer')->where('contact', $data['customer']['contact'])->find();
if (!$customer) {
// 创建新客户
$customerId = Db::name('customer')->insertGetId([
'name' => $data['customer']['name'],
'role' => $data['customer']['role'],
'contact' => $data['customer']['contact'],
'province' => $data['customer']['province'],
'city' => $data['customer']['city'],
'createtime' => time()
]);
} else {
$customerId = $customer['id'];
}
// 创建订单
$orderId = Db::name('order')->insertGetId([
'customer_id' => $customerId,
'order_date' => strtotime($data['order']['order_date']),
'total_amount' => $data['order']['price'],
'status' => 'pending',
'createtime' => time()
]);
// 添加订单商品
Db::name('order_item')->insert([
'order_id' => $orderId,
'product_name' => $data['order']['product_name'],
'quantity' => $data['order']['quantity'],
'price' => $data['order']['price'],
'createtime' => time()
]);
Db::commit();
$this->success('订单添加成功', null, ['order_id' => $orderId]);
} catch (Exception $e) {
Db::rollback();
$this->error('订单添加失败: ' . $e->getMessage());
}
}
return $this->view->fetch();
}
private function parseOrderText($text)
{
$lines = explode("\n", trim($text));
$result = [
'customer' => [],
'order' => []
];
// 解析客户信息
if (count($lines) >= 3) {
$result['customer']['name'] = trim($lines[0]);
$result['customer']['role'] = trim($lines[1]);
$result['customer']['contact'] = trim($lines[2]);
if (isset($lines[3])) {
$location = explode(' ', trim($lines[3]));
if (count($location) >= 2) {
$result['customer']['province'] = $location[0];
$result['customer']['city'] = $location[1];
}
}
}
// 解析订单日期
preg_match('/(\d{8})\s+下了订单/', $text, $dateMatches);
if (isset($dateMatches[1])) {
$dateStr = $dateMatches[1];
$result['order']['order_date'] = date('Y-m-d', strtotime(
substr($dateStr, 0, 4) . '-' .
substr($dateStr, 4, 2) . '-' .
substr($dateStr, 6, 2)
));
}
// 解析商品信息
preg_match('/购买\s+(.+?)\s+(.+?)\s+(\d+)元/', $text, $productMatches);
if (isset($productMatches[1], $productMatches[2], $productMatches[3])) {
$result['order']['product_name'] = $productMatches[1];
$result['order']['quantity'] = $productMatches[2];
$result['order']['price'] = $productMatches[3];
}
return $result;
}
}
前端表单 (FastAdmin)
<form id="add-form" class="form-horizontal" role="form" data-toggle="validator" method="POST" action="">
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">订单文本:</label>
<div class="col-xs-12 col-sm-8">
<textarea id="c-order_text" class="form-control" name="order_text" rows="10" placeholder="粘贴订单文本信息"></textarea>
</div>
</div>
<div class="form-group layer-footer">
<label class="control-label col-xs-12 col-sm-2"></label>
<div class="col-xs-12 col-sm-8">
<button type="submit" class="btn btn-success btn-embossed">提交</button>
<button type="reset" class="btn btn-default btn-embossed">重置</button>
</div>
</div>
</form>
这两个实现都能解析提供的文本格式,并将客户信息和订单信息插入到数据库中。
但是很明显 这不是我想要的 ai
多方思考,感谢学院君老师#
理解 AI 中的 LLM、模型与函数:从概念到实战应用#
在人工智能快速发展的今天,大型语言模型 (LLM)、AI 模型和函数这些概念经常被提及。本文将深入解析这些概念,并通过一个实际案例展示如何利用 LLM 处理日常业务需求。
一、核心概念解析#
LLM (Large Language Model)#
大型语言模型是一种基于深度学习的 AI 系统,通过大量文本数据训练,能够理解和生成人类语言。
例如:GPT-4、Claude、LLaMA等都是LLM
这些模型通过预训练和微调,能够执行各种语言任务,从简单的文本生成到复杂的推理和理解。
模型#
AI 中的模型是一种数学表示,用于从数据中学习模式并做出预测。模型可以简单如线性回归,也可以复杂如神经网络。
# 简单的机器学习模型示例
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(X_train, y_train)
predictions = model.predict(X_test)
模型是 AI 系统的核心,决定了系统的能力边界和性能表现。
函数#
在 AI 上下文中,函数可以指:
- 数学函数:如激活函数、损失函数
- 编程函数:处理数据或实现算法的代码块
- 函数调用:现代 LLM 中的工具使用能力
# 激活函数示例
def relu(x):
return max(0, x)
# 损失函数示例
def mse_loss(y_true, y_pred):
return ((y_true - y_pred) ** 2).mean()
这三个概念相互关联:LLM 是一种特定类型的模型,其内部使用各种函数来处理数据和优化性能。
二、实战案例:利用 LLM 自动处理订单数据#
业务场景#
假设我们有一个电商平台,客服经常收到类似这样的非结构化订单信息:
不带key,李璐璐
店长
lilu518888
江苏 徐州
20250325 下了订单。
购买豆腐 一盒 3元
传统方法需要人工将这些信息录入系统,既耗时又容易出错。我们可以利用 LLM 来自动化这个过程。
解决方案:使用 LLM 函数调用#
以下是使用 OpenAI 的函数调用功能实现自动订单处理的代码:
import pymysql
import json
import openai
# 配置OpenAI客户端
client = openai.OpenAI(api_key="your_api_key")
# 定义函数架构
functions = [
{
"name": "insert_product",
"description": "将商品信息插入数据库",
"parameters": {
"type": "object",
"properties": {
"customer": {
"type": "object",
"properties": {
"name": {"type": "string", "description": "客户姓名"},
"role": {"type": "string", "description": "客户角色"},
"contact": {"type": "string", "description": "联系方式"},
"province": {"type": "string", "description": "省份"},
"city": {"type": "string", "description": "城市"}
}
},
"order": {
"type": "object",
"properties": {
"date": {"type": "string", "description": "订单日期 YYYYMMDD格式"},
"product_name": {"type": "string", "description": "商品名称"},
"quantity": {"type": "string", "description": "数量描述"},
"price": {"type": "number", "description": "价格(元)"}
}
}
},
"required": ["customer", "order"]
}
}
]
def process_order_with_llm(order_text):
# 调用LLM解析文本
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "你是一个订单处理助手,负责从文本中提取客户和订单信息。"},
{"role": "user", "content": f"从以下文本中提取客户信息和订单信息:\n\n{order_text}"}
],
functions=functions,
function_call={"name": "insert_product"}
)
# 获取函数调用结果
function_call = response.choices[0].message.function_call
if function_call and function_call.name == "insert_product":
try:
# 解析参数
args = json.loads(function_call.arguments)
# 调用数据库插入函数
return insert_to_database(args)
except Exception as e:
return {"success": False, "message": f"解析失败: {str(e)}"}
else:
return {"success": False, "message": "AI无法正确解析订单信息"}
def insert_to_database(data):
# 数据库连接
conn = pymysql.connect(
host='localhost',
user='root',
password='password',
database='shop_db'
)
try:
with conn.cursor() as cursor:
# 1. 检查客户是否存在
cursor.execute(
"SELECT id FROM customers WHERE contact = %s",
(data['customer']['contact'],)
)
customer_id = cursor.fetchone()
if not customer_id:
# 创建新客户
cursor.execute(
"INSERT INTO customers (name, role, contact, province, city) VALUES (%s, %s, %s, %s, %s)",
(
data['customer']['name'],
data['customer']['role'],
data['customer']['contact'],
data['customer'].get('province', ''),
data['customer'].get('city', '')
)
)
customer_id = cursor.lastrowid
else:
customer_id = customer_id[0]
# 2. 创建订单
order_date = data['order']['date']
formatted_date = f"{order_date[:4]}-{order_date[4:6]}-{order_date[6:8]}"
cursor.execute(
"INSERT INTO orders (customer_id, order_date, total_amount) VALUES (%s, %s, %s)",
(
customer_id,
formatted_date,
data['order']['price']
)
)
order_id = cursor.lastrowid
# 3. 添加订单商品
cursor.execute(
"INSERT INTO order_items (order_id, product_name, quantity, price) VALUES (%s, %s, %s, %s)",
(
order_id,
data['order']['product_name'],
data['order']['quantity'],
data['order']['price']
)
)
conn.commit()
return {"success": True, "message": f"订单已成功添加,订单ID: {order_id}"}
except Exception as e:
conn.rollback()
return {"success": False, "message": f"添加订单失败: {str(e)}"}
finally:
conn.close()
使用 Claude 实现同样功能#
如果您使用 Claude API,实现方式略有不同:
import pymysql
import json
import anthropic
# 配置Claude客户端
client = anthropic.Anthropic(api_key="your_anthropic_api_key")
def process_order_with_claude(order_text):
# 调用Claude解析文本
message = client.messages.create(
model="claude-3-sonnet-20240229",
max_tokens=1000,
system="你是一个订单处理助手,负责从文本中提取客户和订单信息。",
messages=[
{
"role": "user",
"content": f"从以下文本中提取客户信息和订单信息,并以JSON格式返回,格式为:\n{{\"customer\": {{\"name\": \"姓名\", \"role\": \"角色\", \"contact\": \"联系方式\", \"province\": \"省份\", \"city\": \"城市\"}}, \"order\": {{\"date\": \"YYYYMMDD\", \"product_name\": \"商品名称\", \"quantity\": \"数量描述\", \"price\": 价格数字}}}}\n\n文本内容:\n{order_text}"
}
]
)
# 尝试从回复中提取JSON
try:
response_text = message.content[0].text
# 查找JSON部分
json_start = response_text.find('{')
json_end = response_text.rfind('}') + 1
if json_start >= 0 and json_end > json_start:
json_str = response_text[json_start:json_end]
data = json.loads(json_str)
return insert_to_database(data)
else:
return {"success": False, "message": "无法从AI回复中提取JSON数据"}
except Exception as e:
return {"success": False, "message": f"解析失败: {str(e)}"}
在 FastAdmin 框架中集成#
对于使用 PHP FastAdmin 框架的开发者,可以这样集成 LLM 功能:
<?php
namespace app\admin\controller;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
use GuzzleHttp\Client;
class OrderAI extends Backend
{
protected $model = null;
public function _initialize()
{
parent::_initialize();
$this->model = model('Order');
}
public function parseAndInsert()
{
if ($this->request->isPost()) {
$text = $this->request->post('order_text');
try {
// 使用LLM解析文本
$data = $this->parseWithLLM($text);
if (!isset($data['customer']) || !isset($data['order'])) {
$this->error('AI解析失败,无法识别订单信息');
}
Db::startTrans();
// 检查客户是否存在
$customer = Db::name('customer')->where('contact', $data['customer']['contact'])->find();
if (!$customer) {
// 创建新客户
$customerId = Db::name('customer')->insertGetId([
'name' => $data['customer']['name'],
'role' => $data['customer']['role'],
'contact' => $data['customer']['contact'],
'province' => $data['customer']['province'] ?? '',
'city' => $data['customer']['city'] ?? '',
'createtime' => time()
]);
} else {
$customerId = $customer['id'];
}
// 格式化日期
$orderDate = $data['order']['date'];
$formattedDate = strtotime(
substr($orderDate, 0, 4) . '-' .
substr($orderDate, 4, 2) . '-' .
substr($orderDate, 6, 2)
);
// 创建订单
$orderId = Db::name('order')->insertGetId([
'customer_id' => $customerId,
'order_date' => $formattedDate,
'total_amount' => $data['order']['price'],
'status' => 'pending',
'createtime' => time()
]);
// 添加订单商品
Db::name('order_item')->insert([
'order_id' => $orderId,
'product_name' => $data['order']['product_name'],
'quantity' => $data['order']['quantity'],
'price' => $data['order']['price'],
'createtime' => time()
]);
Db::commit();
$this->success('订单添加成功', null, ['order_id' => $orderId]);
} catch (Exception $e) {
Db::rollback();
$this->error('订单添加失败: ' . $e->getMessage());
}
}
return $this->view->fetch();
}
private function parseWithLLM($text)
{
// 使用OpenAI API
$client = new Client();
$response = $client->post('https://api.openai.com/v1/chat/completions', [
'headers' => [
'Authorization' => 'Bearer ' . config('openai.api_key'),
'Content-Type' => 'application/json',
],
'json' => [
'model' => 'gpt-4',
'messages' => [
['role' => 'system', 'content' => '你是一个订单处理助手,负责从文本中提取客户和订单信息。'],
['role' => 'user', 'content' => "从以下文本中提取客户信息和订单信息,并以JSON格式返回:\n\n{$text}"]
],
'temperature' => 0.2,
'max_tokens' => 500
]
]);
$result = json_decode($response->getBody()->getContents(), true);
$content = $result['choices'][0]['message']['content'];
// 提取JSON部分
preg_match('/{.*}/s', $content, $matches);
if (isset($matches[0])) {
return json_decode($matches[0], true);
}
throw new Exception('无法从AI回复中提取有效数据');
}
}
三、LLM 函数调用的优势#
与传统的规则基础解析方法相比,使用 LLM 进行数据处理有以下优势:
- 灵活性强:能处理各种格式的非结构化文本,不需要为每种可能的输入格式编写特定的解析规则
- 理解能力强:能够理解上下文和含义,而不仅仅是匹配模式
- 容错性高:即使输入文本有拼写错误或格式不一致,也能正确提取信息
- 可扩展性好:同一套代码可以处理多种类型的文本输入,只需调整提示词
四、实施建议#
在实际项目中应用 LLM 函数调用时,有以下几点建议:
- 明确定义函数架构:清晰定义输入输出格式,帮助 LLM 更准确地提取信息
- 添加错误处理:LLM 并非 100% 准确,需要添加适当的验证和错误处理机制
- 考虑成本因素:API 调用会产生费用,对于高频场景可以考虑批处理或本地部署模型
- 保护隐私数据:确保发送给 LLM 的数据不包含敏感信息,或使用隐私保护措施
五、结语#
LLM、模型和函数是现代 AI 系统的核心组件。通过理解这些概念并将它们应用到实际业务场景中,我们可以大幅提高工作效率,减少人工错误,并为用户提供更好的体验。随着 AI 技术的不断发展,这些工具将变得更加强大和易用,为更多行业带来创新和变革。
无论您是开发人员、产品经理还是业务决策者,了解这些概念和应用方法都将帮助您更好地利用 AI 技术解决实际问题。
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: