Build a RAG Q&A application for finance and healthcare

Updated at:

Retrieval-Augmented Generation (RAG) connects large language models (LLMs) to private knowledge bases, improving response accuracy with domain-specific data. This guide walks you through developing and deploying a RAG application in LangStudio.

Background

RAG models combine information retrieval with generative AI to deliver more precise, contextually relevant answers. In domains like finance and healthcare, where accurate information drives critical decisions, traditional generative models may lack the required domain-specific knowledge. RAG bridges this gap by connecting models to external knowledge bases. This guide walks through a RAG solution for finance and healthcare built on Platform for AI (PAI).

Prerequisites

  • LangStudio supports Faiss and Milvus as vector databases. If you want to use Milvus, you must first create a Milvus instance. For more information, see Create a Milvus instance and Instance management.

    Note

    Faiss is suitable for test environments and requires no additional database setup. For production, use Milvus, which supports larger-scale data.

  • The corpus for your RAG knowledge base must be uploaded to OSS. The following sample corpora are provided for finance and healthcare use cases:

    • Financial News: Data in PDF format, containing news reports from public news websites.

    • Disease Introductions: Data in CSV format, containing disease information from Wikipedia.

1. (Optional) Deploy LLM and embedding models

A RAG application flow requires both an LLM service and an embedding model service. You can deploy the required services from the Model Gallery as described below, or skip this step if you already have OpenAI API-compatible model services.

Go to QuickStart > Model Gallery and deploy models for the following two scenarios. For details, see Model deployment and training.

Important

Select an instruction-tuned large language model. Base models cannot reliably follow user instructions.

  • For the Scenario, select Large Language Models and deploy DeepSeek-R1-Distill-Qwen-7B.

  • For the Scenario, select embedding and deploy the bge-m3 general vector model.

2. Create connections

The LLM and embedding model connections in this section use EAS services deployed from QuickStart > Model Gallery. For other connection types, see Configure connections.

2.1 Create an LLM service connection

In LangStudio, select a workspace, navigate to the Configure Service Connection > Model Service tab, and click New Connection to create a generic LLM model service connection.

Key parameters:

Parameter

Description

Model name

If you deployed the model from the Model Gallery, find the model name on its details page by clicking the model card on the Model Gallery page. For details, see Create a connection - Model Service.

Service provider

  • PAI-EAS model service: This topic uses a PAI-EAS model service. For the EAS Service parameter, select the LLM service that you deployed in 1. (Optional) Deploy an LLM and an embedding model. When you select the service, the base_url and api_key fields are automatically populated with the VPC endpoint and token of the deployed LLM service.

  • Third-party model service: For a third-party service such as the official DeepSeek service, the base_url is https://api.deepseek.com. You can obtain the api_key from the DeepSeek official website.

2.2 Create an embedding model service connection

Create a generic embedding model service connection, following the same procedure as in Step 2.1.

On the New Connection page, set the connection type to General Embedding Model Service and select the PAI-EAS Model Service tab as the service provider. Then configure the following parameter settings:

  • EAS Service: select the deployed EAS embedding model service instance.

  • Model name: enter default.

  • base_url: the endpoint of the EAS service.

  • api_key: the API key of the EAS service.

2.3 Create a vector database connection

On the Configure Service Connection > Database tab, click New Connection to create a Milvus database connection.

Key parameters:

Parameter

Description

uri

The Milvus instance endpoint in the format http://<Milvus internal endpoint>. For example, http://c-b1c5222fba****-internal.milvus.aliyuncs.com.

You can obtain the internal endpoint from the details page of your Milvus instance in the Alibaba Cloud console.

token

The username and password for the Milvus instance: <yourUsername>:<yourPassword>.

database

The name of the database. This topic uses the default database default.

3. Create a knowledge base index

Create a knowledge base index. LangStudio parses the corpus, chunks and vectorizes it, and stores the results in the vector database. The following table describes key parameters. For other configurations, see Manage knowledge bases.

