AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Implementing Function Calling with Baichuan API: A Multi-Step Agent Guide

松下祥子 · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

Enterprise software engineers building autonomous AI agents frequently face a hard wall with vanilla text completions: large language models cannot directly query an SQL cluster, check inventory in an ERP system, or fetch real-time exchange rates. Without direct external integration, models hallucinate outdated or fictional business data.

The solution is function calling. Baichuan provides full native compatibility with the standard OpenAI Chat Completions protocol at https://api.baichuan-ai.com/v1. Developers can reuse standard client libraries—such as the official OpenAI Python SDK—to orchestrate multi-step, tool-augmented agent workflows with zero proprietary wrapper overhead.

At 365Finds, our operational verdict is clear: if your application stack processes enterprise queries requiring high-precision Chinese business reasoning alongside structured data access, Baichuan (particularly Baichuan4 and Baichuan4-Turbo) is an exceptionally reliable drop-in backend. Its schema adherence rivals top global models while offering significant cost efficiency and native bilingual comprehension.


1. Protocol Architecture: How Baichuan Implements Tool Calling

Baichuan’s tool execution follows a four-phase closed-loop architecture:

  1. Tool Definition: The client application registers callable tools via the tools array using standard JSON Schema definitions, specifying argument types, descriptions, and required fields.
  2. Intent & Argument Generation: Baichuan evaluates the conversation context and prompt. If external data or action is required, the model halts text generation with finish_reason: "tool_calls" and returns one or more structured tool invocation payloads under choices[0].message.tool_calls.
  3. Local Execution: The client backend intercepts the call, parses the JSON-encoded arguments, maps the call to a local business function, executes the query (e.g., against PostgreSQL or a microservice), and serializes the result.
  4. Context Injection & Resolution: The client appends both the assistant's tool-call request and a corresponding message with role: "tool" (containing the execution result and the matching tool_call_id) back to the conversation thread, allowing Baichuan to synthesize a factual final response.
+-------------------------------------------------------------+
|                     Client Agent Loop                       |
|                                                             |
|  1. Send User Prompt + Tool JSON Schemas                   |
|  -------------------------------------------------------->  |
|                                                             |   Baichuan API
|  2. Returns message with tool_calls + finish_reason        |   (https://api.baichuan-ai.com/v1)
|  <--------------------------------------------------------  |
|                                                             |
|  3. Local Dispatch: Execute DB query / REST API             |
|                                                             |
|  4. Post role="tool" payload with tool_call_id              |
|  -------------------------------------------------------->  |
|                                                             |
|  5. Final synthesis (or next tool step)                     |
|  <--------------------------------------------------------  |
+-------------------------------------------------------------+

2. Setting Up the OpenAI-Compatible Client

Because Baichuan models expose an OpenAI-compliant REST structure, initialization requires only pointing the base URL to Baichuan’s developer gateway and supplying your Baichuan API key.

pip install openai pydantic
import os
from openai import OpenAI

# Initialize standard OpenAI client redirected to Baichuan API
client = OpenAI(
    api_key=os.environ.get("BAICHUAN_API_KEY", "your-baichuan-api-key"),
    base_url="https://api.baichuan-ai.com/v1",
)

Supported enterprise models include Baichuan4 for complex multi-turn logic, Baichuan4-Turbo for balanced speed and cost, and Baichuan4-Air for lightweight classification or extraction tasks.


3. Defining Structured Tool Schemas

To prevent schema mismatch and runtime hallucination, tool parameter definitions must specify accurate types, concise descriptions, and explicit required properties.

Below is an enterprise CRM scenario involving two dependent tools:

  1. get_customer_id: Resolves a company name into a unique internal customer ID.
  2. get_unpaid_invoices: Queries billing records for a specific customer ID and fiscal year.
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_customer_id",
            "description": "Retrieve the unique customer ID corresponding to a company or enterprise name.",
            "parameters": {
                "type": "object",
                "properties": {
                    "company_name": {
                        "type": "string",
                        "description": "Full or partial legal name of the enterprise.",
                    }
                },
                "required": ["company_name"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "get_unpaid_invoices",
            "description": "Query all pending and unpaid billing invoices for a specific customer ID.",
            "parameters": {
                "type": "object",
                "properties": {
                    "customer_id": {
                        "type": "string",
                        "description": "The unique internal customer ID (e.g., CUST-10492).",
                    },
                    "fiscal_year": {
                        "type": "integer",
                        "description": "The 4-digit fiscal year to filter invoices.",
                    },
                },
                "required": ["customer_id"],
            },
        },
    },
]

4. End-to-End Multi-Step Agent Execution Loop

A single user question such as "Check if Nexus Retail has any outstanding invoices for 2024 and summarize the total overdue balance" requires a multi-step chain: the model must first retrieve the customer ID, wait for the result, use that output to trigger the invoice query, and finally synthesize the natural-language answer.

Here is the complete production-ready orchestration script:

import json
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ.get("BAICHUAN_API_KEY"),
    base_url="https://api.baichuan-ai.com/v1",
)

# Simulated backend enterprise systems
MOCK_CUSTOMER_DB = {"Nexus Retail": "CUST-98214", "Acme Industrial": "CUST-44102"}

