Appearance
Synchronous API for text embedding
Reference, synced 2026-06-13.
flowchart TD n0["Models"] n1["Overview"] n2["Products"] n3["Solutions"] n4["Pricing"] n5["Resources"] n6["Partners"] n7["Support"] n8["Language"] n0 --> n1 n1 --> n2 n2 --> n3 n3 --> n4 n4 --> n5 n5 --> n6 n6 --> n7 n7 --> n8
Free access Accelerate Delivery with Fixed-Cost Agentic CodingWatch how it works
Models
Empowering AI innovation for both enterprises and developers with Alibaba Cloud’s best-in-class Qwen models, AI-native apps, and AI solutions.
Alibaba Cloud Model Studio \ Enterprise-grade large model service and application development platform.
Try Visual Model \ Supports image understanding, image generation, and video generation.
Models
HappyHorse-1.0-T2V \ Cinematic creative generation, ultimate dynamic details Qwen3-VL-Plus \ Native VL, spatial reasoning, 1M-context video analysis Wan2.7-VideoEdit \ Supports both localized and global editing with prompt
Qwen3.6-Plus \ Native multimodal, 1M context, agentic coding Wan2.7-Image-Pro \ Interactive editing, long-text rendering, precise prompt following Qwen-Plus \ Balanced intelligence, efficient inference, production-ready performance
Qwen-Image-2.0 \ Professional infographics, exquisite photorealism Z-Image-Turbo \ Ultra-fast image generation, high throughput, cost-optimized inference Qwen3-Coder-Next \ Multi-turn tool interactions, future-ready development support
Wan2.7-T2V \ High-fidelity T2V, 15s duration, advanced camera control Wan2.7-I2V \ Cinematic I2V with emotional depth and visceral impact Wan2.7-R2V \ Up to 5 mixed image/video inputs and audio timbre cloning
GenAI Application
Qoder \ Intelligent coding assistant, available for enterprise-dedicated deployment. Qoder CN \ AI-powered coding assistant that boosts developer productivity with intelligent code completion, AI chat, multi-file editing, and task automation.
AI Service
Model Experience \ Experience full-scale, multimodal model capabilities online. Platform for AI \ An AI-native algorithm engineering platform for end-to-end modeling, training, and inference service deployment. Fine-tune Video Generation Model \ Customize Wan’s text-to-video capabilities through model fine-tuning to meet your unique requirements.
AI Use Case
AI Savings Plan Hot \ Save up to 47% on AI costs. Limited-time offer tailored to your usage. AI Video Creation \ Elevate your professional video production with Wan 2.6.
AI Token Plan \ One plan. Multiple models. Big Savings with a Fixed Subscription. AI Image Creation \ All-in-one creative suite for copywriting, image generation, and poster design.
Overview
As a global full-stack AI leader, Alibaba Cloud aims to make computing accessible to everyone and help worldwide customers accelerate innovation.
Why Alibaba Cloud
About Alibaba Cloud \ AI Powered Cloud Technology Our Global Network \ Explore our global presence and deployment regions around the world Our Global Offices \ With offices in 4 continents, we're always close to where it matters.
Asia Accelerator \ Accelerate Success in Asia with Alibaba Cloud Go Global \ Benefits of our Global Alliance Trust Center \ Empowering enterprises with a secure, compliant, and globally trusted cloud infrastructure
Customers and Insights
Olympic Games \ Alibaba Cloud Powers Olympic Games with AI-powered cloud technology Case Studies \ Learn how customers are scaling their businesses on Alibaba Cloud Analyst Reports \ Learn what the top industry analyst firms are saying about Alibaba Cloud
What's New
Events and Webinars \ Quick access to upcoming and on-demand events Product Updates \ Stay informed of the latest innovations Press Room \ Latest news and media releases
Products
Featured ProductsAI & Machine Learning Computing Container Storage Networking & CDN Security Middleware Database Analytics ComputingMedia ServicesEnterprise Services & Cloud CommunicationDomain Names and WebsitesEnd User ComputingServerlessDeveloper ToolsMigration & O&M ManagementApsara Stack
Featured Products
Alibaba Cloud Model Studio \ Supercharge your AI journey effortlessly with industry-leading GenAI models ApsaraDB RDS \ Store and manage your business data, with automated monitoring and backups Certificate Management Service (Original SSL Certificate) \ Create a safe and secure connection between your website and users
Elastic Compute Service (ECS) \ Host websites anywhere and scale enterprise workloads Container Service for Kubernetes (ACK) \ Run and scale containerized applications on managed Kubernetes infrastructure Object Storage Service (OSS) \ Store large amounts of data in the cloud and access it anywhere, anytime
Simple Application Server (SAS) \ All-in-one services for fast deployment Elastic IP Address (EIP) \ Manage your public IPs independently to improve internet network quality Domain Names and Website \ Get the perfect domain name to suit your every need
Related Programs
Solutions
Solutions by Industry Technical Solutions AI WebsitesNetworking Security and ComplianceData and AnalyticsEnterprise Service and ApplicationCloud MigrationCloud NativeHybrid CloudSMB solutions
Financial Services \ Innovate faster with Alibaba Cloud Games \ Grow your game rapidly with high global availability
New Retail \ Alibaba Cloud enables digital retail transformation to fuel growth and realize an omnichannel customer experience throughout the consumer journey. Media and Entertainment \ Ready your content for today's media market with a digitalized media journey
Supply Chain \ Power your supply chain with intelligent, efficient, and reliable solutions Sports \ Digitizing the sports industry with intelligent tech
Sustainability \ Achieve a sustainable future with low-carbon and energy-efficient technologies
Pricing
Flexible options like pay-as-you-go and clear billing rules to meet diverse business needs.
Overview & Tools
Pricing Calculator \ Get an instant pricing estimate based on your usage and needs Free Trial \ Try our 80+ cloud products for free.
Pricing Options \ Get the most out of Alibaba Cloud with flexible pricing
Optimize your cost
Migrate & Save \ Superior Performance At Lower Pricing. Save up to 50%. Promotion Center \ Unlock the latest Alibaba Cloud offers & promos
Resources
Official documentation, extensive tools, training resources, and a community to grow and innovate in the cloud.
Technical Resources
Documentation \ Product guides and FAQs Architecture Center \ Design reliable, secure, and efficient cloud architecture. Intelligent Solution Explorer \ Find the right solution for you, powered by AI
Blog \ Latest cloud insights and developer trends Whitepapers \ Research that explores the how and why behind our technology
Training&Certification
Alibaba Cloud Academy \ Build cloud skills and earn certifications with expert-led training.
Developer Hub
Alibaba Cloud Project Hub \ Explore real-world projects built by developers using our platform. Our Developer MVPs \ Celebrating the developers who lead, build, and inspire our community
Partners
Partner-first strategy offering collaborative product, sales, and service models, plus high-quality partner solutions that complement Alibaba Cloud’s capabilities.
Marketplace
AI Alliance for ISVs \ Partner with us to build and grow AI solutions together ISV Benefits \ Unlock resources, market access, and go-to-market support as an ISV partner
Alibaba Cloud Marketplace \ Explore ready-to-deploy solutions from our partners and ISVs
Find a Partner
Partner Hub \ Find your ideal partner in no time
Become a Partner
Partner Network \ A partner portal for Alibaba Cloud Channel, Technology, MSP partner and other partner programs
Support
Full-lifecycle support and expert services, from cloud advisory and migration to operations.
Support & Professional Services
Professional Services \ Expert-led services to design, migrate, and optimize your cloud journey Support Plans \ Flexible support for every stage — from startup to enterprise
Partner Support Program \ Priority technical support for partners, with dedicated managers and faster issue resolution
Contact us
Connect With Us \
Talk to a sales expert and get a custom quote for your business
Language
- English
- 简体中文
- 繁體中文
- 日本語
- Bahasa Indonesia
Locale
Visit aliyun.com
Documentation
Alibaba Cloud Model Studio
User Guide (Models) User Guide (Application) API Reference (Models) API Reference (Application)
Search for Help Content
Getting Started
The Beginner's Guide
Well-Architected Framework
AI & Machine Learning
Platform For AI
Alibaba Cloud Model Studio
DashVector
Artificial Intelligence Recommendation
OpenSearch
Image Search
Machine Translation
Intelligent Speech Interaction
Optimization Solver
Intelligent Computing LINGJUN
Computing
Elastic Compute Service
Elastic GPU Service
Elastic Container Instance
Dedicated Host
Compute Nest
Simple Application Server
Cloud Box
Auto Scaling
Elastic High Performance Computing
Batch Compute (Deprecated)
Function Compute
Serverless App Engine
ENS
Elastic Desktop Service
App Streaming
WUYING Terminal
Cloud Phone
Edge Network Acceleration
Alibaba Cloud Linux
AgentBay
Container
Container Service for Kubernetes
Container Compute Service
Container Registry
Storage
Object Storage Service
Cloud Parallel File Storage
File Storage NAS
Tablestore
Storage Capacity Unit
Simple Log Service
Cloud Backup
Intelligent Media Management
Drive and Photo Service
Data Transport
Cloud Storage Gateway
Data Online Migration
Hybrid Cloud Storage Array
Storage Services Overview
Backup and Disaster Recovery Center
Networking and CDN
Server Load Balancer
Elastic IP Address
Internet Shared Bandwidth
Data Transfer Plan
Virtual Private Cloud
NAT Gateway
PrivateLink
Alibaba Cloud DNS PrivateZone
Network Intelligence Service
Cloud Data Transfer
IPv6 Gateway
Anycast Elastic IP Address
Cloud Enterprise Network
Global Accelerator
VPN Gateway
Smart Access Gateway
Express Connect
CDN
Edge Security Acceleration
Cloud Network Well-architected Design Guidelines
Security
Anti-DDoS
Web Application Firewall
Cloud Firewall
Security Center
Bastionhost
Secure Access Service Edge
Certificate Management Service
Key Management Service
Data Security Center
Identity as a Service
Fraud Detection
AI Guardrails
Captcha
Blockchain as a Service
ID Verification
Managed Security Service
Middleware
Enterprise Distributed Application Service
Microservices Engine
Alibaba Cloud Service Mesh
SchedulerX
ApsaraMQ for RocketMQ
ApsaraMQ for Kafka
ApsaraMQ for RabbitMQ
ApsaraMQ for MQTT
Simple Message Queue (formerly MNS)
CloudFlow
EventBridge
Application Real-Time Monitoring Service
Managed Service for Prometheus
Managed Service for Grafana
Managed Service for OpenTelemetry
Performance Testing
STAROps
Databases
ApsaraDB Console
PolarDB
ApsaraDB RDS
ApsaraDB for OceanBase (Deprecated)
Tair (Redis® OSS-Compatible)
Lindorm
Time Series Database
ApsaraDB for MongoDB
ApsaraDB for HBase
ApsaraDB for Memcache
ApsaraDB for MyBase
AnalyticDB
ApsaraDB for ClickHouse
ApsaraDB for SelectDB
Data Transmission Service
Database Autonomy Service
Data Management
Database Gateway - Deprecated
ApsaraDB for Cassandra - Deprecated
Analytics Computing
MaxCompute
Hologres
Realtime Compute for Apache Flink
Elasticsearch
Vector Retrieval Service for Milvus
E-MapReduce
Data Lake Formation
DataV
Quick BI
Quick Audience
Quick Tracking
DataWorks
DataHub
Dataphin
Media Services
ApsaraVideo VOD
ApsaraVideo Live
Intelligent Media Services
ApsaraVideo Media Processing
Apsara Video SDK
Enterprise Services & Cloud Communication
Energy Expert
CloudQuotation
Salesforce on Alibaba Cloud
GoChina ICP Filing Assistant
Marketplace
Alibaba Mail
Direct Mail
Short Message Service
Voice Service
Phone Number Verification Service
Cell Phone Number Service
Chat App Message Service
Financial Intelligence Engine
Domain Names and Websites
Domain Names
ICP Filing
Alibaba Cloud DNS
End User Computing
Elastic Desktop Service
App Streaming
WUYING Terminal
Cloud Phone
AgentBay
Internet of Things
IoT Platform
Serverless
Serverless App Engine
CloudFlow
EventBridge
Simple Message Queue (formerly MNS)
Function Compute
Developer Tools
OpenAPI Explorer
Alibaba Cloud SDK
Cloud Shell
Resource Orchestration Service
Alibaba Cloud CLI
BSS OpenAPI
Terraform
Pulumi
Ticket System API
Mobile Platform as a Service
Alibaba Cloud DevOps
API Gateway
Cloud Control API
AI Coding Assistant Lingma
Cloud Skills Portal
Migration & O&M Management
CloudOps Orchestration Service
Cloud Monitor
Intelligent Advisor
Cloud Governance Center
ActionTrail
Cloud Config
Resource Access Management
Resource Management
Cloud Architect Design Tools
Migration Hub
Server Migration Center
Service Catalog
Logic Composer
Quota Center
CloudSSO
HTTPDNS
Solutions
SAP
SuperApp
OpenLake
Membership Service
Expenses and Costs
Account Center
More
Support
Legal
Tech Share Terms and Conditions
After Sales Support
China Gateway Program
Service Level Objectives
Management Console
Security Control
The general-purpose text embedding model converts text data into numerical vectors for downstream tasks like semantic search, recommendation, clustering, and classification.
Model overview
Singapore
China (Beijing)
China (Hong Kong)
| Model | Embedding dimensions | Max rows | Max tokens per line( Note) | Price (per 1M input tokens) | Supported languages | Free quota (Note) |
| text-embedding-v4 > Part of the Qwen3-Embedding series | 2,048, 1,536, 1,024 (default), 768, 512, 256, 128, 64 | 10 | 8,192 | $0.07 | Chinese, English, Spanish, French, Portuguese, Indonesian, Japanese, Korean, German, Russian, and over 100 other major languages | 1 million tokens Validity: 90 days after you activate Model Studio |
| text-embedding-v3 | 1,024 (default), 768, 512 | Chinese, English, Spanish, French, Portuguese, Indonesian, Japanese, Korean, German, Russian, and over 50 other major languages | 500,000 tokens Validity: 90 days after you activate Model Studio |
| Model | Embedding dimensions | Max rows | Max tokens per line | Price (per 1M input tokens) | Supported languages |
| text-embedding-v4 > Part of the Qwen3-Embedding series | 2,048, 1,536, 1,024 (default), 768, 512, 256, 128, 64 | 10 | 8,192 | $0.072 | Chinese, English, Spanish, French, Portuguese, Indonesian, Japanese, Korean, German, Russian, and over 100 other major languages, plus multiple programming languages |
| Model | Embedding dimensions | Max rows | Max tokens per line | Price (per 1M input tokens) | Supported languages |
| text-embedding-v4 > Part of the Qwen3-Embedding series | 2,048, 1,536, 1,024 (default), 768, 512, 256, 128, 64 | 10 | 8,192 | $0.07 | Chinese, English, Spanish, French, Portuguese, Indonesian, Japanese, Korean, German, Russian, and over 100 other major languages, plus multiple programming languages |
For model rate limits, see Rate limiting.
Prerequisites
Users familiar with the OpenAI ecosystem can use the OpenAI-compatible API for a quick migration. The DashScope API provides more unique features.
Obtain an API key and export the API key as an environment variable. If you use an SDK to make calls, install the DashScope SDK.
OpenAI compatibility
Thebase_url to configure for SDK calls:
Singapore: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1. Replace
WorkspaceIdwith your actual workspace ID.China (Beijing): https://dashscope.aliyuncs.com/compatible-mode/v1
China (Hong Kong): https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/compatible-mode/v1. Replace
WorkspaceIdwith your actual workspace ID.
Theendpoint to configure for HTTP calls:
Singapore: POSThttps://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/embeddings. Replace
WorkspaceIdwith your actual workspace ID.China (Beijing): POSThttps://dashscope.aliyuncs.com/compatible-mode/v1/embeddings
China (Hong Kong): POST https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/compatible-mode/v1/embeddings. Replace
WorkspaceIdwith your actual workspace ID.
Important
The legacy Singapore domain https://dashscope-intl.aliyuncs.comand China (Hong Kong) domain https://cn-hongkong.dashscope.aliyuncs.comwill be discontinued. Migrate to https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com (Singapore) and https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com (China (Hong Kong)) as soon as possible.
| ### Request body | Input string Input string list Input file Python Java curl python import os from openai import OpenAI client = OpenAI( # If you use a model in the China (Beijing) region, you must use an API key from that region. Get one at: https://bailian.console.alibabacloud.com/?tab=model#/api-key api_key=os.getenv("DASHSCOPE_API_KEY"), # If the environment variable is not set, replace the placeholder with your API key. # This is the Singapore region URL. Replace WorkspaceId with your actual workspace ID. URLs differ by region. base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1" ) completion = client.embeddings.create( model="text-embedding-v4", input='The clothes are of good quality and look good, definitely worth the wait. I love them.', dimensions=1024, encoding_format="float" ) print(completion.model_dump_json()) java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.HashMap; import java.util.Map; import com.alibaba.dashscope.utils.JsonUtils; public final class Main { public static void main(String[] args) { // If you use a model in the China (Beijing) region, you must use an API key from that region. Get one at: https://bailian.console.alibabacloud.com/?tab=model#/api-key String apiKey = System.getenv("DASHSCOPE_API_KEY"); if (apiKey == null) { System.out.println("DASHSCOPE_API_KEY not found in environment variables"); return; } // This is the Singapore region URL. Replace WorkspaceId with your actual workspace ID. URLs differ by region. String baseUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/embeddings"; HttpClient client = HttpClient.newHttpClient(); Map<String, Object> requestBody = new HashMap<>(); requestBody.put("model", "text-embedding-v4"); requestBody.put("input", "The wind is strong, the sky is high, and the apes cry mournfully. The islet is clear, the sand is white, and the birds fly back. The boundless forest sheds its leaves shower by shower. The endless river rolls on wave after wave."); requestBody.put("dimensions", 1024); requestBody.put("encoding_format", "float"); try { String requestBodyString = JsonUtils.toJson(requestBody); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(baseUrl)) .header("Content-Type", "application/json") .header("Authorization", "Bearer " + apiKey) .POST(HttpRequest.BodyPublishers.ofString(requestBodyString)) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() == 200) { System.out.println("Response: " + response.body()); } else { System.out.printf("Failed to retrieve response, status code: %d, response: %s%n", response.statusCode(), response.body()); } } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } } > If you use a model in the China (Beijing) region, you must use an API key from that region and replace the URL with https://dashscope.aliyuncs.com/compatible-mode/v1/embeddings. This is the Singapore region URL. Replace WorkspaceId with your actual workspace ID. URLs differ by region. curl curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/embeddings' \ --header "Authorization: Bearer $DASHSCOPE_API_KEY" \ --header 'Content-Type: application/json' \ --data '{ "model": "text-embedding-v4", "input": "The wind is strong, the sky is high, and the apes cry mournfully. The islet is clear, the sand is white, and the birds fly back. The boundless forest sheds its leaves shower by shower. The endless river rolls on wave after wave.", "dimensions": 1024, "encoding_format": "float" }' Python Java curl python import os from openai import OpenAI client = OpenAI( # If you use a model in the China (Beijing) region, you must use an API key from that region. Get one at: https://bailian.console.alibabacloud.com/?tab=model#/api-key api_key=os.getenv("DASHSCOPE_API_KEY"), # If the environment variable is not set, replace the placeholder with your API key. # This is the Singapore region URL. Replace WorkspaceId with your actual workspace ID. URLs differ by region. base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1" ) completion = client.embeddings.create( model="text-embedding-v4", input=['The wind is strong, the sky is high, and the apes cry mournfully.', 'The islet is clear, the sand is white, and the birds fly back.', 'The boundless forest sheds its leaves shower by shower.', 'The endless river rolls on wave after wave.'], dimensions=1024, encoding_format="float" ) print(completion.model_dump_json()) java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.HashMap; import java.util.Map; import java.util.List; import java.util.Arrays; import com.alibaba.dashscope.utils.JsonUtils; public final class Main { public static void main(String[] args) { // Get the API key from an environment variable. If not configured, replace it with your API key. // If you use a model in the China (Beijing) region, you must use an API key from that region. Get one at: https://bailian.console.alibabacloud.com/?tab=model#/api-key String apiKey = System.getenv("DASHSCOPE_API_KEY"); if (apiKey == null) { System.out.println("DASHSCOPE_API_KEY not found in environment variables"); return; } // This is the Singapore region URL. Replace WorkspaceId with your actual workspace ID. URLs differ by region. String baseUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/embeddings"; HttpClient client = HttpClient.newHttpClient(); Map<String, Object> requestBody = new HashMap<>(); requestBody.put("model", "text-embedding-v4"); List<String> inputList = Arrays.asList("The wind is strong, the sky is high, and the apes cry mournfully.", "The islet is clear, the sand is white, and the birds fly back.", "The boundless forest sheds its leaves shower by shower.", "The endless river rolls on wave after wave."); requestBody.put("input", inputList); requestBody.put("encoding_format", "float"); try { // Convert the request body to a JSON string. String requestBodyString = JsonUtils.toJson(requestBody); // Build the HTTP request. HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(baseUrl)) .header("Content-Type", "application/json") .header("Authorization", "Bearer " + apiKey) .POST(HttpRequest.BodyPublishers.ofString(requestBodyString)) .build(); // Send the request and receive the response. HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() == 200) { System.out.println("Response: " + response.body()); } else { System.out.printf("Failed to retrieve response, status code: %d, response: %s%n", response.statusCode(), response.body()); } } catch (Exception e) { // Catch and print the exception. System.err.println("Error: " + e.getMessage()); } } } > If you use a model in the China (Beijing) region, you must use an API key from that region and replace the URL with https://dashscope.aliyuncs.com/compatible-mode/v1/embeddings. This is the Singapore region URL. Replace WorkspaceId with your actual workspace ID. URLs differ by region. curl curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/embeddings' \ --header "Authorization: Bearer $DASHSCOPE_API_KEY" \ --header 'Content-Type: application/json' \ --data '{ "model": "text-embedding-v4", "input": [ "The wind is strong, the sky is high, and the apes cry mournfully.", "The islet is clear, the sand is white, and the birds fly back.", "The boundless forest sheds its leaves shower by shower.", "The endless river rolls on wave after wave." ], "dimensions": 1024, "encoding_format": "float" }' Python Java curl python import os from openai import OpenAI client = OpenAI( # If you use a model in the China (Beijing) region, you must use an API key from that region. Get one at: https://bailian.console.alibabacloud.com/?tab=model#/api-key api_key=os.getenv("DASHSCOPE_API_KEY"), # If the environment variable is not set, replace the placeholder with your API key. # This is the Singapore region URL. Replace WorkspaceId with your actual workspace ID. URLs differ by region. base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1" ) # Make sure to replace 'texts_to_embedding.txt' with your file name or path. with open('texts_to_embedding.txt', 'r', encoding='utf-8') as f: completion = client.embeddings.create( model="text-embedding-v4", input=f, encoding_format="float" ) print(completion.model_dump_json()) java import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.HashMap; import java.util.Map; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import com.alibaba.dashscope.utils.JsonUtils; public class Main { public static void main(String[] args) { // Get the API key from an environment variable. If not configured, replace it with your API key. // If you use a model in the China (Beijing) region, you must use an API key from that region. Get one at: https://bailian.console.alibabacloud.com/?tab=model#/api-key String apiKey = System.getenv("DASHSCOPE_API_KEY"); if (apiKey == null) { System.out.println("DASHSCOPE_API_KEY not found in environment variables"); return; } // This is the Singapore region URL. Replace WorkspaceId with your actual workspace ID. URLs differ by region. String baseUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/embeddings"; HttpClient client = HttpClient.newHttpClient(); // Read the input file. StringBuilder inputText = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new FileReader("<path_to_your_content_root>"))) { String line; while ((line = reader.readLine()) != null) { inputText.append(line).append("\n"); } } catch (IOException e) { System.err.println("Error reading input file: " + e.getMessage()); return; } Map<String, Object> requestBody = new HashMap<>(); requestBody.put("model", "text-embedding-v4"); requestBody.put("input", inputText.toString().trim()); requestBody.put("dimensions", 1024); requestBody.put("encoding_format", "float"); try { String requestBodyString = JsonUtils.toJson(requestBody); // Build the HTTP request. HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(baseUrl)) .header("Content-Type", "application/json") .header("Authorization", "Bearer " + apiKey) .POST(HttpRequest.BodyPublishers.ofString(requestBodyString)) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() == 200) { System.out.println("Response: " + response.body()); } else { System.out.printf("Failed to retrieve response, status code: %d, response: %s%n", response.statusCode(), response.body()); } } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } } > If you use a model in the China (Beijing) region, you must use an API key from that region and replace the URL with https://dashscope.aliyuncs.com/compatible-mode/v1/embeddings. This is the Singapore region URL. Replace WorkspaceId with your actual workspace ID. URLs differ by region. > Replace 'texts_to_embedding.txt' with your file name or path. ```curl FILE_CONTENT=$(cat texts_to_embedding.txt |
modelstring required The name of the model to call. See the Model overview table for model names. | |
inputarray<string> or string or file required The input text to process. The input can be a string, an array of strings, or a file. If the input is a string, the maximum length is 8,192 tokens. If the input is a list of strings or a file, the maximum batch size is 10 items (lines), and each item (line) can contain up to 8,192 tokens. | |
dimensionsinteger optional The dimension of the output embedding vectors. Must be one of the following values: 2048 (for text-embedding-v4 only), 1536 (for text-embedding-v4 only), 1024, 768, 512, 256, 128, or 64. The default value is 1024. | |
encoding_formatstring optional The returned embedding format. Currently, only float is supported. |
| ### Response object | Successful response Error response json { "data": [ { "embedding": [ -0.0695386752486229, 0.030681096017360687, ... ], "index": 0, "object": "embedding" }, ... { "embedding": [ -0.06348952651023865, 0.060446035116910934, ... ], "index": 5, "object": "embedding" } ], "model": "text-embedding-v4", "object": "list", "usage": { "prompt_tokens": 184, "total_tokens": 184 }, "id": "73591b79-d194-9bca-8bb5-xxxxxxxxxxxx" } json { "error": { "message": "Incorrect API key provided. ", "type": "invalid_request_error", "param": null, "code": "invalid_api_key" } } |
dataarray A list of the resulting embedding objects. Property embeddinglist The embedding vector, returned as an array of floating-point numbers. indexinteger The index of the corresponding input text in the input array. object string The object type. The value is always embedding. | |
modelstring The name of the model used for this call. | |
object string The object type. The value is always list. | |
usageobject Property prompt_tokens integer The number of tokens in the input text. total_tokens integer The total number of tokens in the input. This count is determined by how the model's tokenizer parses the input string. | |
| id string A unique request identifier, used for tracing and troubleshooting. |
DashScope
base_url for SDK calls:
Singapore: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1. Replace
WorkspaceIdwith your actual workspace ID.China (Beijing): https://dashscope.aliyuncs.com/api/v1
China (Hong Kong): https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1. Replace
WorkspaceIdwith your actual workspace ID.
Endpoint for HTTP calls:
Singapore: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding. Replace
WorkspaceIdwith your actual workspace ID.China (Beijing): POST https://dashscope.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding
China (Hong Kong): POST https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding. Replace
WorkspaceIdwith your actual workspace ID.
Important
The legacy China (Hong Kong) URL https://cn-hongkong.dashscope.aliyuncs.com/api/v1 will be deprecated soon. Please migrate to the new URL https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1 as soon as possible.
Important
The legacy domain https://dashscope-intl.aliyuncs.com for the Singapore region will be deprecated soon. Please migrate to the new domain https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com as soon as possible.
| ### Request body | Input string Input string list Input file Python Java curl python import dashscope from http import HTTPStatus # This is the Singapore region URL. Replace WorkspaceId with your actual workspace ID. URLs differ by region. dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1' resp = dashscope.TextEmbedding.call( model=dashscope.TextEmbedding.Models.text_embedding_v4, input='A swift wind, a high sky, and the gibbons cry mournfully. A clear islet, white sand, and the birds fly back. Boundless rustling woods shed their leaves. The endless Yangtze River comes rolling in.', dimension=1024, output_type="dense&sparse" ) print(resp) if resp.status_code == HTTPStatus.OK else print(resp) ```java import java.util.Arrays; import java.util.concurrent.Semaphore; import com.alibaba.dashscope.common.ResultCallback; import com.alibaba.dashscope.embeddings.TextEmbedding; import com.alibaba.dashscope.embeddings.TextEmbeddingParam; import com.alibaba.dashscope.embeddings.TextEmbeddingResult; import com.alibaba.dashscope.exception.ApiException; import com.alibaba.dashscope.exception.NoApiKeyException; import com.alibaba.dashscope.utils.Constants; public final class Main { static { // This is the Singapore region URL. Replace WorkspaceId with your actual workspace ID. URLs differ by region. Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"; } public static void basicCall() throws ApiException, NoApiKeyException{ TextEmbeddingParam param = TextEmbeddingParam .builder() .model(TextEmbedding.Models.TEXT_EMBEDDING_V4) .texts(Arrays.asList("A swift wind, a high sky, and the gibbons cry mournfully.", "A clear islet, white sand, and the birds fly back.", "Boundless rustling woods shed their leaves.", "The endless Yangtze River comes rolling in.")).build(); TextEmbedding textEmbedding = new TextEmbedding(); TextEmbeddingResult result = textEmbedding.call(param); System.out.println(result); } public static void callWithCallback() throws ApiException, NoApiKeyException, InterruptedException{ TextEmbeddingParam param = TextEmbeddingParam .builder() .model(TextEmbedding.Models.TEXT_EMBEDDING_V3) .texts(Arrays.asList("A swift wind, a high sky, and the gibbons cry mournfully.", "A clear islet, white sand, and the birds fly back.", "Boundless rustling woods shed their leaves.", "The endless Yangtze River comes rolling in.")).build(); TextEmbedding textEmbedding = new TextEmbedding(); Semaphore sem = new Semaphore(0); textEmbedding.call(param, new ResultCallback<TextEmbeddingResult>() { @Override public void onEvent(TextEmbeddingResult message) { System.out.println(message); } @Override public void onComplete(){ sem.release(); } @Override public void onError(Exception err){ System.out.println(err.getMessage()); err.printStackTrace(); sem.release(); } }); sem.acquire(); } public static void main(String[] args){ try{ callWithCallback(); }catch(ApiException |
modelstring required The model to use. For a list of available models, see the Model overview table. | |
inputstring orarray<string> required The text to process. The input can be a string, an array of strings, or a file. A single string can be up to 8,192 tokens. A list of strings or a file can contain up to 10 items (lines), with each item up to 8,192 tokens. | |
text_typestring optional > When making an HTTP call, place text_type in the parameters object. Text converted to embeddings can be applied to downstream tasks such as retrieval, clustering, and classification. For asymmetric tasks such as retrieval, it is recommended to differentiate between query text (query) and document text (document) to achieve better retrieval performance. For symmetric tasks such as indexing, clustering, and classification, you can simply use the system default value of document. | |
dimensioninteger optional > When making an HTTP call, place dimension in the parameters object. Specifies the embedding dimension for the output vector. Valid values are 2048 (for text-embedding-v4 only), 1536 (for text-embedding-v4 only), 1024, 768, 512, 256, 128, or 64. Defaults to 1024. | |
output_typestring optional > When making an HTTP call, place output_type in the parameters object. Specifies the output vector type. This parameter applies only to the text-embedding-v3 and text-embedding-v4 models. Valid values are dense, sparse, and dense&sparse. Defaults to dense, which returns only the dense vector representation. | |
instructstring optional Provides custom instructions to guide the model in understanding the query intent. English instructions are recommended, as they typically improve performance by 1% to 5%. |
| ### Response object | Successful response Error response json { "status_code": 200, "request_id": "1ba94ac8-e058-99bc-9cc1-7fdb37940a46", "code": "", "message": "", "output":{ "embeddings": [ { "sparse_embedding":[ {"index":7149,"value":0.829,"token":"swift"}, ..... {"index":111290,"value":0.9004,"token":"mournfully"}], "embedding": [-0.006929283495992422,-0.005336422007530928, ...], "text_index": 0 }, { "sparse_embedding":[ {"index":246351,"value":1.0483,"token":"islet"}, ..... {"index":2490,"value":0.8579,"token":"back"}], "embedding": [-0.006929283495992422,-0.005336422007530928, ...], "text_index": 1 }, { "sparse_embedding":[ {"index":3759,"value":0.7065,"token":"Boundless"}, ..... {"index":1130,"value":0.815,"token":"leaves"}], "embedding": [-0.006929283495992422,-0.005336422007530928, ...], "text_index": 2 }, { "sparse_embedding":[ {"index":562,"value":0.6752,"token":"endless"}, ..... {"index":1589,"value":0.7097,"token":"in"}], "embedding": [-0.001945948973298072,-0.005336422007530928, ...], "text_index": 3 } ] }, "usage":{ "total_tokens":27 } } json { "code":"InvalidApiKey", "message":"Invalid API-key provided.", "request_id":"xxxxxxxx" } |
status_codestring The HTTP status code. A value of 200 indicates success. | |
request_idstring A unique identifier for the request. Use this ID to trace and troubleshoot the request. | |
codestring The error code returned if the request fails. This field is empty for successful requests. | |
messagestring A detailed error message if the request fails. This field is empty for successful requests. | |
outputobject The result of the task. Properties embeddingsarray The model's output for the request. This is an array of objects, with each object corresponding to an input text. Properties sparse_embeddingarray The sparse vector representation of the corresponding string. This applies only to text-embedding-v3 and text-embedding-v4. Properties indexinteger The index of the token in the vocabulary. valuefloat Indicates the weight or importance score of the Token. The higher the value, the greater the importance or relevance of the Token in the current text context. tokenstring The text of the token. embeddingarray The dense vector representation for the corresponding string. text_indexinteger The index of the corresponding text in the input array. | |
usageobject Properties total_tokens integer The number of tokens in the input, as calculated by the model's tokenizer. |
Error codes
If a model call fails, see Error Messages.
Previous: Voice cloningNext: Multimodal embeddings
Is this page helpful?
Model overview
Prerequisites
OpenAI compatibility
Request body
Response object
DashScope
Request body
Response object
Error codes
Contact Us
Sales Support
Live-chat with our sales team or get in touch with a business development professional in your region.
Contact Sales
Technical Support
Open a ticket and get quick help from our technical team.
Open a Ticket >
Connect & Report Abuse
We look forward to your suggestion.
Post a Suggestion > Report Abuse >
\ \ Hi, I'm Alibaba Cloud AI Assistant!\ \ I can help with questions and solutions.
Why Alibaba Cloud
About Alibaba Cloud
Asia Accelerator
Our Global Network
Global Offices
Trust Center
Case Studies
Analyst Reports
Products & Pricings
Pricing Calculator
ECS
SAS
Model Studio
Database
Security
SMS
Solutions
Financial Services
Retail Services
Media Services
Gaming Services
ISV Solutions
Engage
Developer Community
Partner Network
Startups
Marketplace
Join Alibaba Cloud
Resources & Support
Developer Learning Hub
Documentation Center
Training & Certification
Service Notices
Submit a Ticket
Security Report
Qwen Cloud
Careers About Us Privacy Policy Legal Integrity Compliance Reporting Channel Service Notices Links
© 2009-2026 Copyright by Alibaba Cloud All rights reserved
- YouTube
- TikTok
- contact.us@alibabacloud.com
- Call Us Now
- Discord
© 2009-2026 Copyright by Alibaba Cloud All rights reserved
Careers About Us Privacy Policy Legal Integrity Compliance Reporting Channel Service Notices Links