Parameter

Description

Basic configurations

Data source OSS path

Set this parameter to the OSS path of the RAG knowledge base corpus described in Prerequisites.

Output OSS path

Specify a path to store intermediate results and index metadata from document parsing.

Important

If you use Faiss as the vector database, the application flow saves the generated index files to OSS. By default, if you use the default PAI role (the Instance RAM Role set when you start the runtime), the application flow has access to your workspace's default storage bucket. Therefore, we recommend setting this parameter to a directory in the OSS bucket that contains the current workspace's default storage path. If you use a custom role, grant it OSS access permissions. We recommend the AliyunOSSFullAccess permission. For more information, see Manage permissions for a RAM role.

Embedding model and database

Embedding type

Select General Embedding Model.

Embedding connection

Select the embedding model service connection that you created in Step 2.2.

Vector database type

Select Vector database Milvus.

Vector database connection

Select the Milvus database connection that you created in Step 2.3.

Table name

Set this parameter to the name of the Collection that you created in your Milvus database, as described in Prerequisites.

VPC configuration

VPC configuration

Select a VPC that is the same as, or can communicate with, the VPC of the Milvus instance.

4. Create and run a RAG application flow

  1. Go to LangStudio, select a workspace, and then on the Application Flow tab, click New Application Flow to create a RAG application flow.

  2. Start the runtime. In the upper-right corner, click Create Runtime and configure the parameters. Note: The runtime must be running before you can parse Python nodes or access more tools.

    Key parameter:

    VPC Configuration: Select the VPC that was used to create the Milvus instance in Prerequisites, or ensure that the selected VPC can communicate with the Milvus instance's VPC.

  3. Develop the application flow.

    image

    Keep the default settings for other nodes or adjust them as needed. Configure the key nodes as follows:

    • Knowledge Retrieval: Retrieves text from the knowledge base relevant to the user's question.

      • Knowledge base index name: Select the knowledge base index that you created in Step 3.

      • Top K: Returns the top K matching results.

    • LLM node: Uses the retrieved documents as context, sends them to the large language model along with the user's question, and generates a response.

      • Model configuration: Select the connection that you created in Step 2.1.

      • Chat history: Specifies whether to enable chat history and use past conversations as input variables.

    For details about each component, see Pre-built Component Library.

  4. Debug or run the flow. In the upper-right corner, click Run to execute the flow. For information about common runtime issues, see FAQ.

  5. View the traces. Below the generated answer, click View Traces to view the trace details or topology.

5. Deploy the application flow

On the application flow development page, click Deploy in the upper-right corner to deploy the application flow as an EAS service. Keep other deployment settings as default or adjust them as needed. Configure the following key parameters:

  • Resource deployment > Instances: Configure the number of service instances. This deployment is for testing purposes, so set the number of instances to 1. For production, we recommend using multiple service instances to mitigate the risk of a single point of failure (SPOF).

  • VPC > VPC: Select the VPC where the Milvus instance resides, or ensure that the selected VPC can communicate with the VPC where the Milvus instance resides.

For more deployment details, see Deploy an application flow.

6. Call the service

After deployment, you are redirected to the PAI-EAS console. On the Debug tab, configure and send a request. The key in the request body must match the "Dialogue input" parameter in the "Start" node of the application flow. This guide uses the default field question.

In the request configuration area, select the POST method and enter the request body as raw JSON, for example:

{"question": "What is the share price of NVIDIA"}

Click Send Request. The Response area on the right returns status code 200 together with a JSON response that contains the share price information retrieved through the knowledge base index.

For other methods of calling the service, such as using an API, see Call the service.

Appendix: Case comparison

The following examples compare results with and without RAG for finance and healthcare tasks. Red highlights indicate factual errors or imprecise answers. Green highlights show correct RAG-enhanced answers.

Finance

Task 1: Investment risk analysis