MOCK_INVOICE_DB = {
    "CUST-98214": [
        {
            "invoice_id": "INV-2024-001",
            "year": 2024,
            "amount_usd": 14250.00,
            "status": "unpaid",
            "due_date": "2024-08-15",
        },
        {
            "invoice_id": "INV-2024-004",
            "year": 2024,
            "amount_usd": 8500.50,
            "status": "unpaid",
            "due_date": "2024-10-01",
        },
        {
            "invoice_id": "INV-2023-089",
            "year": 2023,
            "amount_usd": 5000.00,
            "status": "paid",
            "due_date": "2023-11-20",
        },
    ]
}


def get_customer_id(company_name: str) -> str:
    """Look up customer ID from company directory."""
    for name, cid in MOCK_CUSTOMER_DB.items():
        if company_name.lower() in name.lower():
            return json.dumps({"status": "success", "customer_id": cid, "matched_name": name})
    return json.dumps({"status": "error", "message": f"Customer '{company_name}' not found."})


def get_unpaid_invoices(customer_id: str, fiscal_year: int = 2024) -> str:
    """Fetch unpaid invoices filtered by fiscal year."""
    records = MOCK_INVOICE_DB.get(customer_id, [])
    unpaid = [r for r in records if r["status"] == "unpaid" and r["year"] == fiscal_year]
    total_due = sum(r["amount_usd"] for r in unpaid)
    return json.dumps({
        "status": "success",
        "customer_id": customer_id,
        "fiscal_year": fiscal_year,
        "unpaid_invoices": unpaid,
        "total_due_usd": total_due,
    })


TOOL_DISPATCHER = {
    "get_customer_id": get_customer_id,
    "get_unpaid_invoices": get_unpaid_invoices,
}


def run_baichuan_agent(user_query: str, model: str = "Baichuan4-Turbo", max_steps: int = 6):
    messages = [
        {
            "role": "system",
            "content": (
                "You are an enterprise financial operations agent. When resolving queries, "
                "always query external tools step-by-step rather than guessing identifiers or amounts. "
                "Provide accurate, concise summaries based solely on tool execution results."
            ),
        },
        {"role": "user", "content": user_query},
    ]

    for step in range(max_steps):
        print(f"\n--- [Step {step + 1}] Invoking Baichuan ({model}) ---")
        response = client.chat.completions.create(
            model=model,
            messages=messages,
            tools=tools,
            tool_choice="auto",
            temperature=0.2,
        )

        choice = response.choices[0]
        message = choice.message
        messages.append(message)

        # Termination condition: model produces normal text response
        if choice.finish_reason == "stop" or not message.tool_calls:
            print("--- [Agent Finished] Final Answer Generated ---")
            return message.content

        # Model requests one or more tool calls
        if choice.finish_reason == "tool_calls" and message.tool_calls:
            for tool_call in message.tool_calls:
                call_id = tool_call.id
                func_name = tool_call.function.name
                func_args_raw = tool_call.function.arguments

                print(f"Tool Requested: {func_name} | Call ID: {call_id}")
                print(f"Arguments: {func_args_raw}")

                executor = TOOL_DISPATCHER.get(func_name)
                if not executor:
                    result_payload = json.dumps({"error": f"Tool '{func_name}' is not registered."})
                else:
                    try:
                        args = json.loads(func_args_raw)
                        result_payload = executor(**args)
                    except Exception as e:
                        result_payload = json.dumps({"error": f"Execution failed: {str(e)}"})

                # Return result to model via role="tool"
                messages.append({
                    "role": "tool",
                    "tool_call_id": call_id,
                    "name": func_name,
                    "content": result_payload,
                })

    raise TimeoutError(f"Agent exceeded maximum tool invocation limit of {max_steps} steps.")


if __name__ == "__main__":
    query = "Check if Nexus Retail has any unpaid invoices for 2024 and calculate total balance."
    final_response = run_baichuan_agent(query)
    print("\nResult:")
    print(final_response)

5. Engineering Considerations & 365Finds Recommendations

When deploying Baichuan function-calling agents to high-throughput production environments, keep these engineering practices in mind:

DimensionRisk / Challenge365Finds Recommended Practice
Input ValidationHallucinated argument types or missing keysUse Pydantic schemas to validate arguments before invocation; return structured error JSON on validation failure.
Context OverheadAccumulating multi-turn raw JSON exhausts token windowsPrune redundant tool outputs or strip verbose metadata before appending role: "tool" payloads.
Infinite LoopsModel repeatedly calls failed toolsImplement a hard step counter (max_steps=5) and inject recovery instructions when exceptions occur.
Model SelectionLatency vs. complex planning capabilityUse Baichuan4-Turbo for standard multi-step pipelines; reserve flag-bearer Baichuan4 for deep schema graphs.
Parallel ExecutionSequential tool calls create latency bottlenecksIterate through all items in message.tool_calls and run non-dependent calls in parallel using thread pools.

Handling Parallel Tool Calling

Baichuan supports returning multiple entries in message.tool_calls in a single response turn when multiple actions can be executed concurrently. Ensure your execution loop iterates through every item in message.tool_calls and appends a corresponding role: "tool" entry for each tool_call_id. Failing to return an answer for every emitted call ID will trigger protocol validation errors on subsequent requests.

Graceful Error Feedback

Never raise an uncaught exception in the local runner. If a database query fails or a network timeout happens, format the error into a clean JSON string (e.g., {"status": "error", "code": 504, "detail": "Gateway Timeout"}) and return it as the tool message. Baichuan models are trained to parse these failure signals, allowing the agent to either formulate an alternative query plan or explain the infrastructure limitation politely to the user.


References