A first API demo often fails for reasons unrelated to prompting: a key is committed to source control, a copied model ID is wrong, or a network error leaves no useful record. We will build a deliberately small sentiment classifier while handling those operational details from the start.
Create the environment
uv init --python 3.10
uv add openai
export DASHSCOPE_API_KEY="your-key"
export DASHSCOPE_MODEL="qwen-plus"
Alibaba Cloud Model Studio exposes an OpenAI-compatible endpoint. Compatibility does not mean every platform extension is part of the OpenAI specification, so check the Model Studio documentation before adding features such as web search.
Keep the key outside source files. For a deployed service, use the secret facility provided by the operating system or deployment platform.
Add validation and logs
Create main.py around this flow:
- Read
DASHSCOPE_API_KEYand the configurable model ID from the environment. - Reject a missing key or empty input before making a request.
- Configure a timeout and a limited retry count.
- Ask for exactly one of
positive,negative, orneutral. - Treat the model response as untrusted input and validate the label.
- Catch connection, HTTP status, validation, and unexpected errors separately.
- Never log the key, authorization header, or complete process environment.
Run the program through uv:
uv run python main.py
A normal run should print an allowed label and record a completion event. The model's raw wording is not the contract; the validator defines what the application accepts.
Test failures on purpose
Remove the key temporarily and run again:
unset DASHSCOPE_API_KEY
uv run python main.py
The program should report a configuration error and return a nonzero exit code. Restore the key, set an invalid model ID, and verify that the service error is also distinguishable in the logs.
These checks matter because a successful demo says nothing about expired credentials, model retirement, or a broken network path.
What production still needs
This structure is suitable for learning and small tools. A service also needs request correlation, metrics, rate limiting, concurrency controls, log redaction, and retry rules chosen for the business operation. Even a syntactically valid model label should pass application policy before it triggers an action.
The next article separates web search, retrieval-augmented generation, and conversation memory. They address different data problems and should not be treated as one generic “knowledge” feature.