看我破烂笔记本如何跑qwen3大模型【3】更简明python代码示例:本地qwen agent操控sqlite数据库

在这里插入图片描述
经过前两章【1】【2】的操作,本章我们用比官方示例更简单的代码实现本地qwen agent操控sqlite数据库。
首先看阿里官方的代码:
地址:https://github.com/QwenLM/Qwen-Agent/blob/main/examples/assistant_mcp_sqlite_bot.py
这段代码距离跑起来,对于小白还是有点难度,我认为它不是一个好的示例,有些没必要的功能,徒增读者的烦恼。耗费了我不少时间。

# Copyright 2023 The Qwen team, Alibaba Group. All rights reserved.
# 
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#    http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""A sqlite database assistant implemented by assistant"""

import os
import asyncio
from typing import Optional

from qwen_agent.agents import Assistant
from qwen_agent.gui import WebUI

ROOT_RESOURCE = os.path.join(os.path.dirname(__file__), 'resource')


def init_agent_service():
    llm_cfg = {'model': 'qwen-max'}
    system = ('你扮演一个数据库助手,你具有查询数据库的能力')
    tools = [{
        "mcpServers": {
            "sqlite" : {
                "command": "uvx",
                "args": [
                    "mcp-server-sqlite",
                    "--db-path",
                    "test.db"
                ]
            }
        }
    }]
    bot = Assistant(
        llm=llm_cfg,
        name='数据库助手',
        description='数据库查询',
        system_message=system,
        function_list=tools,
    )

    return bot


def test(query='数据库里有几张表', file: Optional[str] = os.path.join(ROOT_RESOURCE, 'poem.pdf')):
    # Define the agent
    bot = init_agent_service()

    # Chat
    messages = []

    if not file:
        messages.append({'role': 'user', 'content': query})
    else:
        messages.append({'role': 'user', 'content': [{'text': query}, {'file': file}]})

    for response in bot.run(messages):
        print('bot response:', response)


def app_tui():
    # Define the agent
    bot = init_agent_service()

    # Chat
    messages = []
    while True:
        # Query example: 数据库里有几张表
        query = input('user question: ')
        # File example: resource/poem.pdf
        file = input('file url (press enter if no file): ').strip()
        if not query:
            print('user question cannot be empty!')
            continue
        if not file:
            messages.append({'role': 'user', 'content': query})
        else:
            messages.append({'role': 'user', 'content': [{'text': query}, {'file': file}]})

        response = []
        for response in bot.run(messages):
            print('bot response:', response)
        messages.extend(response)


def app_gui():
    # Define the agent
    bot = init_agent_service()
    chatbot_config = {
        'prompt.suggestions': [
            '数据库里有几张表',
            '创建一个学生表包括学生的姓名、年龄',
            '增加一个学生名字叫韩梅梅,今年6岁',
        ]
    }
    WebUI(
        bot,
        chatbot_config=chatbot_config,
    ).run()


if __name__ == '__main__':
    # test()
    # app_tui()
    app_gui()

下面我会给我的代码,更为简单直接明了,已经运行通过。

from qwen_agent.agents import Assistant
from qwen_agent.gui import WebUI
from qwen_agent.utils.output_beautify import typewriter_print

def init_agent_service():
    llm_cfg = {
        'model': 'qwen3:1.7b',
        'model_server':'http://127.0.0.1:11434/v1',#默认的地址
        'api_key': 'ollama',#默认的key
        'generate_cfg': {
            'top_p': 0.8
            } #(可选) LLM 的采样超参数,用于控制生成文本的多样性。它的值通常在 0 到 1 之间,其中 0 表示完全不考虑多样性,1 表示完全考虑多样性。
        }
    system = ('你是一个数据分析师,具有对本地数据库的增删改查能力,同时具有使用python代码的能力')
    tools = [{
        "mcpServers": {
            "sqlite": {
                "command": "uvx",
                "args": [
                    "mcp-server-sqlite",
                    "--db-path",
                    "D:/mypy2025/test.db" #自定义的数据库地址
                ]
            }
        }
    }]
    bot = Assistant(
        llm=llm_cfg,
        name='数据库助手',
        description='你是一位数据库管理员,具有对本地数据库的增删改查能力',
        system_message=system,
        function_list=tools
    )

    return bot
def run_query(query=None):
    # 定义数据库助手
    bot = init_agent_service()
    
    WebUI(bot).run()  # 启动WebUI界面

    messages = []
    messages.append({'role': 'user', 'content': [{'text': query}]})
    previous_text = ""
    print('数据库助手: ', end='', flush=True)

    for response in bot.run(messages):
        previous_text = typewriter_print(response, previous_text)

if __name__ == '__main__':

    query = '帮我查询student表,包括学生的所有信息'
    run_query(query)

在vs code终端中运行以上代码:

PS D:\mypy2025> & D:/py313/python.exe d:/mypy2025/assistant_mcp_sqlite_bot.py
2025-06-12 23:16:34,300 - mcp_manager.py - 141 - INFO - Initializing MCP tools from mcp servers: ['sqlite']
2025-06-12 23:16:34,364 - mcp_manager.py - 370 - INFO - Initializing a MCP stdio_client, if this takes forever, please check the config of this mcp server: sqlite
2025-06-12 23:16:38,907 - mcp_manager.py - 237 - INFO - Failed in listing MCP resource templates: Method not found
* Running on local URL:  http://127.0.0.1:7860

To create a public link, set `share=True` in `launch()`.

在浏览器中打开给出的地址http://127.0.0.1:7860
将会看到:
在这里插入图片描述
大功告成了么?并没有!哈哈哈
qwen3模型此刻还没有运行,你看到的只是界面,一张没有脑子的脸。
下次在运行之前,首先应在命令行提示符中启动ollama调用大模型,如图:
在这里插入图片描述
然后关掉命令提示符窗口,放心,ollama在后台已经运行。屏幕右下角你能找到它的图标。
agent花了10s(毕竟是破烂笔记本),回答了我的数据库查询命令:“帮我查询student表,包括学生的所有信息”,截图如下:
在这里插入图片描述
接下来,她就是你的了,尽情折腾吧!
由此出发,开始我们的AI之旅。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

狮弟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值