Question: Based on the latest news reports, analyze the current investment risk in the U.S. technology sector. Is there a bubble? Please provide a specific "yes" or "no" answer.

Response from DeepSeek-R1-Distill-Qwen-7B

image

Response from DeepSeek-R1-Distill-Qwen-7B + RAG

Yes. Based on the latest news reports, the U.S. technology sector is fairly likely to be in a bubble.

The main evidence is as follows:

1. High valuations: share prices of many technology companies sit at historical highs, and the market has overestimated the optimistic outlook for their future growth potential. Once market sentiment shifts, share prices may fall sharply.
2. Surging capital expenditure: technology companies are investing heavily in fields such as artificial intelligence and cryptocurrency. Returns in these high-risk fields are highly uncertain, which increases financial pressure.
3. Market volatility: the recent wave of layoffs and share price swings show that the market is repricing the technology sector, and such volatility is an important signal of a market bubble.
4. Policy uncertainty: regulatory policy changes worldwide affect technology companies, increase market uncertainty, and may push the bubble closer to bursting.
5. Economic environment: the current uncertainty of the global economy, including rising interest rates and slowing growth, may all weigh on the technology sector.

In summary, the U.S. technology sector currently does carry a fairly high probability of being in a bubble. Investors should remain cautious and adopt corresponding risk management measures.

Task 2: Industry trend analysis

Question: Based on the latest news reports, determine whether the outlook for the real estate industry is optimistic.

Response from DeepSeek-R1-Distill-Qwen-7B

Assessing the real estate industry requires reference to the most recent news reports and data. I can, however, offer a general analytical framework based on current trends to help you evaluate the outlook for the sector.

1. Macroeconomic environment: economic growth, the inflation rate, and interest rate levels directly affect the property market. Economic growth usually lifts property demand, whereas high inflation and rising interest rates may suppress home-buying demand.
2. Policy regulation: government measures such as purchase restrictions, lending restrictions, and changes in land supply policy all affect supply and demand as well as the investment climate.
3. Market demand: urbanization, changes in population structure, and household income levels shape long-term demand for property.
4. Technological progress and innovation: new technologies such as green buildings and smart homes may change the form and function of property products and influence purchase decisions.
5. International environment: the global economic situation and international trade conditions may indirectly affect the domestic property market.
6. Market confidence: confidence among investors and consumers is one of the key factors. If the market broadly expects property prices to rise, more investment tends to follow, and the reverse also holds.

Because I cannot access the latest news reports, consult recent economic reports, official statistics, and research published by professional analysis institutions for a more accurate assessment of the sector's outlook. Government policy documents are also worth following for the latest policy direction and regulatory measures.

Response from DeepSeek-R1-Distill-Qwen-7B + RAG

image

Task 3: Trade situation analysis

Question: What has been the situation of China's goods trade imports and exports over the past 10 months?

Response from DeepSeek-R1-Distill-Qwen-7B

image

Response from DeepSeek-R1-Distill-Qwen-7B + RAG

image

Healthcare

Task 1: Treatment recommendations

Question: A 40-year-old female patient has a long-term history of systemic lupus erythematosus. Based on relevant medical knowledge, please provide personalized treatment recommendations.

Response from DeepSeek-R1-Distill-Qwen-7B

For a 40-year-old female patient diagnosed with systemic lupus erythematosus (SLE), treatment is usually individualized, because the symptoms and severity of SLE vary widely between patients. The goals of treatment are to control inflammation, relieve symptoms, prevent organ damage, and improve quality of life. Basic treatment recommendations include the following.

Drug therapy:

Non-steroidal anti-inflammatory drugs (NSAIDs): used to relieve mild pain and inflammation.

Glucocorticoids: for example prednisone, used to control acute inflammation and severe symptoms. Long-term use may cause side effects, so the dose must be adjusted with care.

Immunosuppressants: for example cyclophosphamide and methotrexate, used when disease activity is high, especially when glucocorticoids are not effective enough.

