Goose API参考:完整接口文档和使用示例

Goose API参考:完整接口文档和使用示例

【免费下载链接】goose an open source, extensible AI agent that goes beyond code suggestions - install, execute, edit, and test with any LLM 【免费下载链接】goose 项目地址: https://gitcode.com/GitHub_Trending/goose3/goose

Goose是一个开源、可扩展的AI代理框架,提供丰富的RESTful API接口,支持开发者构建智能化的自动化工作流。本文档详细介绍了Goose的核心API接口、请求响应格式以及实际使用示例。

🚀 API基础信息

认证方式

所有API请求都需要在Header中包含认证信息:

X-Secret-Key: your-secret-key

基础URL

http://localhost:8080

📋 API接口分类

1. 配置管理API

获取所有配置
GET /config

响应示例:

{
  "config": {
    "GOOSE_MODEL": "gpt-4o",
    "OPENAI_API_KEY": "sk-...",
    "GOOSE_MODE": "auto"
  }
}
更新配置项
POST /config/upsert
Content-Type: application/json

{
  "key": "GOOSE_MODEL",
  "value": "claude-3-opus",
  "is_secret": false
}
删除配置项
POST /config/remove
Content-Type: application/json

{
  "key": "GOOSE_MODEL",
  "is_secret": false
}

2. 扩展管理API

获取所有扩展
GET /config/extensions

响应示例:

{
  "extensions": [
    {
      "enabled": true,
      "config": {
        "name": "filesystem",
        "description": "文件系统操作扩展",
        "version": "1.0.0"
      }
    }
  ]
}
添加扩展
POST /config/extensions
Content-Type: application/json

{
  "name": "github",
  "config": {
    "api_key": "ghp_...",
    "base_url": "https://api.github.com"
  },
  "enabled": true
}

3. 代理管理API

获取可用工具
GET /agent/tools?extension_name=filesystem

响应示例:

[
  {
    "name": "read_file",
    "description": "读取文件内容",
    "parameters": ["path"],
    "permission": "auto"
  },
  {
    "name": "write_file",
    "description": "写入文件内容",
    "parameters": ["path", "content"],
    "permission": "ask_before"
  }
]
更新模型提供商
POST /agent/update_provider
Content-Type: application/json

{
  "provider": "openai",
  "model": "gpt-4o"
}

4. 会话管理API

获取会话列表
GET /sessions

响应示例:

{
  "sessions": [
    {
      "id": "session-123",
      "created_at": "2024-01-15T10:30:00Z",
      "status": "completed",
      "task": "代码生成"
    }
  ]
}
获取会话历史
GET /sessions/{session_id}/history

5. 配方管理API

创建配方
POST /recipes
Content-Type: application/json

{
  "name": "web-scraper",
  "description": "网页抓取配方",
  "steps": [
    {
      "action": "fetch_url",
      "parameters": {
        "url": "https://example.com"
      }
    }
  ]
}
列出所有配方
GET /recipes

🔧 核心数据结构

消息结构

interface Message {
  role: 'user' | 'assistant' | 'system';
  content: MessageContent;
  timestamp: string;
}

interface MessageContent {
  type: 'text' | 'image' | 'file';
  text?: string;
  url?: string;
}

工具调用结构

interface ToolRequest {
  name: string;
  parameters: Record<string, any>;
  confirmation_required: boolean;
}

interface ToolResponse {
  success: boolean;
  result: any;
  error?: string;
}

🎯 使用示例

示例1:自动化代码生成

import requests
import json

class GooseClient:
    def __init__(self, base_url="http://localhost:8080", api_key="your-secret-key"):
        self.base_url = base_url
        self.headers = {
            "X-Secret-Key": api_key,
            "Content-Type": "application/json"
        }
    
    def generate_code(self, task_description):
        """使用Goose生成代码"""
        payload = {
            "task": task_description,
            "language": "python",
            "requirements": ["使用pandas", "包含错误处理"]
        }
        
        response = requests.post(
            f"{self.base_url}/agent/execute",
            headers=self.headers,
            json=payload
        )
        
        if response.status_code == 200:
            return response.json()["code"]
        else:
            raise Exception(f"代码生成失败: {response.text}")

# 使用示例
client = GooseClient()
code = client.generate_code("创建一个读取CSV文件并计算统计信息的Python脚本")
print(code)

示例2:批量文件处理

const axios = require('axios');

class GooseBatchProcessor {
  constructor(apiKey) {
    this.client = axios.create({
      baseURL: 'http://localhost:8080',
      headers: { 'X-Secret-Key': apiKey }
    });
  }

  async processFiles(filePaths, operation) {
    const results = [];
    
    for (const filePath of filePaths) {
      try {
        const response = await this.client.post('/agent/execute', {
          tool: 'file_operation',
          parameters: {
            operation: operation,
            file_path: filePath
          }
        });
        
        results.push({
          file: filePath,
          success: true,
          result: response.data
        });
      } catch (error) {
        results.push({
          file: filePath,
          success: false,
          error: error.message
        });
      }
    }
    
    return results;
  }
}

// 使用示例
const processor = new GooseBatchProcessor('your-api-key');
const results = await processor.processFiles(
  ['file1.txt', 'file2.txt', 'file3.txt'],
  'analyze'
);

示例3:智能工作流编排

#!/bin/bash

# 配置Goose环境
export GOOSE_API_KEY="your-secret-key"
export GOOSE_BASE_URL="http://localhost:8080"

# 定义工作流函数
run_workflow() {
    local task=$1
    local prompt=$2
    
    curl -X POST "${GOOSE_BASE_URL}/agent/execute" \
        -H "X-Secret-Key: ${GOOSE_API_KEY}" \
        -H "Content-Type: application/json" \
        -d "{
            \"task\": \"${task}\",
            \"prompt\": \"${prompt}\",
            \"max_steps\": 10,
            \"timeout\": 300
        }"
}

