AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Configuring Qwen Tool and Function Calling on Alibaba Cloud Bailian with the OpenAI Python SDK

傅星達 · 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

Software engineers building production-grade autonomous agents and backend API orchestrators frequently run into an operational dilemma: migrating from OpenAI models to Alibaba Cloud’s Tongyi Qianwen (Qwen) family usually risks code rewrite friction. Rewriting mature agent orchestration logic to proprietary client libraries incurs technical debt, testing overhead, and vendor lock-in.

The solution is Alibaba Cloud Bailian’s native OpenAI-compatible interface (/compatible-mode/v1). By pointing the standard openai Python SDK to Bailian’s endpoint, technical teams can invoke Tongyi Qianwen models—such as qwen-plus, qwen-max, and qwen-turbo—with native JSON Schema tool definitions, multi-turn message loops, and parallel tool calling, without altering existing OpenAI client infrastructure.

At 365Finds, our engineering assessment is unequivocal: do not rewrite your orchestration pipeline to vendor-specific SDK wrappers. Standardizing on the OpenAI-compatible protocol while using dedicated workspace endpoints provides the highest resilience, minimizes migration friction, and preserves architectural flexibility across multi-model deployments.


Architecture Overview & Endpoint Configuration

Alibaba Cloud Model Studio (Bailian) exposes an OpenAI-compatible REST interface that mirrors /v1/chat/completions. To establish connectivity, engineers need two configuration items:

  1. A valid Model Studio API key (DASHSCOPE_API_KEY).
  2. The appropriate region-specific base URL.

Endpoint Selection: Dedicated vs. Shared

Bailian offers two endpoint types:

Client Initialization

Install the official OpenAI Python SDK (version 1.40.0 or higher recommended):

pip install --upgrade "openai>=1.40.0" pydantic

Initialize the client using standard environment variables:

import os
from openai import OpenAI

# 365Finds recommends workspace-dedicated endpoints for production isolation
WORKSPACE_ID = os.getenv("BAILIAN_WORKSPACE_ID", "default")
DASHSCOPE_API_KEY = os.getenv("DASHSCOPE_API_KEY")

base_url = (
    f"https://{WORKSPACE_ID}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
    if WORKSPACE_ID != "default"
    else "https://dashscope.aliyuncs.com/compatible-mode/v1"
)

client = OpenAI(
    api_key=DASHSCOPE_API_KEY,
    base_url=base_url,
    timeout=30.0,
    max_retries=3,
)

Defining JSON Schema Tool Specifications

Tongyi Qianwen adheres strictly to the OpenAI tools schema format. Each tool is wrapped as an object of type: "function" containing the function's name, description, and parameter JSON Schema.

To ensure high parameter extraction accuracy:

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Retrieve current atmospheric weather data and forecasts for a specified geographic location.",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string",
                        "description": "City and region name, e.g., 'San Francisco, CA' or 'Hangzhou, China'",
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Unit of temperature measurement. Defaults to 'celsius'.",
                    },
                },
                "required": ["city"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "query_database_records",
            "description": "Query internal enterprise transactional database for customer order summaries.",
            "parameters": {
                "type": "object",
                "properties": {
                    "customer_id": {
                        "type": "string",
                        "description": "The unique alphanumeric ID of the customer account, e.g., 'CUST-8802'.",
                    },
                    "status_filter": {
                        "type": "string",
                        "enum": ["all", "pending", "shipped", "delivered"],
                        "description": "Filter orders by shipping or fulfillment status.",
                    },
                },
                "required": ["customer_id"],
            },
        },
    },
]

The Complete Multi-Turn Function Calling Loop

Executing function calling with Tongyi Qianwen requires a deterministic multi-turn sequence:

  1. Model Invitation: Send user input and the tools array with tool_choice="auto".
  2. Call Inspection: Check if message.tool_calls exists in the model's response.
  3. History Preservation: Append the assistant's message containing tool_calls directly to the messages array.
  4. Execution & Response Mapping: Execute local code and append each result as a message with role: "tool", referencing the exact tool_call_id.
  5. Final Synthesis: Re-invoke the model with the updated conversation history to obtain the final answer.
import json

# Local mock functions
def get_weather(city: str, unit: str = "celsius") -> dict:
    return {"city": city, "temperature": 21.5, "condition": "Partly Cloudy", "unit": unit}

def query_database_records(customer_id: str, status_filter: str = "all") -> dict:
    return {
        "customer_id": customer_id,
        "record_count": 2,
        "orders": [
            {"order_id": "ORD-101", "amount": 149.50, "status": "shipped"},
            {"order_id": "ORD-102", "amount": 89.00, "status": "pending"},
        ],
    }

tool_registry = {
    "get_weather": get_weather,
    "query_database_records": query_database_records,
}

messages = [
    {"role": "system", "content": "You are a professional enterprise operations assistant."},
    {"role": "user", "content": "Check pending orders for customer CUST-8802 and check the weather in Hangzhou right now."},
]

# Step 1: Initial call to Tongyi Qianwen
response = client.chat.completions.create(
    model="qwen-plus",
    messages=messages,
    tools=tools,
    tool_choice="auto",
    temperature=0.2,
)

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

