Просмотр исходного кода

fix Display problem in chapter7 and add 7.4.5 in English version

jjyaoao 4 месяцев назад
Родитель
Сommit
d0a8d3c5f9

+ 68 - 0
docs/chapter7/Chapter7-Building-Your-Agent-Framework.md

@@ -1279,6 +1279,74 @@ As shown in Table 7.2, through this framework refactoring, we not only maintaine
   <img src="https://raw.githubusercontent.com/datawhalechina/Hello-Agents/main/docs/images/7-figures/table-02.png" alt="" width="90%"/>
 </div>
 
+### 7.4.5 FunctionCallAgent
+
+FunctionCallAgent is an Agent introduced in hello-agents after version 0.2.8, based on OpenAI's native function calling mechanism. It demonstrates how to build an Agent using OpenAI's function calling capabilities.
+It supports the following features:
+
+- _build_tool_schemas: Constructs OpenAI function calling schema through tool descriptions
+- _extract_message_content: Extracts text content from OpenAI responses
+- _parse_function_call_arguments: Parses JSON string parameters returned by the model
+- _convert_parameter_types: Converts parameter types
+
+These features enable native OpenAI Function Calling capabilities, providing stronger robustness compared to prompt-constrained approaches.
+
+```python
+def _invoke_with_tools(self, messages: list[dict[str, Any]], tools: list[dict[str, Any]], tool_choice: Union[str, dict], **kwargs):
+        """Invoke underlying OpenAI client to execute function calls"""
+        client = getattr(self.llm, "_client", None)
+        if client is None:
+            raise RuntimeError("HelloAgentsLLM client not properly initialized, cannot execute function calls.")
+
+        client_kwargs = dict(kwargs)
+        client_kwargs.setdefault("temperature", self.llm.temperature)
+        if self.llm.max_tokens is not None:
+            client_kwargs.setdefault("max_tokens", self.llm.max_tokens)
+
+        return client.chat.completions.create(
+            model=self.llm.model,
+            messages=messages,
+            tools=tools,
+            tool_choice=tool_choice,
+            **client_kwargs,
+        )
+
+# Internal logic wraps OpenAI native function calling
+# OpenAI native function calling example
+from openai import OpenAI
+client = OpenAI()
+
+tools = [
+  {
+    "type": "function",
+    "function": {
+      "name": "get_current_weather",
+      "description": "Get the current weather in a given location",
+      "parameters": {
+        "type": "object",
+        "properties": {
+          "location": {
+            "type": "string",
+            "description": "The city and state, e.g. San Francisco, CA",
+          },
+          "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
+        },
+        "required": ["location"],
+      },
+    }
+  }
+]
+messages = [{"role": "user", "content": "What's the weather like in Boston today?"}]
+completion = client.chat.completions.create(
+  model="gpt-5",
+  messages=messages,
+  tools=tools,
+  tool_choice="auto"
+)
+
+print(completion)
+```
+
 ## 7.5 Tool System
 
 The content of this section will deeply explore the design and implementation of the tool system based on the Agent infrastructure built earlier. We will start from infrastructure construction and gradually delve into custom development design. The learning objectives of this section revolve around the following three core aspects:

+ 5 - 4
docs/chapter7/第七章 构建你的Agent框架.md

@@ -1283,10 +1283,11 @@ print(f"数学专用Agent结果: {math_result}")
 
 FunctionCallAgent是hello-agents在0.2.8之后引入的Agent,它基于OpenAI原生函数调用机制的Agent,展示了如何使用OpenAI的函数调用机制来构建Agent。
 它支持以下功能:
-_build_tool_schemas:通过工具的description构建OpenAI的function calling schema
-_extract_message_content:从OpenAI的响应中提取文本
-_parse_function_call_arguments:解析模型返回的JSON字符串参数
-_convert_parameter_types:转换参数类型
+
+- _build_tool_schemas:通过工具的description构建OpenAI的function calling schema
+- _extract_message_content:从OpenAI的响应中提取文本
+- _parse_function_call_arguments:解析模型返回的JSON字符串参数
+- _convert_parameter_types:转换参数类型
 
 这些功能可以使其具备原生的OpenAI Function Calling的能力,对比使用prompt约束的方式,具备更强的鲁棒性。
 ```python