# 执行复杂工作流
echo "开始数据分析和报告生成工作流..."

# 步骤1: 数据收集
run_workflow "data-collection" "从API收集最新数据"

# 步骤2: 数据处理
run_workflow "data-processing" "清洗和转换数据"

# 步骤3: 分析生成
run_workflow "analysis" "生成统计分析和可视化"

# 步骤4: 报告编写
run_workflow "reporting" "创建详细的报告文档"

echo "工作流执行完成!"

📊 错误处理

Goose API使用标准的HTTP状态码:

状态码含义处理建议
200成功正常处理响应
400错误请求检查请求参数
401未授权验证API密钥
404未找到检查资源路径
429频率限制降低请求频率
500服务器错误联系技术支持

错误响应示例:

{
  "error": "Invalid API key",
  "code": "AUTH_001",
  "details": "提供的API密钥无效或已过期"
}

🔐 权限管理

Goose支持细粒度的工具权限控制:

POST /config/permissions
Content-Type: application/json

{
  "tool_permissions": [
    {
      "tool_name": "execute_command",
      "permission": "ask_before"
    },
    {
      "tool_name": "read_file", 
      "permission": "auto"
    }
  ]
}

权限级别说明:

  • auto: 自动批准,无需确认
  • ask_before: 执行前需要用户确认
  • deny: 完全拒绝执行

🚦 速率限制

Goose API设有速率限制保护:

  • 普通接口:60请求/分钟
  • 计算密集型接口:10请求/分钟
  • 批量操作接口:5请求/分钟

建议在客户端实现适当的重试机制和退避策略。

📈 监控和日志

获取运行状态

GET /health

响应示例:

{
  "status": "healthy",
  "version": "1.0.0",
  "uptime": "5h30m",
  "memory_usage": "256MB",
  "active_sessions": 3
}

查看日志

GET /logs?level=info&limit=100

🔗 集成示例

Python集成封装

import requests
from typing import Dict, List, Optional
from dataclasses import dataclass
import json

@dataclass
class GooseConfig:
    base_url: str = "http://localhost:8080"
    api_key: str = ""
    timeout: int = 30

class GooseAPI:
    def __init__(self, config: GooseConfig):
        self.config = config
        self.session = requests.Session()
        self.session.headers.update({
            "X-Secret-Key": config.api_key,
            "Content-Type": "application/json"
        })
    
    def execute_task(self, task: str, parameters: Dict = None) -> Dict:
        """执行AI任务"""
        payload = {
            "task": task,
            "parameters": parameters or {}
        }
        
        response = self.session.post(
            f"{self.config.base_url}/agent/execute",
            json=payload,
            timeout=self.config.timeout
        )
        response.raise_for_status()
        return response.json()
    
    def get_tools(self, extension: Optional[str] = None) -> List[Dict]:
        """获取可用工具列表"""
        params = {}
        if extension:
            params["extension_name"] = extension
        
        response = self.session.get(
            f"{self.config.base_url}/agent/tools",
            params=params,
            timeout=self.config.timeout
        )
        response.raise_for_status()
        return response.json()
    
    def create_recipe(self, name: str, description: str, steps: List[Dict]) -> Dict:
        """创建自动化配方"""
        payload = {
            "name": name,
            "description": description,
            "steps": steps
        }
        
        response = self.session.post(
            f"{self.config.base_url}/recipes",
            json=payload,
            timeout=self.config.timeout
        )
        response.raise_for_status()
        return response.json()

# 使用示例
config = GooseConfig(api_key="your-secret-key")
goose = GooseAPI(config)

# 执行代码审查任务
result = goose.execute_task("code-review", {
    "code": "def example(): pass",
    "language": "python",
    "strictness": "high"
})

print(f"审查结果: {result['feedback']}")

🎨 高级用法

流式响应处理

对于长时间运行的任务,可以使用流式响应:

def stream_task_execution(task_description):
    """处理流式任务执行"""
    with requests.post(
        f"{BASE_URL}/agent/execute-stream",
        headers=HEADERS,
        json={"task": task_description},
        stream=True
    ) as response:
        for line in response.iter_lines():
            if line:
                data = json.loads(line)
                if data.get("type") == "progress":
                    print(f"进度: {data['progress']}%")
                elif data.get("type") == "result":
                    print(f"结果: {data['result']}")

批量操作优化

async def batch_process_tasks(tasks, max_concurrent=5):
    """并发处理多个任务"""
    semaphore = asyncio.Semaphore(max_concurrent)
    
    async def process_task(task):
        async with semaphore:
            try:
                result = await goose.execute_task_async(task)
                return {"task": task, "success": True, "result": result}
            except Exception as e:
                return {"task": task, "success": False, "error": str(e)}
    
    results = await asyncio.gather(*[
        process_task(task) for task in tasks
    ])
    
    return results

📝 最佳实践

  1. 错误重试机制: 实现指数退避的重试逻辑
  2. 请求验证: 始终验证输入参数的有效性
  3. 资源清理: 及时关闭不再使用的会话和连接
  4. 监控告警: 设置关键指标的监控和告警
  5. 版本兼容: 注意API版本变化,做好向后兼容

通过本文档,您可以全面了解Goose API的功能和使用方法,快速构建基于AI的自动化应用。Goose的强大功能和灵活接口使其成为现代软件开发中不可或缺的智能助手。

【免费下载链接】goose an open source, extensible AI agent that goes beyond code suggestions - install, execute, edit, and test with any LLM 【免费下载链接】goose 项目地址: https://gitcode.com/GitHub_Trending/goose3/goose

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

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

抵扣说明:

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

余额充值