Function calling on Baidu Qianfan turns Ernie Bot from a conversational model into an execution engine. Getting it to reliably invoke your internal APIs without hallucinating parameters or choking on malformed JSON, however, requires deliberate defensive engineering.
At 365Finds, our primary stance on Qianfan integration is simple: abandon the legacy native API format whenever possible. Route all new implementations through Qianfan's OpenAI-compatible /v2 endpoints. The native BCE RPC protocol works, but its proprietary payload nesting and strict schema validation create unnecessary maintenance drag. Below is the exact architecture, schema configuration, and debugging pipeline we recommend for Ernie Bot.
Step 1: Choose Your Interface (v2 OpenAI-Compatible vs. Native SDK)
Baidu supports two invocation pathways for Ernie Bot tool calling:
- OpenAI-Compatible Endpoint (
https://qianfan.baidubce.com/v2): Standardizedtoolsarray,tool_choice,role: "tool", and stringified JSON arguments. Compatible with standard Pythonopenaipackages and agentic orchestration libraries. - Native Qianfan Python SDK (
qianfan.ChatCompletion): Uses legacyfunctionsparameter,role: "function", and Baidu Cloud Entity (BCE) AK/SK credential signatures.
Unless you have enterprise compliance rules dictating BCE request signing, 365Finds strongly advises sticking to the OpenAI-compatible v2 route.
import os
import json
from openai import OpenAI
from pydantic import BaseModel, Field
# Initialize client against Qianfan v2 endpoint
client = OpenAI(
api_key=os.environ.get("QIANFAN_API_KEY"), # Format: bce-v3/... or Qianfan bearer token
base_url="https://qianfan.baidubce.com/v2"
)
Step 2: Define Tool Schemas Defensively
Ernie Bot enforces strict JSON Schema syntax. If your schema omits top-level property types or fails to define nested objects explicitly, Qianfan will reject the payload with a 400 Bad Request before the prompt reaches the transformer.
Instead of writing raw JSON dictionaries by hand, generate your tool schemas using Pydantic. This guarantees standard-compliant JSON schema output.
class WeatherQueryArgs(BaseModel):
city: str = Field(..., description="The target city name, e.g., 'Beijing' or 'Shanghai'. Do not include province names.")
days: int = Field(default=1, ge=1, le=7, description="Number of forecast days, between 1 and 7.")
tools = [
{
"type": "function",
"function": {
"name": "get_weather_forecast",
"description": "Fetch weather forecast for a specified Chinese or international city. Do not use for historical climate data.",
"parameters": WeatherQueryArgs.model_json_schema()
}
}
]
Notice the negative constraint in the description: "Do not use for historical climate data." Ernie Bot responds sharply to boundary constraints inside parameter and tool descriptions. Providing negative triggers cuts down accidental tool invocation on irrelevant conversational turns.
Step 3: Execute the Full Two-Turn Loop
Function calling is a multi-step conversation. A common bug we see teams make is dropping the intermediate assistant tool-call message when returning tool execution results. Qianfan requires the entire context chain to reconstruct state.
def run_conversation(user_prompt: str):
messages = [
{"role": "system", "content": "You are a precise enterprise assistant. Rely on tools for factual live queries."},
{"role": "user", "content": user_prompt}
]
# First turn: Request tool call from Ernie Bot
response = client.chat.completions.create(
model="ernie-4.0-turbo-8k", # Or ernie-3.5-8k
messages=messages,
tools=tools,
tool_choice="auto",
temperature=0.1 # Keep low to stabilize parameter generation
)
choice = response.choices[0]
messages.append(choice.message)
# Check if Ernie Bot requested a function execution
if not choice.message.tool_calls:
return choice.message.content
for tool_call in choice.message.tool_calls:
call_id = tool_call.id
fn_name = tool_call.function.name
raw_args = tool_call.function.arguments
# Safe parsing and local execution
tool_result = execute_local_tool(fn_name, raw_args)
# Append tool execution result
messages.append({
"role": "tool",
"tool_call_id": call_id,
"name": fn_name,
"content": json.dumps(tool_result, ensure_ascii=False)
})
# Second turn: Let Ernie Bot synthesize final answer
final_response = client.chat.completions.create(
model="ernie-4.0-turbo-8k",
messages=messages
)
return final_response.choices[0].message.content
Step 4: Robust Debugging and Error Recovery
When function calls fail in production, the failure almost always belongs to one of three categories:
| Failure Mode | Root Cause | Debugging Remedy |
|---|---|---|
Schema Rejection (400) | Missing type: "object" or malformed parameters block. | Validate schema via Pydantic; enable HTTP debug logs to inspect raw payload. |
| JSON Decode Error | Model returns truncated strings or unescaped characters in arguments. | Wrap json.loads in a try/except; feed the error back into the message loop instead of crashing. |
| Parameter Hallucination | Ambiguous prompt or high temperature (> 0.7). | Pin temperature to 0.1-0.2; write explicit parameter boundary descriptions. |
Feeding Validation Errors Back to Ernie Bot
When Ernie Bot returns arguments that violate your business validation rules (for example, requesting an invalid city or an out-of-range date), do not raise an unhandled Python exception. Feed the validation failure back to the model as the tool result:
def execute_local_tool(name: str, raw_args: str) -> dict:
if name != "get_weather_forecast":
return {"status": "error", "message": f"Unknown tool: {name}"}
try:
data = json.loads(raw_args or "{}")
# Validate against our Pydantic model
validated_args = WeatherQueryArgs(**data)
except Exception as exc:
# Crucial: return failure details so the model can rectify its mistake
return {
"status": "validation_failed",
"error_detail": str(exc),
"hint": "Please supply a valid city string and integer days between 1 and 7."
}
# Simulate actual API call
return {
"status": "success",
"city": validated_args.city,
"temperature_celsius": 19,
"condition": "Cloudy"
}
Ernie Bot inspects validation_failed payloads and will either re-attempt the tool call with corrected parameters or politely explain the issue to the end user.
Step 5: Enabling Low-Level Protocol Logs
If Qianfan returns generic error codes like 336000 (Internal Error) or 336003 (Invalid Parameter), standard console outputs won't reveal which field failed. Turn on low-level logging:
- When using the
openaiclient:import logging logging.basicConfig(level=logging.DEBUG) logging.getLogger("httpx").setLevel(logging.DEBUG) - When using the native
qianfanSDK:import os os.environ["QIANFAN_DEBUG"] = "True"
Inspect the exact JSON string inside the outgoing request's tools or functions array. Check that every object schema specifies "type": "object" and that required array lists match real property keys.
365Finds has tested tool calling across multiple generations of Ernie Bot. While early ERNIE 3.5 releases occasionally hallucinated argument structures under high context loads, ERNIE 4.0 and ERNIE 4.5 handle constrained JSON extraction reliably once your schemas are cleanly defined.