Windows平台深度学习入门:通过LangChain将Ollama接入MySQL数据库

云信安装大师
90
AI 质量分
11 5 月, 2025
3 分钟阅读
0 阅读

Windows平台深度学习入门:通过LangChain将Ollama接入MySQL数据库

引言

在Windows平台上构建深度学习应用时,经常需要将大型语言模型(LLM)与数据库连接起来。本教程将展示如何使用LangChain框架将Ollama本地运行的LLM与MySQL数据库集成,实现数据查询和自然语言交互功能。

准备工作

环境要求

  • Windows 10/11 64位系统
  • Python 3.8+
  • MySQL 8.0+
  • Ollama本地运行环境

安装必要组件

首先打开PowerShell或CMD,安装所需Python包:

代码片段
# 安装LangChain和相关依赖
pip install langchain langchain-community mysql-connector-python ollama

启动Ollama服务

确保Ollama服务已在本地运行。如果没有安装,可以前往Ollama官网下载Windows版本并安装。

代码片段
# 启动Ollama服务(如果未设置为自动启动)
ollama serve

配置MySQL数据库

1. 创建示例数据库

代码片段
CREATE DATABASE langchain_demo;
USE langchain_demo;

CREATE TABLE products (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    category VARCHAR(50) NOT NULL,
    price DECIMAL(10,2) NOT NULL,
    stock INT NOT NULL
);

INSERT INTO products (name, category, price, stock) VALUES 
('Laptop', 'Electronics', 999.99, 50),
('Smartphone', 'Electronics', 699.99, 100),
('Desk Chair', 'Furniture', 149.99, 30),
('Coffee Maker', 'Appliances', 79.99, 25);

2. 创建数据库用户并授权

代码片段
CREATE USER 'langchain_user'@'localhost' IDENTIFIED BY 'securepassword';
GRANT ALL PRIVILEGES ON langchain_demo.* TO 'langchain_user'@'localhost';
FLUSH PRIVILEGES;

LangChain集成实现

1. MySQL连接设置

创建db_connection.py文件:

代码片段
from mysql.connector import connect, Error

def get_db_connection():
    try:
        connection = connect(
            host="localhost",
            user="langchain_user",
            password="securepassword",
            database="langchain_demo"
        )
        return connection
    except Error as e:
        print(f"Error connecting to MySQL: {e}")
        return None

2. LangChain与Ollama集成

创建ollama_mysql.py文件:

代码片段
from langchain_community.llms import Ollama
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from db_connection import get_db_connection

# 初始化Ollama LLM (使用mistral模型)
llm = Ollama(model="mistral")

# MySQL连接测试函数
def test_mysql_connection():
    conn = get_db_connection()
    if conn:
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM products LIMIT 1")
        result = cursor.fetchone()
        print("MySQL连接测试成功,示例数据:", result)
        conn.close()

# SQL查询执行函数
def execute_sql_query(query):
    conn = get_db_connection()
    if not conn:
        return "无法连接到数据库"

    try:
        cursor = conn.cursor(dictionary=True)
        cursor.execute(query)

        if query.strip().lower().startswith("select"):
            results = cursor.fetchall()
            return results if results else "查询无结果"
        else:
            conn.commit()
            return f"操作成功,影响行数: {cursor.rowcount}"

    except Exception as e:
        return f"SQL执行错误: {str(e)}"
    finally:
        if conn:
            conn.close()

# NL转SQL的提示模板
prompt_template = """
你是一个专业的SQL编写助手。根据用户的问题和下面的表结构,编写合适的MySQL查询语句。

表结构:
products(id, name, category, price, stock)

问题: {question}

请只返回SQL查询语句,不要包含其他解释或说明。
"""

prompt = PromptTemplate.from_template(prompt_template)
sql_chain = LLMChain(llm=llm, prompt=prompt)

def natural_language_to_sql(question):
    # Step1: NL转SQL
    generated_sql = sql_chain.run(question=question)

    # Step2: SQL执行并获取结果
    query_result = execute_sql_query(generated_sql)

    # Step3: LLM解释结果(可选)
    explanation_prompt = f"""
    原始问题: {question}
    生成的SQL: {generated_sql}
    查询结果: {query_result}

    请用自然语言解释这些结果。
    """

    explanation = llm(explanation_prompt)

    return {
        "generated_sql": generated_sql,
        "query_result": query_result,
        "explanation": explanation.strip()
    }

if __name__ == "__main__":
    test_mysql_connection()

    while True:
        question = input("\n请输入您的问题(输入q退出): ")
        if question.lower() == 'q':
            break

        response = natural_language_to_sql(question)

        print("\n=== SQL生成 ===")
        print(response["generated_sql"])

        print("\n=== 查询结果 ===")
        print(response["query_result"])

        print("\n=== AI解释 ===")
        print(response["explanation"])

运行与测试

在PowerShell中运行脚本:

代码片段
python ollama_mysql.py

测试示例问题:
1. “显示所有电子产品”
2. “哪些商品价格低于100美元且库存超过20件?”
3. “计算每个类别的商品数量”

实践经验与注意事项

  1. 模型选择

    • Ollama支持多种模型(mistral、llama2等),可以根据硬件配置选择合适的模型大小
    • GPU加速建议使用NVIDIA显卡并安装CUDA驱动
  2. 性能优化

    代码片段
    # Ollama初始化时可以调整参数提高性能/质量平衡
    llm = Ollama(
        model="mistral",
        temperature=0.7,      # 控制创造性(0-1) 
        num_predict=512       # max tokens生成数限制 
    )
    
  3. 安全考虑

    • SQL注入防护:实际生产环境中应添加输入验证和参数化查询
    • API密钥管理:使用环境变量存储敏感信息而非硬编码在代码中
  4. 常见错误解决

    • ConnectionError:

      • 检查Ollama服务是否运行(ollama list)
      • Windows防火墙可能需要放行端口11434
    • MySQL Access Denied:

      代码片段
      -- MySQL中重新授权用户权限解决连接问题
      GRANT ALL PRIVILEGES ON *.* TO 'langchain_user'@'localhost';
      FLUSH PRIVILEGES;
      
  5. 扩展方向

    • RAG架构:添加向量数据库实现基于文档的增强检索功能
    • Web界面:使用Gradio或Streamlit构建交互式界面

总结

本教程完整展示了在Windows平台上:
1. Ollama本地LLM服务的部署和使用方法 ✔️
2. LangChain框架集成MySQL数据库的技术方案 ✔️
3. NL到SQL转换的完整实现流程 ✔️
4. Python代码最佳实践和安全考虑 ✔️

通过这种集成方式,开发者可以轻松构建能够理解自然语言并操作关系型数据库的智能应用系统。

原创 高质量