Getting Started with Qwen API
This page will help you get started with Qwen API. You'll be up and running in a jiffy!
Qwen API User Guide
A comprehensive guide to understanding and using the Qwen API Proxy effectively.
Table of Contents
- Getting Started
- Understanding Authentication
- Choosing the Right Model
- Feature Guide
- File Upload Guidelines
- Best Practices
- Common Use Cases
- Error Handling
- Troubleshooting
- FAQ
Getting Started
What You Need
Before you begin using the Qwen API, make sure you have:
- A Qwen Account - Sign up at chat.qwen.ai if you don't have one
- Your Authentication Token - Extract it using the browser script provided in the README
- An HTTP Client - Any tool that can make HTTP requests (cURL, Postman, your application, etc.)
First Steps
- Get Your Token: Visit the Qwen website, run the token extraction script in your browser console, and copy the generated token
- Validate Your Token: Use the
/v1/validateendpoint to ensure your token is working - List Available Models: Check
/v1/modelsto see all models you can use - Make Your First Request: Try a simple chat completion to get familiar with the API
- Preserve Follow-Up Metadata: Store complete assistant messages so the hidden Qwen continuation metadata remains available
API Base URL
Direct endpoint requests should be sent to: https://qwen.aikit.club
For OpenAI SDK configuration, use: https://qwen.aikit.club/v1
The compatibility target is OpenAI Chat Completions and the documented Images-style endpoints. /v1/responses is not implemented.
Understanding Authentication
What is the Token?
The authentication token is the Qwen access token stored by chat.qwen.ai. Treat it like a password: it grants access to Qwen through your account.
Token Format
- Uses JWT format with three dot-separated segments:
header.payload.signature - Usually starts with
eyJ... - Can be sent as
Authorization: Bearer YOUR_TOKEN - The proxy also accepts the token through the
x-api-keyheader
Token Lifecycle
Valid Token → Make Requests → Token Expires → Refresh Token → Continue Using
When to Refresh
Your token will eventually expire. You'll know it's expired when you start getting authentication errors. Use the /v1/refresh endpoint to get a new token without logging in again.
Security Tips
- ✅ Store tokens securely (environment variables, secure storage)
- ✅ Never commit tokens to version control
- ✅ Use HTTPS only (never HTTP)
- ✅ Rotate tokens periodically
- ❌ Don't share tokens publicly
- ❌ Don't hardcode tokens in your application
Choosing the Right Model
Quick Model Selector
Need general conversation, vision, search, or reasoning?
→ Start with qwen3.7-plus
Need the strongest general model?
→ Use qwen3.8-max
Need web search?
→ Use qwen3.8-max, qwen3.7-plus, qwen3.6-plus, or qwen3.5-plus
Need configurable reasoning?
→ Use a reasoning-capable model with reasoning_effort or thinking_mode
Need comprehensive research?
→ Use qwen-deep-research (multi-phase research with citations)
Need code generation?
→ Use qwen3-coder-plus (specialized for coding)
Need web development?
→ Use qwen-web-dev (frontend UI/UX specialist)
Need full application?
→ Use qwen-full-stack (complete stack development)
Need presentation generation?
→ Use qwen-slides (slide previews plus downloadable PDF)
Need multimodal analysis?
→ Use a vision-capable listed model and attach image, audio, video, or document content
Model Capabilities Overview
Each model has different strengths. Check the Model Capabilities table in the README to see which features each model supports:
- 👁️ Vision - Can analyze images and visual content
- 💡 Reasoning - Advanced thinking and problem-solving
- 🌐 Web Search - Can search the web for current information
- 🔧 Tool Calling - Can use external tools and functions
Feature Guide
1. Basic Chat Conversations
What it does: Have text-based conversations with AI
When to use: General questions, content generation, explanations, creative writing
Best starting models: qwen3.7-plus, qwen3.8-max
Tips:
- Keep messages clear and specific
- Provide context when needed
- Use system messages to set behavior
- Enable streaming for real-time responses
2. Web Search Integration
What it does: AI can search the web and use current information
When to use: Questions about current events, recent developments, real-time data
Requirements:
- Use a model with web search capability (check the README table)
- Add
web_search_optionsto the request; the legacytools: [{ type: "web_search" }]form remains supported - Search responses include clickable citations and OpenAI-compatible URL annotations
Tips:
- Ask about current topics ("What happened today...")
- Request recent information ("Latest news about...")
- Specify time frames ("In the last week...")
3. Thinking Mode (Reasoning)
What it does: Selects Fast, Auto, or Thinking behavior and returns Qwen's reasoning summary as reasoning_content when available
When to use: Math problems, logic puzzles, complex analysis, step-by-step solutions
Requirements:
- OpenAI SDKs can use
reasoning_effort none/minimalmap to Fast,low/mediummap to Auto, andhigh/xhigh/maxmap to Thinking- Qwen-specific clients may use
thinking_mode: "fast" | "auto" | "thinking" - Legacy
enable_thinkingremains supported;thinking_budgetis no longer sent upstream
Tips:
- Use for problems that need careful reasoning
- Ask for step-by-step explanations
- Works best with reasoning-capable models
4. Vision and Image Analysis
What it does: AI can see and understand images, photos, screenshots, diagrams
When to use: Image description, visual analysis, OCR, chart interpretation
Supported formats: JPG, PNG, GIF, WebP (most common)
Tips:
- Provide clear, high-quality images
- Ask specific questions about what you want to know
- Combine multiple images for comparison (up to 5)
- Works with URLs or base64-encoded images
5. Document Analysis
What it does: AI can read and analyze PDF documents, text files, and other documents
When to use: Document summarization, information extraction, content analysis
Supported formats: PDF, TXT, MD, DOC, DOCX, PPT, PPTX, CSV, XLS, XLSX
Tips:
- Keep documents under 20MB
- Can combine with images (e.g., PDF + photo)
- Ask specific questions about document content
- Request summaries, key points, or specific information
6. Deep Research
What it does: Comprehensive multi-phase research with web search and citations
When to use: Academic research, market analysis, in-depth investigations
Model: Must use qwen-deep-research
Features:
- Normal research by default
- Advanced research through
reasoning_effort: "medium" | "high" | "xhigh" | "max" thinking_mode: "thinking"orenable_thinking: trueselects advanced research; Fast/Auto/false selects normal research- Multi-phase research process
- The same image, audio, video, and document attachments as normal multimodal chat
- Research planning and progress in
reasoning_content - Source validation
- Automatic citations
- Comprehensive reports
- Export to PDF/Markdown
Tips:
- Ask broad research questions
- Answer any first-turn clarification questions and include the complete assistant response in the follow-up request
- Let the AI complete all research phases; Deep Research collects the upstream result before formatting the final response
- Review citations for accuracy
- Download reports for offline use
- Do not add
toolsorweb_search_options; Deep Research manages research internally - Research-depth precedence is
thinking_mode, thenreasoning_effort, then legacyenable_thinking;thinking_budgetis ignored
7. Image Generation
What it does: Create new images from text descriptions
When to use: Creating art, illustrations, concept designs, visual content
Options:
- Size:
auto,1:1,3:4,4:3,16:9,9:16, or customWIDTHxHEIGHT - Custom dimensions map to the nearest supported aspect ratio
- Response: temporary
url(default) or inlineb64_json
Tips:
- Be descriptive in your prompts
- Specify style, mood, colors
- Mention composition and perspective
- Iterate with edits for refinement
8. Image Editing
What it does: Modify existing images using text instructions
When to use: Changing image elements, style adjustments, adding/removing objects
Input: Original image + editing instructions
Limit: Exactly one source image. Repeated image/image[] fields or a JSON image array return HTTP 400.
Output: Set response_format to url or b64_json
Tips:
- Provide clear editing instructions
- Use simple, direct commands
- One change at a time works best
- Can use generated images as input
9. Video Generation
What it does: Create videos from text, or animate one source image with a text instruction
When to use: Video content creation, animations, visual storytelling
Modes:
- Omit
imagefor text-to-video - Provide one image URL, base64 data URL, or multipart upload for image-to-video
- Repeated images or image arrays return HTTP 400
Options:
- Size:
auto, supported aspect ratios, or customWIDTHxHEIGHT - Response: temporary
url(default) or inline MP4b64_json
Tips:
- Describe motion and action clearly
- Specify scene changes
- Keep descriptions focused
- Longer videos take more time
10. Slides Generation
What it does: Creates a presentation plan, generates visual slide previews, and produces a downloadable PDF
Model: Use qwen-slides
Features:
- Topic or document-based slide planning
- Image and document attachments through the normal upload pipeline
- Generated Markdown image links for slide previews
- Downloadable presentation PDF
- Persistent follow-ups for confirmation and edits
Tips:
- Give a clear topic, audience, style, and approximate slide count
- A detailed source document such as a PDF improves planning reliability
- The first response may contain a draft plan; include it and reply
Confirmto continue the same Slides chat - Download the signed PDF URL promptly
11. Code Generation
What it does: Generate code, debug, explain programming concepts
Model: Best with qwen3-coder-plus
Features:
- Multi-language support
- Function/tool calling
- Code explanation
- Bug fixing
- Code optimization
Tips:
- Specify programming language
- Describe functionality clearly
- Ask for comments and documentation
- Request error handling
12. Web Development
What it does: Create web components, UI elements, responsive designs
Model: Use qwen-web-dev
Output: HTML, CSS, JavaScript
Features:
- Responsive design
- Modern CSS
- Interactive components
- Framework support (React, Vue)
- Accessibility considerations
Tips:
- Describe desired functionality
- Specify design preferences
- Mention framework if needed
- Ask for responsive design
- Include the prior assistant response when requesting edits so the same artifact chat continues
13. Full-Stack Development
What it does: Build complete applications with frontend, backend, database
Model: Use qwen-full-stack
Output: Complete application code
Features:
- Frontend frameworks
- Backend APIs
- Database schemas
- Authentication
- Deployment-ready code
Tips:
- Describe full requirements
- Specify tech stack preferences
- Mention scalability needs
- Request security features
- Continue with the prior assistant response to modify the existing application instead of starting over
File Upload Guidelines
Understanding File Categories
Files are grouped into two main categories:
Media Files (Image, Audio, Video):
- Image, audio, and video are different media types in the media group
- Do not mix different media types in one request
- Multiple images are allowed; audio and video are limited to one each
- Examples: JPG + MP4 = ❌ Invalid, JPG + PNG = ✅ Valid
Documents (PDF, Office, and text files):
- Separate category from media
- Can combine with media files
- Examples: JPG + PDF = ✅ Valid
What You Can Upload
Valid Single File Types:
- ✅ One or more images (up to 5)
- ✅ One audio file
- ✅ One video file
- ✅ One or more documents (up to 5)
Valid Combinations:
- ✅ Multiple images only
- ✅ Image(s) + Document(s)
- ✅ Audio + Document(s)
- ✅ Video + Document(s)
- ✅ Single media file only
Invalid Combinations:
- ❌ Image + Audio
- ❌ Image + Video
- ❌ Audio + Video
- ❌ Multiple videos
- ❌ Multiple audio files
Size and Duration Limits
Images:
- Maximum: 20MB per image
- Count: Up to 5 images
- Formats: JPG, PNG, GIF, WebP recommended
Audio:
- Maximum: 2,000MB
- Duration: Up to 3 hours (10,800 seconds)
- Count: 1 file only
- Formats: MP3, WAV, M4A, AAC recommended
Video:
- Maximum: 2,000MB
- Duration: Up to 1 hour (3,600 seconds)
- Count: 1 file only
- Formats: MP4, MOV, AVI, MKV recommended
Documents:
- Maximum: 20MB per document
- Count: Up to 5 documents
- Formats: PDF, TXT, MD, DOC, DOCX, PPT, PPTX, CSV, XLS, XLSX
These are Qwen's live runtime limits. The selected model's file_limits configuration can override them. Agent Mode may impose a separate maximum of 10 files, 20MB per file, and 50MB total.
Upload Methods
Method 1: URL
Provide a direct URL to the file hosted online
Method 2: Base64
Encode the file as base64 data and include it directly
Method 3: File Upload
Read a local file in your application and send it as a base64 data URL. Multipart form data is supported directly by image editing and image-to-video endpoints.
Attachment uploads are best-effort. If an attachment cannot be downloaded or uploaded, the proxy may skip it and continue as a text-only request.
Best Practices
Request Optimization
Stream for Real-Time:
- Enable streaming for chatbot-like experiences
- Provides instant feedback to users
- Better for long responses
Non-Stream for Complete Data:
- Use when you need the full response at once
- Better for batch processing
- Easier error handling
Message Management
System Messages:
- Set AI behavior and personality
- Define response format
- Establish context
User Messages:
- Ask clear, specific questions
- Provide necessary context
- Keep conversations focused
Assistant Messages:
- Include the complete previous AI response for context
- Responses contain an invisible
qwen_metadataHTML comment with upstream response and chat IDs - Keeping that assistant content lets the proxy continue the same Qwen chat instead of creating a new chat
- Build on previous exchanges
Context Management
Keep Relevant History:
- Include the latest assistant response containing
qwen_metadataand the new user message - Keep other relevant messages when your application needs local history
- Web Dev, Full Stack, Slides, and Deep Research use the same continuation mechanism
Token Awareness:
- Longer conversations use more tokens
- Summarize old conversations if needed
- Reset context when changing topics
Rate Limiting
Respect Limits:
- Don't spam requests rapidly
- Implement delays between requests
- Use queuing for bulk operations
Handle Failures:
- Retry with exponential backoff
- Don't retry immediately
- Log errors for debugging
Error Recovery
Graceful Degradation:
- Have fallback options
- Inform users of issues
- Don't crash on errors
Token Refresh:
- Detect expiration automatically
- Refresh before making request
- Store new token securely
Common Use Cases
1. Building a Chatbot
Goal: Create an interactive conversational AI
Steps:
- Initialize with system message
- Maintain conversation history
- Stream responses for real-time feel
- Handle context window limits
- Reset conversation when needed
Best Practices:
- Keep last 10-20 messages
- Use streaming for better UX
- Implement typing indicators
- Handle connection issues
2. Document Summarization
Goal: Extract key information from documents
Steps:
- Upload document (PDF, TXT)
- Ask for summary
- Request specific sections
- Extract key points
Best Practices:
- Use clear, focused questions
- Specify desired length
- Ask for structured output
- Verify important information
3. Image Analysis
Goal: Understand and describe visual content
Steps:
- Provide image URL or file
- Ask specific questions
- Request detailed analysis
- Compare multiple images
Best Practices:
- Use high-quality images
- Ask focused questions
- Specify what to look for
- Combine with text context
4. Research Assistant
Goal: Conduct comprehensive research
Steps:
- Use
qwen-deep-researchmodel - Provide a research topic and optional media/documents
- Answer any clarification questions in a follow-up request
- Wait for all phases to complete
- Review sources and citations
- Download PDF/Markdown reports if needed
Best Practices:
- Start with clear research question
- Allow time for completion
- Verify citations
- Use non-streaming when you need one complete result; streaming is formatted after upstream research completes
5. Content Generation
Goal: Create written content
Steps:
- Describe content type
- Specify tone and style
- Set length requirements
- Iterate and refine
Best Practices:
- Provide examples if possible
- Be specific about requirements
- Review and edit output
- Regenerate if needed
6. Code Assistant
Goal: Help with programming tasks
Steps:
- Use
qwen3-coder-plusmodel - Describe functionality
- Specify language/framework
- Request explanations
- Ask for improvements
Best Practices:
- Include context about project
- Specify error handling needs
- Request code comments
- Test generated code
7. Visual Content Creation
Goal: Generate images and videos
Steps:
- Write detailed prompts
- Specify size and style
- Generate initial content
- Edit and refine
- Download final result
Best Practices:
- Be descriptive
- Iterate on results
- Use editing for refinement
- Save successful prompts
- Use
b64_jsonwhen you need inline bytes instead of a signed URL - Download URL results promptly because generated asset links may be temporary
8. Multi-Language Support
Goal: Translate or work in multiple languages
Steps:
- Specify source and target languages
- Provide context
- Request translation or generation
- Verify accuracy
Best Practices:
- Specify language explicitly
- Provide cultural context
- Verify translations
- Use native speakers for review
Error Handling
Common Errors and Solutions
Authentication Errors (401)
Symptoms: "Invalid API key" or "Unauthorized"
Solutions:
- Validate your token using
/v1/validate - Refresh token using
/v1/refresh - Regenerate token from browser
- Check token format is correct
Invalid Request (400)
Symptoms: "Bad request" or "Invalid parameters"
Solutions:
- Check request format matches API spec
- Verify all required fields are present
- Validate JSON syntax
- Check parameter values are valid
Rate Limiting (429)
Symptoms: "Too many requests"
Solutions:
- Slow down request rate
- Implement request queuing
- Add delays between requests
- Use exponential backoff
File Too Large (413)
Symptoms: "File size exceeds limit"
Solutions:
- Compress images before upload
- Use smaller file sizes
- Split large documents
- Check size limits for file type
Unsupported Format (415)
Symptoms: "Unsupported media type"
Solutions:
- Use supported file formats
- Convert files to compatible format
- Check format is in allowed list
- Verify MIME type is correct
Server Error (500)
Symptoms: "Internal server error"
Solutions:
- Retry request after delay
- Check if service is operational
- Report persistent errors
- Use different endpoint if available
Error Response Structure
Every error response includes:
- message: Human-readable error description
- type: Error category
- code: Specific error code
- param: Which parameter caused error (if applicable)
Retry Strategies
Immediate Retry (Network issues):
- Retry 1-2 times immediately
- For temporary connection problems
- Don't retry on auth errors
Exponential Backoff (Rate limits):
- Wait 1s, 2s, 4s, 8s between retries
- For 429 or temporary 500 errors
- Give up after 3-5 attempts
No Retry (Client errors):
- Don't retry 400, 401, 403, 415
- Fix the request instead
- These indicate client-side problems
Troubleshooting
Token Issues
Problem: Token not working
Diagnostic Steps:
- Check token format (JWT with three dot-separated segments, usually starting with
eyJ) - Validate using
/v1/validateendpoint - Check if token is expired
- Verify you're logged into Qwen
- Regenerate token from browser
Common Causes:
- Token copied incorrectly
- Session expired
- Account issues
- Wrong token format
Streaming Problems
Problem: Stream cuts off or doesn't work
Diagnostic Steps:
- Verify
stream: trueis set - Check you're handling SSE format
- Look for
[DONE]marker - Test with non-streaming first
- Check network/proxy settings
Common Causes:
- Incorrect SSE parsing
- Network interruptions
- Proxy buffering
- Client timeout too short
File Upload Failures
Problem: Can't upload files
Diagnostic Steps:
- Check file size against limits
- Verify file format is supported
- Test with smaller file
- Check file is not corrupted
- Verify URL is accessible (if using URL)
Common Causes:
- File too large
- Unsupported format
- Mixing incompatible file types
- Network issues
Model Not Working
Problem: Specific model gives errors
Diagnostic Steps:
- Check model name spelling
- Verify model exists (
/v1/models) - Check model supports requested feature
- Try with default model
- Check capability matrix
Common Causes:
- Typo in model name
- Model doesn't support feature
- Model deprecated or unavailable
- Feature flag not set
Slow Responses
Problem: Requests take too long
Diagnostic Steps:
- Check if large file uploads
- Verify network connection
- Try simpler request
- Use
qwen3.7-pluswith Fast mode for lower latency - Enable streaming for normal chat
Common Causes:
- Large files being processed
- Complex thinking/research tasks
- Network latency
- Server load
- Long generation requested
Follow-Up Context Not Working
Problem: Each message starts a new Qwen chat
Diagnostic Steps:
- Keep the complete previous assistant response in your next
messagesarray - Verify it still contains the invisible
<!-- qwen_metadata: ... -->comment - Do not strip HTML comments from stored assistant content
- Confirm the previous response completed successfully
- Test with non-streaming mode to inspect the complete response
Common Causes:
- Client removed the metadata comment
- Only the latest user message was sent
- Stream was interrupted before metadata arrived
- A renderer or sanitizer stripped HTML comments
FAQ
General Questions
Q: Is this service free to use?
A: Yes, the proxy itself is free. However, you need a Qwen account, and any usage limits depend on your Qwen account tier. Free Qwen accounts have certain limitations, while premium accounts have higher limits.
Q: Are there rate limits?
A: The proxy doesn't impose its own rate limits. All limitations come from your Qwen account. Free accounts have lower limits than paid accounts.
Q: Can I use this in production?
A: Yes, but keep in mind this is an unofficial proxy. For production use, implement proper error handling, token refresh logic, and have fallback strategies.
Q: How do I get support?
A: Open an issue on GitHub for bugs or feature requests. Check existing issues and discussions for common questions.
Q: Can I self-host this?
A: Yes! The code is open source. You can deploy it to your own Cloudflare Workers account or adapt it for other platforms.
Authentication
Q: How long do tokens last?
A: Tokens expire based on Qwen's session management. You'll need to refresh or regenerate them periodically.
Q: Can I use the same token from multiple applications?
A: Yes, one token can be used across multiple applications, but be aware of rate limits.
Q: What if my token gets leaked?
A: Regenerate immediately from the Qwen website and update it in your applications.
Q: Do I need to refresh tokens manually?
A: You can implement automatic refresh using the /v1/refresh endpoint when you detect expiration.
Models
Q: Which model should I use?
A: For general use, start with qwen3.7-plus. Use qwen3.8-max when you need the strongest supported general model.
Q: Can I switch models mid-conversation?
A: Changing models should be treated as a new conversation. For follow-ups with the same model, preserve the prior assistant response and its hidden metadata.
Q: Are all models always available?
A: Availability depends on your Qwen account. Some models may require premium access.
Q: How do I choose between Fast, Auto, and Thinking?
A: Use Fast for lower latency, Auto when Qwen should decide whether reasoning is needed, and Thinking for complex work that benefits from a reasoning summary.
Features
Q: Can I use web search with any model?
A: No, only models with web search capability (check the capabilities table) support this feature.
Q: How do I enable thinking mode?
A: Prefer OpenAI's reasoning_effort field or use thinking_mode: "thinking". Legacy enable_thinking: true remains supported.
Q: Can I combine multiple features?
A: Yes! For example, you can use web search + thinking mode + vision together if the model supports all three.
Q: Does audio input return realtime speech output?
A: No. The chat.qwen.ai Web API accepts audio input but does not expose realtime speech-to-speech or audio-output streaming. Those capabilities belong to the official Qwen/DashScope API.
Q: Are generated asset links permanent?
A: Generated image, video, Slides, PDF, and Markdown URLs may be signed or temporary. Download important assets promptly or request b64_json for supported generation endpoints.
Q: What's the maximum file size?
A: Current runtime defaults are Images (20MB each), Audio (2,000MB), Video (2,000MB), and Documents (20MB each). Model-specific limits may override them.
Technical
Q: Is streaming faster than non-streaming?
A: Streaming provides faster first response but same total time. It's better for user experience.
Q: Can I cancel a request in progress?
A: You can close the connection, but the server may continue processing.
Q: How do I handle long conversations?
A: Keep only recent relevant messages to avoid hitting context limits. Summarize old conversations if needed.
Q: Can I use this with OpenAI SDKs?
A: Yes for the documented Chat Completions-style endpoints: set the base URL to https://qwen.aikit.club/v1 and use your Qwen token. The OpenAI Responses API (/v1/responses) is not implemented, and Qwen-specific fields may require extra_body or raw request dictionaries.
Troubleshooting
Q: Why am I getting "Invalid API key" errors?
A: Your token may be expired, invalid, or incorrectly formatted. Try validating or regenerating it.
Q: Files aren't uploading properly
A: Check file size, format, and that you're not mixing incompatible file types (e.g., image + video).
Q: Responses are cut off
A: This could be token limits, connection issues, or streaming problems. Try non-streaming mode first.
Q: Can I get request logs for debugging?
A: Continuation IDs are stored in an invisible qwen_metadata HTML comment appended to assistant content. Preserve it for follow-up requests.
Updated 3 months ago
