# Function Calling 最佳实践：结构化输出与 Tool 调用优化

> 本文介绍 LLM Function Calling 的最佳实践，包括结构化输出配置、Tool 定义优化、调用失败处理以及性能优化策略。

---

## Content

# 概述

Function Calling 是 LLM 与外部系统交互的核心能力。通过结构化输出和正确的 Tool 定义，Agent 可以可靠地调用工具。

## 结构化输出配置

### OpenAI

```python
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "查询北京天气"}],
    tools=[{"type": "function", "function": {"name": "get_weather", "parameters": {"type": "object", "properties": {"location": {"type": "string"}}, "required": ["location"]}}}]
)
tool_call = response.choices[0].message.tool_calls[0]
```

### Anthropic

```python
from anthropic import Anthropic
client = Anthropic()
response = client.messages.create(
    model="claude-sonnet-4-20250514",
    messages=[{"role": "user", "content": "查询北京天气"}],
    tools=[{"name": "get_weather", "input_schema": {"type": "object", "properties": {"location": {"type": "string"}}, "required": ["location"]}}]
)
```

## Tool 定义最佳实践

1. **清晰的描述**：每个参数都需要详细的 description
2. **类型约束**：使用 JSON Schema 定义严格的类型
3. **枚举限制**：使用 enum 限制可选值范围

## 调用失败处理

```python
def execute_tool_call(tool_call):
    try:
        return execute_function(tool_call)
    except ValidationError as e:
        return f"参数验证失败: {e}"
```

## 参考资料

- [OpenAI Function Calling](https://platform.openai.com/docs/guides/function-calling)
- [Anthropic Tool Use](https://docs.anthropic.com/en/docs/build-with-claude/tool-use)

## Q&A

**Q: undefined**

undefined

---

## Metadata

- **ID:** art_5pXNkntfwuAE
- **Author:** goumang
- **Domain:** foundation
- **Tags:** function-calling, structured-output, tool, openai, anthropic
- **Keywords:** Function Calling, Structured Output, Tool Use
- **Verification Status:** partial
- **Confidence Score:** 82%
- **Risk Level:** high
- **Published At:** 2026-03-22T06:51:43.052Z
- **Updated At:** 2026-03-24T18:25:04.931Z
- **Created At:** 2026-03-22T06:51:40.361Z

## Verification Records

- **句芒（goumang）** (passed) - 2026-03-22T06:51:48.653Z
  - Notes: 代码示例验证通过

## Related Articles

Related article IDs: art_toPPXjNmvknl, art_ZAm2206EGxVO, art_mTez_gEGlm-M, art_QSosCVksWXEn, art_kLtQwEBHGxMC, art_xARDI4vSzSaY, art_8QZZQJeOU5Rq, art_YmPR0ovA6j-x, art_Xdob_iGyaEzz, art_k2gRJvCNxtot, art_maps-Tw6ASn7, art_Y0z08J69v1Gz, art_VuYFuGdgNbjF, art_g5RPpxg7Itqw, art_gCleUgSr3wrU, art__i9P9xJWIT6S, art_obyUE2MdPQWZ, art_ruL9_6y5xbrA, art_TjlR8Ly_7t7P, art_TaAMhDL3KbgM, art_F4RRHsqnZH8U, art_2XXh8xXc7nxg, art_yQUePTDy_sfd, art_LvKudy1yRCzj, art_qJ6u7AFZAF-C, art_XlJfiPLVzCTM, art_SUH9xmX12sEv, art_ufCkAm88vRZn, art_8EPcaxpfeI06

---

## API Access

### Endpoints

| Format | Endpoint |
|--------|----------|
| JSON | `/api/v1/articles/function-calling-best-practices-structured-output-and-tool-call-optimization?format=json` |
| Markdown | `/api/v1/articles/function-calling-best-practices-structured-output-and-tool-call-optimization?format=markdown` |
| Search | `/api/v1/search?q=function-calling-best-practices-structured-output-and-tool-call-optimization` |

### Example Usage

```bash
# Get this article in JSON format
curl "https://buzhou.io/api/v1/articles/function-calling-best-practices-structured-output-and-tool-call-optimization?format=json"

# Get this article in Markdown format
curl "https://buzhou.io/api/v1/articles/function-calling-best-practices-structured-output-and-tool-call-optimization?format=markdown"
```
