|
| 1 | +"""A sqlite database assistant implemented by assistant""" |
| 2 | + |
| 3 | +import os |
| 4 | +import asyncio |
| 5 | +from typing import Optional |
| 6 | + |
| 7 | +from qwen_agent.agents import Assistant |
| 8 | +from qwen_agent.gui import WebUI |
| 9 | + |
| 10 | +ROOT_RESOURCE = os.path.join(os.path.dirname(__file__), 'resource') |
| 11 | + |
| 12 | + |
| 13 | +def init_agent_service(): |
| 14 | + llm_cfg = { |
| 15 | + 'model': 'qwen3:30b-a3b', |
| 16 | + 'model_server': 'http://localhost:11434/v1/' |
| 17 | + } |
| 18 | + system = ('你扮演一个数据库助手,你具有查询数据库的能力') |
| 19 | + tools = [{ |
| 20 | + "mcpServers": { |
| 21 | + "sqlite" : { |
| 22 | + "command": "uvx", |
| 23 | + "args": [ |
| 24 | + "mcp-server-sqlite", |
| 25 | + "--db-path", |
| 26 | + "test.db" |
| 27 | + ] |
| 28 | + } |
| 29 | + } |
| 30 | + }] |
| 31 | + bot = Assistant( |
| 32 | + llm=llm_cfg, |
| 33 | + name='数据库助手', |
| 34 | + description='数据库查询', |
| 35 | + system_message=system, |
| 36 | + function_list=tools, |
| 37 | + ) |
| 38 | + |
| 39 | + return bot |
| 40 | + |
| 41 | + |
| 42 | +def test(query='数据库里有几张表', file: Optional[str] = os.path.join(ROOT_RESOURCE, 'poem.pdf')): |
| 43 | + # Define the agent |
| 44 | + bot = init_agent_service() |
| 45 | + |
| 46 | + # Chat |
| 47 | + messages = [] |
| 48 | + |
| 49 | + if not file: |
| 50 | + messages.append({'role': 'user', 'content': query}) |
| 51 | + else: |
| 52 | + messages.append({'role': 'user', 'content': [{'text': query}, {'file': file}]}) |
| 53 | + |
| 54 | + for response in bot.run(messages): |
| 55 | + print('bot response:', response) |
| 56 | + |
| 57 | + |
| 58 | +def app_tui(): |
| 59 | + # Define the agent |
| 60 | + bot = init_agent_service() |
| 61 | + |
| 62 | + # Chat |
| 63 | + messages = [] |
| 64 | + while True: |
| 65 | + # Query example: 数据库里有几张表 |
| 66 | + query = input('user question: ') |
| 67 | + # File example: resource/poem.pdf |
| 68 | + file = input('file url (press enter if no file): ').strip() |
| 69 | + if not query: |
| 70 | + print('user question cannot be empty!') |
| 71 | + continue |
| 72 | + if not file: |
| 73 | + messages.append({'role': 'user', 'content': query}) |
| 74 | + else: |
| 75 | + messages.append({'role': 'user', 'content': [{'text': query}, {'file': file}]}) |
| 76 | + |
| 77 | + response = [] |
| 78 | + for response in bot.run(messages): |
| 79 | + print('bot response:', response) |
| 80 | + messages.extend(response) |
| 81 | + |
| 82 | + |
| 83 | +def app_gui(): |
| 84 | + # Define the agent |
| 85 | + bot = init_agent_service() |
| 86 | + chatbot_config = { |
| 87 | + 'prompt.suggestions': [ |
| 88 | + '数据库里有几张表', |
| 89 | + '创建一个学生表包括学生的姓名、年龄', |
| 90 | + '增加一个学生名字叫韩梅梅,今年6岁', |
| 91 | + ] |
| 92 | + } |
| 93 | + WebUI( |
| 94 | + bot, |
| 95 | + chatbot_config=chatbot_config, |
| 96 | + ).run() |
| 97 | + |
| 98 | + |
| 99 | +if __name__ == '__main__': |
| 100 | + # test() |
| 101 | + app_tui() |
| 102 | + #app_gui() |
0 commit comments