跳转到内容

Gemini函数调用 ​

借助函数调用,您可以将模型连接到外部工具和 API。 该模型不会生成文本回答,而是确定何时调用特定函数,并提供执行实际操作所需的参数。这样,模型就可以充当自然语言与现实世界操作和数据之间的桥梁。函数调用有 3 种主要用例:

  • 扩充知识:访问数据库、API 和知识库等外部来源中的信息。
    
  • 扩展功能:使用外部工具执行计算,并扩展模型的限制,例如使用计算器或创建图表。
    
  • 执行操作:使用 API 与外部系统互动,例如安排预约、创建账单、发送电子邮件或控制智能家居设备。
    

如下示例:(获取天气信息)

js
curl "https://mishu.one/google/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -X POST \
  -d '{
    "contents": [
      {
        "role": "user",
        "parts": [
          {
            "text": "What'\''s the temperature in London?"
          }
        ]
      }
    ],
    "tools": [
      {
        "functionDeclarations": [
          {
            "name": "get_current_temperature",
            "description": "Gets the current temperature for a given location.",
            "parameters": {
              "type": "object",
              "properties": {
                "location": {
                  "type": "string",
                  "description": "The city name, e.g. San Francisco"
                }
              },
              "required": ["location"]
            }
          }
        ]
      }
    ]
  }'

返回:

js
{
    "candidates": [
        {
            "content": {
                "parts": [
                    {
                        "functionCall": {
                            "name": "get_current_temperature",
                            "args": {
                                "location": "London"
                            }
                        }
                    }
                ],
                "role": "model"
            },
            "finishReason": "STOP",
            "avgLogprobs": 0.0000042350231004612785
        }
    ],
    "usageMetadata": {
        "promptTokenCount": 36,
        "candidatesTokenCount": 7,
        "totalTokenCount": 43,
        "promptTokensDetails": [
            {
                "modality": "TEXT",
                "tokenCount": 36
            }
        ],
        "candidatesTokensDetails": [
            {
                "modality": "TEXT",
                "tokenCount": 7
            }
        ]
    },
    "modelVersion": "gemini-2.0-flash",
    "responseId": "l4JRaMDQNKiUsbQPmK3KkQI"
}

Mishu · API 开发文档