CrewAI AIMindTool 实战指南:用自然语言查询任意数据源
2026/9/6 18:28:52 网站建设 项目流程

CrewAI AIMindTool 实战指南:用自然语言查询任意数据源

【免费下载链接】crewAIFramework for orchestrating role-playing, autonomous AI agents. By fostering collaborative intelligence, CrewAI empowers agents to work together seamlessly, tackling complex tasks.项目地址: https://gitcode.com/GitHub_Trending/cr/crewAI

AIMindTool 是 CrewAI 工具包中用于"自然语言问数据"的内置工具。本篇基于仓库中的 AIMind Tool 文档 与 工具源码实现,完整讲解其安装、配置参数、datasources结构与接入 Agent 的方法,并深入剖析该工具在构造期与运行期的真实调用链,帮助你将 Minds 数据问答能力直接集成进 CrewAI 项目。

什么是 Minds 以及 AIMindTool 能做什么

Minds 是 MindsDB 提供的 AI 系统,工作方式类似大语言模型(LLM),但能力更进一步——它可以从任意数据源回答任意问题。其工作原理分三步完成:

  1. 通过参数化搜索(parametric search)为问题选出最相关的数据;
  2. 通过语义搜索(semantic search)理解问题含义,在正确的上下文中组织响应;
  3. 分析数据并调用机器学习(ML)模型,给出精确答案。

AIMindTool正是这一能力的 CrewAI 封装:你只需配置好数据源的连接参数,就可以用自然语言查询这些数据源。从源码中工具自身的描述看,它支持的数据源包括 PostgreSQL、MySQL、MariaDB、ClickHouse、Snowflake 和 Google BigQuery(见 ai_mind_tool.py 中description字段);更多支持的引擎与连接参数以 Minds 官方数据源文档为准。

安装与前置准备

按官方文档,接入 AIMindTool 需要完成 4 个步骤:

  1. 安装crewai[tools]包:
pip install 'crewai[tools]'
  1. 安装 Minds SDK:
pip install minds-sdk
  1. 注册 Minds 账号并获取 API Key;
  2. 将 API Key 设置为环境变量MINDS_API_KEY

源码层面的两个细节印证了上述要求:

  • AIMindToolpackage_dependencies中声明了"minds-sdk"依赖(见 ai_mind_tool.py),并在__init__中延迟导入minds.client.Clientminds.datasources.DatabaseConfig,若导入失败会抛出带安装提示的ImportError
try: from minds.client import Client from minds.datasources import DatabaseConfig except ImportError as e: raise ImportError( "`minds_sdk` package not found, please run `pip install minds-sdk`" ) from e
  • 工具通过env_vars字段显式声明了对MINDS_API_KEY的依赖(required=True),CrewAI 的项目框架会据此提示缺失的环境变量。

构造 AIMindTool:datasources 参数逐项解析

最小可用的初始化代码如下(来自工具文档):

from crewai_tools import AIMindTool # Initialize the AIMindTool. aimind_tool = AIMindTool( datasources=[ { "description": "house sales data", "engine": "postgres", "connection_data": { "user": "demo_user", "password": "demo_password", "host": "samples.mindsdb.com", "port": 5432, "database": "demo", "schema": "demo_data" }, "tables": ["house_sales"] } ] ) aimind_tool.run("How many 3 bedroom houses were sold in 2008?")

datasources是一个字典列表,每个字典包含以下键:

是否必填说明
description必填该数据源中包含的数据的描述,会随数据源配置一起提交给 Minds
engine必填数据源的引擎(类型),如postgres;支持的引擎列表见 Minds 官方文档
connection_data必填连接参数字典,具体字段随引擎不同而不同
tables可选限定数据源使用的表列表;省略时默认使用数据源中的全部表

从源码看,datasources在类中被定义为list[dict[str, Any]](默认空列表),而 API Key 的获取优先级是:构造函数参数api_key> 环境变量MINDS_API_KEY,两者都缺失时立即抛出ValueError

def __init__(self, api_key: str | None = None, **kwargs: Any) -> None: super().__init__(**kwargs) self.api_key = api_key or os.getenv("MINDS_API_KEY") if not self.api_key: raise ValueError( "API key must be provided either through constructor or " "MINDS_API_KEY environment variable" )

因此,如果你希望在特定环境下使用不同的密钥,也可以直接传入:AIMindTool(api_key="sk-...", datasources=[...])

构造期到底发生了什么:Mind 与数据源是自动创建的

这一点值得特别注意——AIMindTool实例化时并不是"惰性配置",而是会立即与 Minds 服务通信完成资源创建(见 ai_mind_tool.py):

  1. 用 API Key 初始化minds.client.Client
  2. 遍历datasources,为每一项构建DatabaseConfig,数据源名称自动生成:crwai_ds_前缀 +secrets.token_hex(5)生成的随机十六进制串,避免命名冲突;
  3. 创建 Mind:名称为crwai_mind_前缀 + 随机十六进制串,并传入replace=True以便重名时替换,创建成功后将返回的mind.name保存到实例字段mind_name