Antimalarial drugs: for example hydroxychloroquine, which can control skin and joint symptoms.

Biologic agents: for some patients who respond poorly to conventional therapy, biologic agents may need to be considered.

Lifestyle adjustments:

Avoid direct sunlight: ultraviolet light can trigger or aggravate SLE symptoms, so prolonged sun exposure should be avoided.

Healthy diet: eat a balanced diet and maintain a healthy body weight.

Moderate exercise: helps improve physical condition and mood, but excessive fatigue should be avoided.

Stop smoking and limit alcohol: tobacco and alcohol may aggravate the condition.

Regular follow-up: undergo blood tests and other necessary medical examinations regularly so that the treatment plan can be adjusted in time.

Psychological support: SLE can place considerable psychological pressure on patients, so appropriate psychological support and counseling are very important.

These recommendations are for reference only. The specific treatment plan should be drawn up by a rheumatology specialist according to the actual condition of the patient. Because every patient differs, treatment plans also differ, so working closely with the attending physician to decide on the most suitable plan is strongly recommended.

Response from DeepSeek-R1-Distill-Qwen-7B + RAG

For a 40-year-old patient with systemic lupus erythematosus (SLE), an individualized treatment plan must account for the specific symptoms, the level of disease activity, and whether organ damage or complications are present. Recommendations include the following.

1. Regular monitoring and assessment: perform lung function tests and assess respiratory symptoms regularly so that lung damage can be detected and treated early. Test immune markers such as antinuclear antibodies regularly so that the treatment plan can be adjusted sooner.
2. Drug therapy: choose drugs according to disease activity. If the condition is relatively stable, non-steroidal anti-inflammatory drugs (NSAIDs) may be enough to control symptoms. If the disease is more active, glucocorticoids and immunosuppressants such as hydroxychloroquine, methotrexate, or mycophenolate mofetil may be required. Patients with severe complications such as lupus nephritis or neuropsychiatric lupus may need more potent immunosuppressants or biologic agents.
3. Lifestyle advice: advise the patient to avoid excessive sun exposure, because ultraviolet light may trigger or aggravate the condition. Also encourage the patient to stop smoking, exercise moderately, and maintain a healthy lifestyle.
4. Regular re-examination: a high resolution computed tomography (HRCT) scan every six to twelve months, together with lung function monitoring, is recommended so that early signs of lung damage can be found and treated in time.
5. Nutrition and support: encourage adequate intake of vitamins and minerals, especially vitamin D, to maintain overall health. Provide psychological support and counseling to help the patient cope with the stress and emotional burden of the disease.

These recommendations are for reference only. The specific treatment plan should be drawn up by a specialist physician based on the detailed medical history and physical examination results.

Task 2: Assisted diagnosis

Question: A 30-year-old male patient recently experienced severe vision loss in his right eye, with blurred vision and double vision, accompanied by limb weakness and ataxia. Based on relevant medical knowledge, diagnose the possible condition and recommend a hospital department for treatment.

Response from DeepSeek-R1-Distill-Qwen-7B

Sample response: from the symptoms the patient describes, the model derives five possible diagnoses, namely optic neuritis, cerebrovascular accident, multiple sclerosis, an intracranial tumor, and other neurological disorders such as Guillain-Barre syndrome. It then suggests the hospital departments to visit, including neurology, ophthalmology, neurosurgery, and rehabilitation medicine, and the further examinations to arrange, including an MRI scan, a visual evoked potential (VEP) test, blood tests, and a lumbar puncture. It closes by advising the patient to go to the hospital emergency department immediately.

Response from DeepSeek-R1-Distill-Qwen-7B + RAG

image

Task 3: Disease early warning

Question: What are the causes of pre-eclampsia in pregnant women?

Response from DeepSeek-R1-Distill-Qwen-7B

image

Response from DeepSeek-R1-Distill-Qwen-7B + RAG

image

Related documents