RDS for PostgreSQL offers the rds_ai extension, which integrates advanced models from Alibaba Cloud Model Studio, including Qwen, text embedding, and text rerank. This extension enables a wide range of applications, such as LLM-based Q&A, text-to-vector conversion, text rerank, top-N similar vector retrieval, and Retrieval-Augmented Generation (RAG). In addition, rds_ai supports custom models, allowing you to add models to build diverse AI applications.
Join the RDS for PostgreSQL DingTalk group (ID: 103525002795) for support, discussions, and feedback about the extension.
Prerequisites
-
Ensure your RDS for PostgreSQL instance meets the version requirements in the following table:
Major version
Minor version
PostgreSQL 16
20241230 or later
PostgreSQL 14, PostgreSQL 15, and PostgreSQL 17
20250430 or later
PostgreSQL 18
20251130 or later
To update the minor engine version, see Update the minor engine version.
-
You must have a privileged account for your RDS for PostgreSQL instance. For more information, see Create an account.
-
The model used in this document is provided by Alibaba Cloud Model Studio. You must first activate the service and obtain an API key. For more information, see Get an API key.
Network configuration
By default, an RDS PostgreSQL instance cannot access external networks. To enable access to external models, you must either use PrivateLink to connect your VPC to Model Studio, or configure a NAT Gateway for the instance's VPC.
-
Connect over PrivateLink
Accessing Model Studio over a private connection enhances data security and transfer efficiency. You can use PrivateLink to connect your VPC to Model Studio. For details, see Access model and application APIs in Model Studio over a private network.
-
Connect over a public network
Alternatively, you can configure a NAT Gateway for the VPC hosting your RDS PostgreSQL instance. For more information, see Use the SNAT feature of a public NAT gateway to access the internet.
Create and drop extensions
Before you install an extension, ensure that your RDS for PostgreSQL instance is running a major and minor version that supports it. For more details, see prerequisites in this topic.
-
Install an extension on the Plug-ins page.
-
Go to the Instances page, select a region at the top, and then click the ID of the target instance.
-
In the navigation pane on the left, click Plug-ins.
-
On the Extension Marketplace tab, find the rds_ai extension and click Install.
-
In the dialog box, select the target database and account, and then click Install.
(Optional) On the Extension Management page, you can uninstall extensions from the Installed Extensions tab.
-
-
Manage extensions with SQL statements
Create an extension
CREATE EXTENSION IF NOT EXISTS rds_ai CASCADE;Note-
Only a privileged account can execute this statement. To create a privileged account, see Create an account.
-
Creating the rds_ai extension also creates the pgvector and pgsql-http extensions.
-
To view all installed extensions, execute the
SELECT * FROM pg_extension;statement.
Drop an extension
DROP EXTENSION rds_ai; -
Default models
The rds_ai extension supports the default models listed below. You can also create custom models.
|
API |
Parameter |
Type |
Default |
|
prompt API |
rds_ai.default_prompt_model |
enum |
|
|
rank API |
rds_ai.default_rerank_model |
enum |
gte-rerank |
|
embedding API |
rds_ai.default_embed_model |
enum |
text-embedding-v3 |
To change a default model, you must add rds_ai to the Running Value of the shared_preload_libraries instance parameter. For more information about how to configure parameters, see Set instance parameters. For example, change the Running Value to 'pg_stat_statements,auto_explain,rds_ai'.
The default models in the rds_ai extension provide the following capabilities:
Basic settings
-
To call a large language model using rds_ai, you must first configure the API key.
-- Set the API key for the target model. SELECT rds_ai.update_model('qwen-plus', 'token', 'sk-****'); -- Set the API key for all models in rds_ai.model_list. SELECT rds_ai.update_model(model_name,'token','sk-****') FROM rds_ai.model_list; -
The rds_ai extension uses the pgsql-http extension to remotely call models. Configure the following timeout settings to interrupt long-running requests.
NoteThese timeout settings are session-level and must be reconfigured for each new connection.
-- Set the request timeout period in milliseconds. SET http.timeout_msec TO 200000; SELECT http.http_set_curlopt('CURLOPT_TIMEOUT', '200000'); -- Set the connection timeout period. SELECT http.http_set_curlopt('CURLOPT_CONNECTTIMEOUT_MS', '200000'); -
(Optional) If you use PrivateLink to connect the VPC of your RDS for PostgreSQL instance to Alibaba Cloud Model Studio, run the following statement to update the URL of the target model.
SELECT rds_ai.update_model('qwen-plus', 'uri', '<URL_after_connecting_via_PrivateLink>');After you connect the VPC of your RDS for PostgreSQL instance to Alibaba Cloud Model Studio over PrivateLink, see Access model or application APIs of Alibaba Cloud Model Studio over a private network for the model URLs. For example, if your VPC is in the China (Beijing) region, replace the public domain name
dashscope.aliyuncs.cominhttps://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generationwith your custom service domain name, such asvpc-cn-beijing.dashscope.aliyuncs.com.The following SQL statement provides an example of how to update the URLs for multiple models:
SELECT rds_ai.update_model( model_name, 'uri', 'https://vpc-cn-beijing.dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation' ) FROM rds_ai.model_list WHERE model_name IN ('qwen-max', 'qwen-turbo', 'qwen-plus');
LLM-based Q&A
By default, the rds_ai extension uses the Qwen text generation model for LLM-based Q&A.
-
(Optional) Set the default model for LLM-based Q&A. If you do not set this parameter, the system uses the
qwen-plusmodel by default.NoteTo change a default model, you must add
rds_aito the Running Value of the shared_preload_libraries instance parameter. For more information about how to configure parameters, see Set instance parameters. For example, change the Running Value to'pg_stat_statements,auto_explain,rds_ai'.SET rds_ai.default_prompt_model TO 'qwen-max'; -
Use
rds_ai.promptto call the default large language model for Q&A. For example:SELECT rds_ai.prompt('Give me a recipe for a dish made with carrots, potatoes, and eggplants.');Full API call:
SELECT rds_ai.prompt( model_name=>'qwen-plus', -- The model name. content=>'Give me a recipe for a dish made with carrots, potatoes, and eggplants.', -- The question. args=>'{"top_p": 0.7}'::jsonb -- The parameters for calling the large language model. );
Text-to-vector conversion
By default, the rds_ai extension uses the text-embedding-v3 model for text-to-vector conversion.
-
By default, the output is a dense vector.
SELECT rds_ai.embed( 'On the wind-swept plain, gibbons cry; the islet is clear, the sand is white, birds wheel back. Leaves fall without end; the Yangtze rolls on, never ceasing.' -- The text to convert to a vector. ); -
Specify the output as a sparse vector.
-- Convert text to a sparse vector, which has 250002 dimensions by default. SELECT rds_ai.embed( content=>'On the wind-swept plain, gibbons cry; the islet is clear, the sand is white, birds wheel back. Leaves fall without end; the Yangtze rolls on, never ceasing.', args=>'{"output_type": "sparse"}'::jsonb -- The parameter list. );
Store the resulting vectors in a destination table.
-
Create the test_embed table.
CREATE TABLE test_embed(a text, b vector(1024), c sparsevec(250002)); -
Insert the text that you want to convert.
INSERT INTO test_embed (a) values ('hello world'); -
Use
rds_ai.embedto call thetext-embedding-v3model and write the results to the test_embed table.-
Write a dense vector.
UPDATE test_embed SET b = rds_ai.embed(a, '{"output_type": "dense"}'::jsonb)::vector; -
Write a sparse vector.
UPDATE test_embed SET c = rds_ai.embed(a, '{"output_type": "sparse"}'::jsonb)::sparsevec;
-
Text ranking
By default, the rds_ai extension uses the gte-rerank model for text ranking.
Use rds_ai.rank to call the gte-rerank model for ranking.
-- Call the default text ranking model gte-rerank.
SELECT * FROM rds_ai.rank
(
'What is a text ranking model?', -- The query.
ARRAY[
'Text ranking models are widely used in search engines and recommendation systems. They rank candidate texts based on relevance.',
'Quantum computing is a cutting-edge area of computer science.',
'The development of pretrained language models has brought new advances to text ranking models.'
]
);
Full API call:
SELECT * FROM rds_ai.rank
(
query=>'who are you',
document=>ARRAY['a','b','c'],
args=>'{"top_n":2}'::jsonb
);
Top-N similar vector retrieval
By default, the rds_ai extension uses the text-embedding-v3 model for similar vector retrieval. For example:
-
Create a test table.
-- Create a test table named test_rag. CREATE TABLE test_rag ( id SERIAL PRIMARY KEY, chunk TEXT ); -- Add an embedding column to store the vector converted from the chunk. ALTER TABLE test_rag ADD COLUMN embedding VECTOR(1024); -- Populate the embedding column. UPDATE test_rag SET embedding=rds_ai.embed(chunk)::vector; -
Create a vector index.
NoteWhen you create a vector index, you must use the vector_cosine_ops operator class.
-- Create an HNSW index. CREATE INDEX ON test_rag USING hnsw (embedding vector_cosine_ops); -- Create an IVFFlat index. CREATE INDEX ON test_rag USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100); -
Use
rds_ai.retrieve, which calls thetext-embedding-v3model, to perform vector retrieval in the test table.SELECT * FROM rds_ai.retrieve ('Why is PostgreSQL considered the most advanced open source database', 'public', 'test_rag', 'chunk', 'embedding');Full API call:
SELECT * FROM rds_ai.retrieve ( embed_model=>'text-embedding-v3', -- The embedding model to use. question=>'Why is PostgreSQL considered the most advanced open source database', source_schema=>'public', -- The schema of the table for the similarity search. source_table=>'test_rag', -- The table for the similarity search. chunk_col=>'chunk', -- The column that contains text chunks. vector_col=>'embedding', -- The column that contains vectors. -- The following are optional parameters. topn=>10, -- The number of top results to return. embed_args=>'{}'::jsonb, -- The parameters for the embedding model. distance_type=>'cosine' -- The distance algorithm. Valid values: L1, L2, cosine, and inner product. );
RAG-based Q&A
By default, the rds_ai extension uses the text-embedding-v3 model and the Qwen text generation model for RAG-based Q&A.
-- Embedding model: text-embedding-v3. Text generation model: specified by the rds_ai.default_prompt_model parameter.
SELECT * FROM rds_ai.rag
('Why is PostgreSQL considered the most advanced open source database',
'public', 'test_rag', 'chunk', 'embedding');
Full API call:
SELECT * FROM rds_ai.rag
(
embed_model=>'text-embedding-v3', -- The embedding model to use.
prompt_model=>'qwen-plus', -- The prompt model to use.
question=>'Why is PostgreSQL considered the most advanced open source database',
source_schema=>'public', -- The schema of the table for the similarity search.
source_table=>'test_rag', -- The table for the similarity search.
chunk_col=>'chunk', -- The column that contains text chunks.
vector_col=>'embedding', -- The column that contains vectors.
-- The following are optional parameters.
topn=>10,
embed_args=>'{}'::jsonb, -- The parameters for the embedding model.
prompt_args=>'{}'::jsonb, -- The parameters for the prompt model.
distance_type=>'L2' -- The distance algorithm. Valid values: L1, L2, cosine, and inner product.
);
Custom models
If you have any issues adding a custom model, please contact us.
You can add a custom model using the rds_ai.model_list metadata table. The following table describes the fields in rds_ai.model_list.
|
Parameter |
Type |
Description |
|
model_name |
name |
The name of the model. This field is the primary key. |
|
request_type |
text |
The HTTP request method, such as POST. |
|
request_header |
http.http_header[] |
The request header contains information such as authentication credentials. This data type is provided by the pgsql-http extension. |
|
uri |
text |
The endpoint URL of the model. |
|
content_type |
text |
The content type of the request, such as application/json. |
|
content_template |
text |
The template for the request body. It can contain placeholders that are populated when you invoke the model. |
|
json_path |
text |
An SQL statement used to parse the HTTP response and extract the required content. |
|
token |
text |
The authentication token included in the request header. |
Add a custom model
SELECT rds_ai.add_model(
'test-model', -- Model name
'POST', -- HTTP request method
ARRAY[('Authorization', 'Bearer %s')]::http.http_header[], -- Request header
'https://****.com', -- Request URL
'application/json', -- Content type
'{"key":"%s"}', -- Request body template
'SELECT %L' -- SQL statement to parse the response
);
Use a custom model
-
Use the rds_ai.raw_invoke_model function to send a request based on the model's configuration. The function populates the request template with an ARRAY and returns the complete HTTP response.
SELECT * FROM rds_ai.raw_invoke_model('qwen-plus', ARRAY['who are you']); -
Use the rds_ai.invoke_model function to send a request based on the model's configuration and extract specific fields from the response using the
json_pathsetting.SELECT * FROM rds_ai.invoke_model('qwen-plus', ARRAY['who are you']);
Delete a custom model
SELECT rds_ai.del_model('test-model');
Add a DeepSeek model
You can invoke DeepSeek models through Alibaba Cloud Model Studio.
-
Obtain the endpoint URL for the DeepSeek model. The default public endpoint is https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions.
NoteIf you connect to Alibaba Cloud Model Studio from your RDS for PostgreSQL instance's VPC using PrivateLink, replace the public domain name with the custom domain name of the PrivateLink endpoint. For example, if the VPC is in the China (Beijing) region, change the DeepSeek model URL to https://vpc-cn-beijing.dashscope.aliyuncs.com/compatible-mode/v1/chat/completions.
-
Activate Alibaba Cloud Model Studio and get an API key. For more information, see Get an API key.
-
Add the DeepSeek model. When adding the model, use the
%splaceholder for the model name and content. This lets you specify different DeepSeek models during invocation.SELECT rds_ai.add_model( 'deepseek', -- Model name 'POST', -- Request method ARRAY[('Authorization', '%s')]::http.http_header[], -- Request header 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions', -- Request URL 'application/json', -- Content type '{ "model": "%s", "messages": [ { "role": "user", "content": "%s" } ] }', -- Request body 'SELECT (%L::jsonb->''choices''-> 0->''message''->''content'')::text' -- Parse path ); -
Configure the API key.
SELECT rds_ai.update_model('deepseek', 'token','sk-1a19fe7d73c240cca2192473e8a5****');
Verify the new DeepSeek model. For example:
SELECT rds_ai.invoke_model(
'deepseek',
ARRAY[
'deepseek-r1',
'Introduce yourself'
]
);
This example uses deepseek-r1. You can use other DeepSeek models based on your requirements. For a list of supported DeepSeek models, see DeepSeek-Alibaba Cloud.
Add a PAI-RAG model
We recommend deploying PAI-EAS and your RDS for PostgreSQL instance in the same VPC. When you configure the model in the rds_ai extension, use the VPC endpoint of the PAI service. This keeps all communication within your VPC for enhanced security.
-
Deploy a RAG service in PAI-EAS. For more information, see Deploy an LLM-based RAG chatbot by using PAI-EAS and RDS for PostgreSQL.
-
Obtain the invocation information for the RAG service.
-
Click the name of the RAG service to open the Service Details page.
-
In the Basic Information section, click View Invocation Information.
-
In the Invocation Information dialog box, obtain the service endpoint and token.
-
-
Add the PAI-RAG model.
SELECT rds_ai.add_model( 'pai-rag', -- Model name 'POST', -- Request method ARRAY[('Authorization','%s')]::http.http_header[], -- Request header, 'http://rds-pai-rag-demo.****.cn-hangzhou.pai-eas.aliyuncs.com/service/query', -- Request URL 'application/json', -- Content type '{ "question": "%s" }', -- Request body 'SELECT (%L::jsonb->''answer'')::text' -- Parse path );Note-
Replace the model URL with your actual service endpoint and append
/service/query. -
For more information about invoking PAI-RAG models, see Call PAI models by using an API.
-
-
Configure the token for the PAI-RAG model.
SELECT rds_ai.update_model('pai-rag', 'token','MTFkYjMwZjgzYzA1YmE2N2YyNWMxM2NkNDVjMjEzNjYxMDAzMzE5****');
Verify the new PAI-RAG model. For example:
SELECT rds_ai.invoke_model('pai-rag', ARRAY['Which parameters are related to WAL log accumulation?']);
Add a Function Compute RAG model
-
Deploy an AgentCraft application in Function Compute. For more information, see Deploy AgentCraft in the cloud.
-
Create an agent and configure its client access.
For example, as described in Connect an agent to a DingTalk chatbot, obtain and save the service endpoint and token when you configure client access.
-
Add the Function Compute RAG model.
SELECT rds_ai.add_model( 'fc-rag', -- Model name 'POST', -- Request method ARRAY[('Authorization','Bearer %s')]::http.http_header[], -- Request header, 'https://agentcrckend-de-obnhjsknam.cn-hangzhou.fcapp.run/v1/chat/completions', -- Request URL 'application/json', -- Content type '{ "messages":[ { "role": "user", "content": "%s" } ], "stream": false, "max_tokens": 1024 }', 'SELECT (%L::jsonb->''choices''->0->''message''->>''content'')::text' -- Parse path );NoteReplace the model URL with the actual URL and append
/completions. -
Configure the token for the Function Compute RAG model.
SELECT rds_ai.update_model('fc-rag', 'token','8UiGAziWgYGPxM3qR5sAChBfDJRt****');
Verify the new Function Compute RAG model. For example:
SELECT rds_ai.invoke_model('fc-rag', ARRAY['Which parameters are related to WAL log accumulation?']);
Add the text-embedding-v2 model
-
Obtain the endpoint URL for the text-embedding-v2 model. The default public endpoint is https://dashscope.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding.
NoteIf you connect to Alibaba Cloud Model Studio from your RDS for PostgreSQL instance's VPC using PrivateLink, replace the public domain name with the custom domain name of the PrivateLink endpoint. For example, if the VPC is in the China (Beijing) region, change the text-embedding-v2 model URL to https://vpc-cn-beijing.dashscope.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding.
-
The text-embedding-v2 model is provided by Alibaba Cloud Model Studio. Activate the service and get an API key. For more information, see Get an API key.
-
Add the text-embedding-v2 model.
SELECT rds_ai.add_model( 'text-embedding-v2-self', -- Model name 'POST', -- Request method ARRAY[('Authorization','Bearer %s')]::http.http_header[], 'https://dashscope.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding', -- Request URL 'application/json', -- Content type '{ "model": "text-embedding-v2", "input": {"texts": ["%s"]}, "parameters": %s }', -- Request body 'SELECT %L::jsonb' -- Parse path );NoteFor more information about invoking the text-embedding-v2 model, see text and multimodal embedding.
-
Configure the API key.
SELECT rds_ai.update_model('text-embedding-v2-self', 'token','sk-1a19fe7d73c240cca2192473e8a5****');
Verify the new text-embedding-v2 model. For example:
SELECT rds_ai.invoke_model(
'text-embedding-v2-self', -- Custom model name
ARRAY['The wind is swift, the sky is high, and the apes wail','{"text_type":"query"}'] -- The array elements sequentially replace the %s placeholders. The token is automatically added to the header and does not need to be specified.
);