工具感知对话代理

Gemini Tool Agent 是一个基于 Google Gemini AI 模型的 Python 库,用于创建支持自定义工具的结构化对话代理,适用于需要自动化工具集成的开发场景。

  • by paulfruitful
  • Python
  • 本地部署
  • 2 星标
  • 更新于
在 GitHub 查看 paulfruitful/gemini-tool-agent

使用说明

Gemini工具代理

一个轻量级的、工具感知的Gemini代理,用于处理对话中的结构化提示和工具使用。

概述

Gemini Tool Agent是一个Python库,它提供了一个简单的接口,用于创建由谷歌Gemini AI模型支持的工具感知代理。它使开发人员能够使用结构化输入模式定义自定义工具,并将其无缝集成到会话流中。

特性

  • 工具感知的对话处理
  • 结构化提示处理
  • 自动上下文管理
  • JSON响应解析
  • 对话历史跟踪

安装

pip install gemini-tool-agent

需求

  • Python 3.8或更高版本
  • 谷歌生成人工智能Python SDK(谷歌genai>=0.3.2)

用法

from gemini_tool_agent.agent import Agent

# Initialize the agent with your API key
agent = Agent(key="your-api-key")

# Define your tools
agent.tools = [
    {
        "name": "save_note",
        "description": "Save a note to the database",
        "input_schema": {
            "title": "string",
            "content": "string"
        }
    }
]

# Process a query that might use tools
response = agent.process_query("Save a note about AI agents")
print(response)

响应格式

代理以JSON格式返回结构化响应:

{
  "needs_tool": true,
  "tool_name": "save_note",
  "needs_direct_response": true,
  "direct_response_first": false,
  "reasoning": "The query explicitly asks to save a note, which requires the save_note tool",
  "direct_response": "AI agents are software entities that can perform tasks autonomously..."
}

刀具参数提取

在确定需要使用工具后,您可以从对话中提取参数:

# First process the query to determine if a tool is needed
response = agent.process_query("Save a note titled 'AI Agents' with content about machine learning")

# If a tool is needed, extract the parameters
if response.get("needs_tool", False):
    tool_name = response.get("tool_name")
    tool_params = agent.process_use_tool(tool_name)
    
    # Now you can use the extracted parameters to execute the tool
    print(tool_params)
    # Output: {'tool_name': 'save_note', 'input': {'title': 'AI Agents', 'content': '...'}}  
    #You can then execute the tool with the extracted parameters

优化响应生成

该代理会自动处理大型提示以提高内存效率:

# For direct usage (normally used internally by the agent)
response_text = agent.generate_response(large_prompt)

# The method automatically optimizes prompts over 10,000 characters by:
# - Trimming conversation history to the most recent 15 lines when needed
# - Truncating large direct responses while preserving start and end content

高级用法

您可以访问对话历史记录:

# Get the conversation history
history = agent.history

许可证

麻省理工学院

作者

保罗硕果累累(fruitful2007@outlook.com)