Make a Qwen request through the official DashScope Python SDK. Load the workspace URL and credential from the environment, then inspect a normal response and a deliberate model error.
What you'll build
You will create a compact script that sends a safe text request, prints the answer and usage, and exposes an API failure without an automatic retry loop. It establishes the relationship between workspace host, credential, model and response parser before you add application features.
The official Qwen quickstart recommends the DashScope Python SDK and demonstrates qwen3.8-max through MultiModalConversation. Official documentation.
The tutorial keeps the native DashScope HTTP base URL in configuration because the correct host comes from your workspace access setup. It does not invent an account identifier or assume that a generic endpoint copied from an older tutorial is the right path for every account.
Prerequisites
Complete the Alibaba API-key guide and configure DASHSCOPE_API_KEY plus DASHSCOPE_HTTP_BASE_URL for the Python process. Copy the native DashScope HTTP URL for the intended workspace; it ends in /api/v1, unlike the compatible-mode URL used by the key-page verification example.
Inspect the selected model’s access and the account’s spending controls before running. If the experiment is free-only, verify the applicable quota and supported stop setting. A successful request should be an intentional account action, not a test that silently changes the planned billing boundary.
Use a dedicated Python environment and record its interpreter and installed SDK version. The editor, terminal and service runner can choose different interpreters, so a successful package installation in one place does not prove the script can import it elsewhere.
Install SDK
python -m pip install --upgrade dashscope
Save the full script as first_alibaba.py. Configure environment values through your normal protected launch method, then run the command from the interpreter used for installation. Keep the key out of the source and do not print a complete environment listing while troubleshooting.
python first_alibaba.py
This command makes a real API request when valid account configuration is supplied. Run the small fixture and inspect the response before repeating it. The sample output printed in this tutorial is explicitly schematic rather than a claim that your account has executed the script.
Full script
import os
import sys
import json
from http import HTTPStatus
import dashscope
from dashscope import MultiModalConversation
from requests.exceptions import Timeout
model = os.environ.get("DASHSCOPE_MODEL", "qwen3.8-max")
if "--bad-model" in sys.argv:
model = "ai-api-hub-invalid-model"
# Copy the native DashScope HTTP Base URL for your actual workspace.
# It uses /api/v1, not the OpenAI-compatible /compatible-mode/v1 path.
dashscope.base_http_api_url = os.environ["DASHSCOPE_HTTP_BASE_URL"].rstrip("/")
try:
result = MultiModalConversation.call(
api_key=os.environ["DASHSCOPE_API_KEY"],
model=model,
messages=[{"role":"user","content":[{"text":"Explain why an extracted field should retain its source in one sentence."}]}],
max_tokens=512,
stream=False,
request_timeout=60,
)
except Timeout:
raise SystemExit("Request timed out; inspect the task before resubmitting")
if result.status_code != HTTPStatus.OK:
print(f"HTTP {result.status_code}")
print(json.dumps({"code":result.code,"message":result.message,"request_id":result.request_id}, ensure_ascii=False))
raise SystemExit(1)
choice = result.output.choices[0]
print("".join(part.get("text", "") for part in choice.message.content))
print("finish_reason:", choice.finish_reason)
print(json.dumps(result.usage, ensure_ascii=False))
The native request_timeout setting controls client waiting. This script does not add an application retry loop; the SDK transport may recover a dropped pooled connection internally. Official documentation.
Inspect the status on the returned DashScope object before reading its output. A rejected request is represented through native code and message fields rather than the OpenAI client exception used in the key-page example. Keep account and invalid-request conditions outside a generic retry loop.
The model can be changed through DASHSCOPE_MODEL. When selecting another candidate, inspect its request settings and workspace availability. An environment override makes configuration convenient; it does not validate every model and parameter combination automatically.
Expected output
The following is schematic output and was not captured from an inference call. Your authorized run establishes its own answer, completion reason and usage.
Retaining the source lets a reader verify the extracted field and investigate discrepancies.
finish_reason: stop
{"input_tokens":14,"output_tokens":18,"characters":0}
Check the sentence against the task and inspect whether the completion finished as expected. Save safe usage metadata with the fixture. If the answer is empty, incomplete or structurally invalid, retain that observation instead of editing the sample transcript to look successful.
For a later extraction workflow, replace the small prompt with a safe document and explicit field rules. Include a field that is absent from the source. The application should distinguish absence from an invented value before the result is passed downstream.
One deliberate error and its fix
python first_alibaba.py --bad-model
The branch sends ai-api-hub-invalid-model instead of the normal model identifier. Keep the credential configured so the request reaches model validation. The script exposes the returned rejection and stops; restore the ordinary command to use the supported model again.
The following error-field excerpt was captured on 2026-09-12 15:53 UTC from an authorized HTTP request to the same provider interface. It used harmless connection-validation input and small output settings. This records the provider’s rejection; it does not claim that the Python SDK example itself was executed.
These are normalized captured fields with the message preserved verbatim. They are not a reconstructed full provider response envelope. Empty fields and request identifiers are omitted.
{
"http_status": 400,
"code": "InvalidParameter",
"message": "Model not exist."
}
Fix the deliberate error by restoring a current accessible model identifier. Do not resend the invalid identifier in a retry loop. If the ordinary request also fails, inspect that response independently because permission, funding and request validation can fail at different stages. Official error reference.
Keep the missing-key startup check as an additional local configuration guard. It tests whether the process can read its environment; it does not establish that the provider accepted the key or evaluated the requested model.
What this request costs
Estimate your API costs
Your text and estimates stay in this browser. No API requests are sent to model providers.
Loading verified model records…
Transfer actual returned usage into the Model Studio cost calculator and select the applicable model and price condition. Do not treat the schematic usage in this article as a measurement.
For a larger job, include every inference stage and any associated service outside the token estimate. If the workflow moves to batch, inspect its separate billing and offer scope. Keep the workload description with the estimate so another developer can reproduce its assumptions.
Next steps
Retain the passing baseline, then add one required feature at a time. For structured output, validate field meaning as well as syntax. For media, inspect the endpoint’s accepted representation. For tools, keep the model proposal separate from the application’s authorized execution step.
Read Model Studio error handling, account traffic planning and version selection before deploying an unattended worker.
Record the workspace owner, exact model, native DashScope interface, safe fixture, accepted result and actual usage from your run. Include the secret-rotation and stop procedure without the credential value. This turns a first call into a baseline that remains useful during maintenance.
Last verified · Source ↗
Frequently asked questions
Why is the base URL an environment value?
Which credential variable is read?
Was the shown response observed?
What does the wrong-model branch test?
Can any model override use the same settings?
What should I preserve after a successful first call?
Sources
- First Qwen API call ↗
- Recommended models ↗
- Model inference pricing ↗
- API keys and permissions ↗
- Rate limits ↗
- Error codes ↗
- New-user free quota ↗
- Model usage ↗
- Context cache ↗
- Batch API ↗
- Billing and cost management ↗
- Dynamic rate limiting ↗
- Qwen Coder ↗
- Model updates ↗
- Official DashScope Python SDK ↗
Last verified · Source ↗