# Step 2: Process tool calls if triggered
if assistant_message.tool_calls:
    for tool_call in assistant_message.tool_calls:
        fn_name = tool_call.function.name
        fn_args = json.loads(tool_call.function.arguments)
        
        target_fn = tool_registry.get(fn_name)
        if target_fn:
            output = target_fn(**fn_args)
        else:
            output = {"error": f"Tool '{fn_name}' not recognized."}

        # Step 3: Append tool execution result
        messages.append({
            "role": "tool",
            "tool_call_id": tool_call.id,
            "name": fn_name,
            "content": json.dumps(output),
        })

    # Step 4: Final generation synthesizing tool outputs
    final_response = client.chat.completions.create(
        model="qwen-plus",
        messages=messages,
    )
    print("Final Assistant Output:\n", final_response.choices[0].message.content)
else:
    print("Direct Assistant Output:\n", assistant_message.content)

Robust Parallel Tool Calling & Concurrent Fault Handling

When a prompt references multiple discrete queries—such as fetching weather across multiple branches or pulling disparate records—Tongyi Qianwen emits multiple calls inside the assistant_message.tool_calls list in a single turn.

In high-throughput microservices, running these tool calls serially induces unacceptable latency. Engineers should execute them concurrently using thread pools or asynchronous tasks.

Critical Engineering Rule: Strict tool_call_id Matching

[!IMPORTANT] The OpenAI API protocol requires that every tool_call returned by the model has a matching message with role: "tool" and identical tool_call_id in subsequent turns. If one tool call fails, times out, or throws an unhandled exception, you must not omit its result from the messages array. Omitting a tool response breaks the state machine and causes Alibaba Cloud Bailian to reject the next request with an HTTP 400 validation error.

Here is a production-grade concurrent execution pattern:

import json
import concurrent.futures
from typing import Dict, Any

def execute_single_tool(tool_call) -> Dict[str, Any]:
    call_id = tool_call.id
    fn_name = tool_call.function.name
    
    try:
        fn_args = json.loads(tool_call.function.arguments)
    except json.JSONDecodeError as err:
        return {
            "tool_call_id": call_id,
            "name": fn_name,
            "content": json.dumps({"error": f"Invalid JSON arguments: {str(err)}"}),
        }

    handler = tool_registry.get(fn_name)
    if not handler:
        return {
            "tool_call_id": call_id,
            "name": fn_name,
            "content": json.dumps({"error": f"Function '{fn_name}' not implemented"}),
        }

    try:
        # Enforce execution timeout if necessary
        result = handler(**fn_args)
        content_str = json.dumps(result)
    except Exception as exc:
        content_str = json.dumps({"error": f"Execution failure: {str(exc)}"})

    return {
        "tool_call_id": call_id,
        "name": fn_name,
        "content": content_str,
    }

def handle_parallel_tool_calls(client: OpenAI, model: str, messages: list, tools: list):
    response = client.chat.completions.create(
        model=model,
        messages=messages,
        tools=tools,
        tool_choice="auto",
    )
    
    msg = response.choices[0].message
    messages.append(msg)
    
    if not msg.tool_calls:
        return msg.content

    # Execute tools concurrently across worker threads
    tool_results = []
    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
        futures = [executor.submit(execute_single_tool, tc) for tc in msg.tool_calls]
        for future in concurrent.futures.as_completed(futures):
            tool_results.append(future.result())

    # Maintain deterministic tool response injection
    for item in tool_results:
        messages.append({
            "role": "tool",
            "tool_call_id": item["tool_call_id"],
            "name": item["name"],
            "content": item["content"],
        })

    # Second pass to complete response
    final_step = client.chat.completions.create(
        model=model,
        messages=messages,
    )
    return final_step.choices[0].message.content

365Finds Model Selection & Strategy Matrix

Choosing the right Qwen tier for tool-calling pipelines determines operational latency and billing cost.

Model TierSchema AdherenceLatencyRecommended Use Cases365Finds Judgment
qwen-plusVery HighFast (200–400ms TTFT)General tool calls; single-turn API triggers; SQL routingPrimary Recommendation: Best balance of speed, cost, and structural adherence.
qwen-maxExceptionalModerate (400–800ms TTFT)Multi-hop reasoning; deeply nested JSON structures; ambiguous user intentsReserve for complex orchestration where parameter ambiguity is high.
qwen-turboModerateUltra-Fast (<150ms TTFT)High-volume simple tools; classification and keyword lookupCost-effective, but prone to argument dropping on complex schemas.

Handling Reasoning and "Thinking" Modes

When using newer reasoning-enabled models or experimental builds in Bailian, enabling internal chain-of-thought (enable_thinking=True) can cause conflicts if tool_choice="required" is passed. For strict tool calling, 365Finds advises explicitly disabling thinking mode or using standard tool_choice="auto":

# Disabling thinking mode for deterministic, fast tool-calling pipelines
completion = client.chat.completions.create(
    model="qwen-plus",
    messages=messages,
    tools=tools,
    extra_body={
        "enable_thinking": False
    }
)

Context Window Hygiene & Production Takeaways

  1. Prune Intermediate Tool Payloads: Internal enterprise APIs often return megabytes of raw JSON logs. Feeding raw data back into role: "tool" causes rapid context window inflation and increases token billing. Summarize or extract only relevant database keys before populating content.
  2. Defensive Schema Parsing: Always wrap json.loads(tool_call.function.arguments) in a try...except block. Even high-grade LLMs can occasionally escape strings improperly under high token pressure.
  3. Preserve the Assistant Message: Never discard the intermediate message where tool_calls were declared. The conversational context requires the sequence [user, assistant(tool_calls), tool(result), assistant(final)].

By adopting the OpenAI-compatible endpoint on Alibaba Cloud Bailian, engineering teams achieve zero-cost migration, robust parallel execution, and access to Tongyi Qianwen's flagship open-weights intelligence without sacrificing existing code quality.


References