name = f"{AIMindToolConstants.MIND_NAME_PREFIX}_{secrets.token_hex(5)}" mind = minds_client.minds.create( name=name, datasources=datasources, replace=True ) self.mind_name = mind.name

从源码结构看,每次构造AIMindTool都会在 Minds 侧新建一个独立的 Mind(含其数据源),而不是复用已有资源;MIND_NAME_PREFIXDATASOURCE_NAME_PREFIX常量固定为crwai_mind_crwai_ds_,便于在服务端识别由 CrewAI 创建的资源。另外类定义中还有一个mind_name: str | None = None字段,正常情况下由构造流程自动填充。

运行期原理:Minds API 是 OpenAI 兼容接口

AIMindTool继承 CrewAI 的BaseTool(定义见 base_tool.py),其输入被 Pydantic 模型AIMindToolInputSchema约束为单个自然语言问题字段:

class AIMindToolInputSchema(BaseModel): """Input for AIMind Tool.""" query: str = Field(description="Question in natural language to ask the AI-Mind")

_run方法的实现揭示了一个关键事实:Minds 的查询 API 是 OpenAI 兼容的,所以工具直接用openaiPython 客户端对接,把 Mind 名称当作model参数:

def _run(self, query: str) -> str | None: # The Minds API is OpenAI compatible and therefore, the OpenAI client can be used. openai_client = OpenAI( base_url=AIMindToolConstants.MINDS_API_BASE_URL, api_key=self.api_key ) if self.mind_name is None: raise ValueError("Mind name is not set.") completion = openai_client.chat.completions.create( model=self.mind_name, messages=[{"role": "user", "content": query}], stream=False, ) if not isinstance(completion, ChatCompletion): raise ValueError("Invalid response from AI-Mind") return completion.choices[0].message.content

要点归纳:

  • API 基址固定为常量https://mdb.ai/MINDS_API_BASE_URL);
  • 请求以非流式(stream=False)单轮对话形式发出,model即构造期创建的 Mind 名称;
  • 返回值是ChatCompletionchoices[0].message.content的文本内容,若响应类型不符合预期会抛出ValueError("Invalid response from AI-Mind")
  • 由于mind_name在构造期才被赋值,若绕过__init__直接调用_run会抛出ValueError("Mind name is not set.")

调用aimind_tool.run("How many 3 bedroom houses were sold in 2008?")时,问题会经BaseTool.run的通用封装(参数校验、失败处理等)进入_run,最终以字符串形式返回 Minds 的答案。

将 AIMindTool 交给 Agent

在 CrewAI 项目中,工具通过Agenttools参数注入。文档给出的标准写法(配合@agent装饰器声明式定义)是:

from crewai import Agent from crewai.project import agent # Define an agent with the AIMindTool. @agent def researcher(self) -> Agent: return Agent( config=self.agents_config["researcher"], allow_delegation=False, tools=[aimind_tool] )

Agent 运行时会依据工具的description判断何时调用 AIMindTool——其描述明确提示"当你需要从 PostgreSQL、MySQL、MariaDB、ClickHouse、Snowflake、Google BigQuery 等数据源获取答案时使用,输入应为自然语言问题",这让 LLM 能够准确理解工具的适用场景。AIMindToolcrewai_tools包顶层导出(见 tools/init.py),因此from crewai_tools import AIMindTool即可直接导入使用。

小结与实践建议

  • AIMindTool 的价值在于把"自然语言 → 数据源查询 → 带上下文的答案"这条链路封装成 Agent 可用的单个工具,你只需要管好 API Key 和连接参数;
  • 配置时datasources四项中tables是唯一可选项,省略即默认使用数据源全部表;需要缩小查询范围时建议显式指定;
  • 注意构造即创建:每次实例化都会在 Minds 端创建带随机后缀的 Mind 与数据源,且 API Key 缺失会在构造阶段直接报错,而不是等到运行时;
  • 运行期走的是 OpenAI 兼容接口,非流式单次对话,返回值为纯文本答案;
  • 更多引擎类型与各引擎的connection_data字段,请以 Minds 官方数据源文档为准;本仓库中该工具的实现位于 lib/crewai-tools/src/crewai_tools/tools/ai_mind_tool/,可结合 tool.specs.json 查看工具注册元信息。

【免费下载链接】crewAIFramework for orchestrating role-playing, autonomous AI agents. By fostering collaborative intelligence, CrewAI empowers agents to work together seamlessly, tackling complex tasks.项目地址: https://gitcode.com/GitHub_Trending/cr/crewAI

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询