FEATURED · 精选文章

【Agent】22. OpenAI智能体查询引擎实验指南

发布时间 / 2026/9/15 10:29:29
来源 / 创域科博编辑部
栏目 / 资讯中心
【Agent】22. OpenAI智能体查询引擎实验指南 1. 案例目标本案例旨在展示如何使用LlamaIndex的FunctionAgent结合多种查询引擎工具实现复杂查询任务。主要目标包括探索FunctionAgent在不同查询引擎工具上的应用演示自动检索、SQL查询与向量搜索的结合使用展示如何通过智能体协调多种数据源回答复杂问题提供多工具智能体的实现模板和最佳实践2. 技术栈与核心依赖核心框架LlamaIndex - 数据查询与索引框架OpenAI GPT模型 - 语言理解与生成FunctionAgent - 智能体实现数据存储Pinecone - 向量数据库SQL数据库 - 结构化数据存储VectorStoreIndex - 向量索引主要依赖包pip install llama-indexpip install llama-index-llms-openaipip install llama-index-agent-openaipip install llama-index-readers-wikipediapip install llama-index-vector-stores-pineconepip install pinecone-clientpip install sqlalchemy3. 环境配置API密钥设置import osos.environ[OPENAI_API_KEY] sk-...os.environ[PINECONE_API_KEY] ...模型配置from llama_index.llms.openai import OpenAIfrom llama_index.embeddings.openai import OpenAIEmbeddingfrom llama_index.core import SettingsSettings.llm OpenAI(modelgpt-4o)Settings.embed_model OpenAIEmbedding(modeltext-embedding-3-small)Pinecone初始化import pineconepc pinecone.Pinecone(api_keyPINECONE_API_KEY)index_name quickstart-indexif index_name not in pc.list_indexes().names():pc.create_index(nameindex_name,dimension1536,metriceuclidean)4. 案例实现4.1 自动检索工具实现首先实现一个自动检索工具可以根据查询自动从向量存储中检索相关文档from llama_index.core.retrievers import VectorIndexAutoRetrieverfrom llama_index.core.vector_stores import MetadataInfo, VectorStoreInfofrom llama_index.core.query_engine import RetrieverQueryEnginevector_store_info VectorStoreInfo(content_infobrief biography of celebrities,metadata_info[MetadataInfo(namecategory, typestr, descriptionCategory of the celebrity),MetadataInfo(namecountry, typestr, descriptionCountry of the celebrity),],)auto_retriever VectorIndexAutoRetriever(vector_index, vector_store_infovector_store_info)retriever_query_engine RetrieverQueryEngine.from_args(auto_retriever,)4.2 SQL查询工具实现创建SQL查询引擎用于处理结构化数据查询from llama_index.core import SQLDatabasefrom llama_index.core.query_engine import NLSQLTableQueryEngine# 创建SQL数据库sql_database SQLDatabase.from_uri(sqlite:///cities.db)# 创建自然语言到SQL的查询引擎query_engine NLSQLTableQueryEngine(sql_databasesql_database,tables[city_stats],)4.3 智能体工具集成将查询引擎封装为工具并集成到FunctionAgent中from llama_index.core.tools import QueryEngineToolfrom llama_index.core.agent.workflow import FunctionAgent# 创建工具sql_tool QueryEngineTool.from_defaults(query_enginequery_engine,namesql_tool,description(Useful for translating a natural language query into a SQL query over a table containing: city_stats, containing the population/country of each city),)vector_tool QueryEngineTool.from_defaults(query_engineretriever_query_engine,namevector_tool,description(Useful for answering semantic questions about different cities),)# 创建智能体agent FunctionAgent(tools[sql_tool, vector_tool],llmOpenAI(modelgpt-4o),)4.4 智能体执行查询使用智能体执行复杂查询自动选择合适的工具from llama_index.core.workflow import Context# 创建上下文ctx Context(agent)# 执行查询handler agent.run(Tell me about the arts and culture of the city with the highest population.,ctxctx,)# 流式处理结果async for ev in handler.stream_events():if isinstance(ev, ToolCallResult):print(f\\nCalled tool {ev.tool_name} with args {ev.tool_kwargs}, got response: {ev.tool_output})elif isinstance(ev, AgentStream):print(ev.delta, end, flushTrue)response await handler5. 案例效果5.1 查询示例1人口最多城市的文化信息当用户询问Tell me about the arts and culture of the city with the highest population时智能体会首先调用sql_tool查询人口最多的城市返回Tokyo然后调用vector_tool查询东京的艺术和文化信息综合两个工具的结果提供完整的回答输出结果Called tool sql_tool with args {input: SELECT city FROM city_stats ORDER BY population DESC LIMIT 1;}, got response: The city with the highest population is Tokyo.Called tool vector_tool with args {input: Tell me about the arts and culture of Tokyo.}, got response: Tokyo boasts a vibrant arts and culture scene, characterized by a diverse range of museums, galleries, and performance venues. Ueno Park is a cultural hub, housing the Tokyo National Museum, which specializes in traditional Japanese art...5.2 查询示例2城市历史信息当用户询问Tell me about the history of Berlin时智能体会识别需要查询柏林的历史信息调用vector_tool检索柏林相关文档返回柏林的详细历史信息输出结果Called tool vector_tool with args {input: Tell me about the history of Berlin.}, got response: Berlins history dates back to prehistoric times, with evidence of human settlements as early as 60,000 BC. The area saw the emergence of various cultures, including the Maglemosian culture around 9,000 BC...5.3 查询示例3城市与国家对应关系当用户询问Can you give me the country corresponding to each city?时智能体会识别需要查询所有城市及其对应的国家调用sql_tool执行SQL查询返回城市与国家的对应列表输出结果Here are the cities along with their corresponding countries:- Toronto is in Canada.- Tokyo is in Japan.- Berlin is in Germany.6. 案例实现思路6.1 整体架构本案例采用多工具智能体架构主要包括以下组件FunctionAgent作为核心协调器负责理解用户意图并选择合适的工具QueryEngineTool将不同类型的查询引擎封装为统一接口的工具向量检索工具处理非结构化数据的语义查询SQL查询工具处理结构化数据的精确查询6.2 关键技术点自动检索机制通过VectorIndexAutoRetriever实现基于元数据的自动过滤和检索自然语言到SQL转换使用NLSQLTableQueryEngine将自然语言查询转换为SQL语句工具描述设计为每个工具提供清晰的描述帮助智能体理解工具用途上下文管理使用Context对象维护智能体的会话状态6.3 工作流程用户提出查询请求FunctionAgent分析查询意图根据工具描述选择最合适的工具调用工具执行查询收集工具返回的结果整合结果并生成最终回答7. 扩展建议7.1 功能扩展添加更多工具类型如API调用工具、计算工具、时间序列分析工具等实现工具链允许一个工具的输出作为另一个工具的输入实现更复杂的工作流多模态支持添加图像、音频等多媒体内容的处理工具记忆机制为智能体添加长期记忆记住之前的交互和结果7.2 性能优化并行工具调用对于可并行的查询同时调用多个工具提高效率缓存机制缓存常用查询结果减少重复计算工具选择优化基于历史数据优化工具选择策略增量索引更新支持向量索引的增量更新保持数据最新7.3 应用场景企业知识库问答整合企业内部多种数据源提供统一查询入口多源数据分析结合结构化和非结构化数据进行综合分析研究助手帮助研究人员从多种文献和数据源中获取信息个性化推荐结合用户行为数据和内容特征提供精准推荐8. 总结本案例展示了如何使用LlamaIndex的FunctionAgent结合多种查询引擎工具实现复杂查询任务。通过将向量检索和SQL查询等不同类型的工具集成到统一框架中智能体能够根据查询意图自动选择最合适的工具并综合多个工具的结果提供全面回答。案例的核心价值在于统一接口通过工具封装为不同类型的数据源提供统一查询接口智能选择智能体能够根据查询内容自动选择最合适的工具结果整合能够整合多个工具的结果提供全面的回答可扩展性框架设计支持轻松添加新的工具类型这种多工具智能体架构为构建复杂的数据查询和分析系统提供了强大而灵活的基础可广泛应用于企业知识管理、数据分析和智能问答等领域。
RELATED — 相关阅读

相关资讯

LATEST — 最新资讯

最新发布

TODAY — 本日精选

新闻

WEEKLY — 本周精选

新闻

MONTHLY — 本月精选

新闻