Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

LangChain Integration with Alibaba Bailian

LangChain Integration with Alibaba Bailian

LangChain is currently the most mainstream framework for large model application development. It helps developers quickly build prompts, models, tool chains, and agent applications through a unified component interface.

Alibaba Cloud Bailian (DashScope) is Alibaba Cloud's large model service platform, providing the Qwen (qwen) series of chat models, text embedding models, and reranking models.

This article introduces how to integrate Bailian models into LangChain, covering three major categories: chat models, text embedding models, and reranking models, and provides complete examples in Python, JavaScript, and Java.

Prerequisites

We need to activate the Alibaba Cloud Model Studio service and obtain an API key.

We can first use the Alibaba Cloud main account to visit the Model Studio platform:https://bailian.console.aliyun.com/, then click Log in in the upper right corner. After logging in, click the gear ⚙️ icon in the upper right corner, select API key, and copy the API key. If you do not have one, you can create one:

Before getting started, first understand two key concepts: LangChain's "model integration classes" and Bailian's "two integration modes".

Model integration classes

LangChain wraps models from different providers into unified "integration classes".

Application code is programmed against a unified interface; when switching providers, you only need to change the integration class and parameters, with almost no changes to business logic.

Taking chat models as an example, on the Python side there are two integration classes, ChatOpenAI and ChatTongyi, corresponding to Bailian's OpenAI-compatible mode and DashScope native mode, respectively.

Two integration modes

Bailian provides two sets of integration protocols; choosing a different protocol corresponds to a different LangChain integration class.

OpenAI-compatible mode: The interface protocol is consistent with OpenAI, so any framework supporting the OpenAI protocol can connect directly, with the lowest integration cost.

DashScope native mode: Uses Bailian's own DashScope protocol and can call all of Bailian's text generation models, including deployed custom models.

The overall integration architecture is shown in the figure below:

LangChain integration with Alibaba Cloud Bailian architecture diagram

The so-called "OpenAI-compatible interface" means that the provider's HTTP interface protocol is consistent with OpenAI's.

As long as the protocol is compatible, any code or tool written for OpenAI can be reused directly, with only the interface address needing to be changed.

Configure Environment Variables

All languages and integration methods uniformly use the environment variable DASHSCOPE_API_KEY to store the secret key.

On Linux / macOS, export in the terminal:



export DASHSCOPE_API_KEY="sk-你的百炼APIKey"

How to set it on Windows (CMD):



set DASHSCOPE_API_KEY=sk-你的百炼APIKey

It is recommended to write the export command into a shell configuration file (such as ~/.bashrc or ~/.zshrc) to avoid setting it again every time you open a terminal.

Configure via a .env file (recommended)

A more recommended approach is to write the secret key into a .env file in the project root directory and use python-dotenv to automatically load it into environment variables.

Separating the secret key from the code, combined with .gitignore, can prevent accidental commits and makes it easier for each person to maintain their own key when collaborating.

Create a .env file in the project root directory:



# File path: project root directory/.env

DASHSCOPE_API_KEY=sk-你的百炼APIKey

For example, create a .env file in our test project runoob-langchain-test and add the configuration:

Install python-dotenv:



pip install python-dotenv

Load the .env file at the beginning of the Python code:

Example

from

dotenv

import

load_dotenv

load_dotenv

(

)

 

Read the .env file in the project root directory and inject it as environment variables

After loading, the code can read the key with os.getenv("DASHSCOPE_API_KEY"), with the same effect as a manual export.

This loading method is demonstrated in the examples in the "Chat Model" section.

.env is a sensitive file; please add it to .gitignore (write a line with .env) to prevent the key from being committed to the repository.

Please replace the key in the example with a real Key and never share it with others.


Comparison of the Two Integration Methods

First look at a comparison table, then choose an integration method as needed.

Comparison Item OpenAI-compatible mode DashScope native mode
Integration principle Reuse the integration class of the OpenAI protocol Use the native DashScope SDK
Supported models Only some models All text generation models and deployed models
Python integration class ChatOpenAI ChatTongyi
JavaScript integration class ChatOpenAI ChatAlibabaTongyi
Java integration class OpenAiChatModel QwenChatModel
Applicable scenarios Existing OpenAI code that needs a quick switch Need full model capabilities or use deployed models

Both modes use the same domain, dashscope.aliyuncs.com; the difference lies in the path: the OpenAI-compatible mode path is /compatible-mode/v1, while the DashScope native mode path is built into the SDK.


Chat Model

Chat models are the most commonly used type of model, for tasks such as multi-turn conversations, question answering, and content generation.

The following introduces integration methods by language; the examples uniformly use qwen-plus as the model, which can be changed as needed.

Python: OpenAI-compatible approach

Use the ChatOpenAI integration class in the langchain_openai package to call Bailian as an OpenAI service.

First install the dependencies:



pip install langchain_openai

Example code:

Example

from

langchain_openai

import

ChatOpenAI

from

dotenv

import

load_dotenv  

Read the configuration from the .env file

import

os

load_dotenv

(

)

 

Load the key and other environment variables from the .env file in the project root directory

Create a chat model instance to connect to Bailian via the OpenAI-compatible protocol

chatLLM

=

ChatOpenAI

(

    api_key

=

os

.

getenv

(

"DASHSCOPE_API_KEY"

)

,

 

Read the Bailian API Key from the environment variable (required)

    base_url

=

"https://dashscope.aliyuncs.com/compatible-mode/v1"

,

 

Bailian OpenAI-compatible interface address (required)

    model

=

"qwen-plus"

,

 

Model name (required); qwen-plus is used here as an example

   

Other optional parameters: temperature (generation temperature), max_tokens (maximum output length), etc.

)

Construct a multi-turn conversation message list

messages

=

[

   

{

"role"

:

"system"

,

"content"

:

"You are a helpful assistant."

}

,

 

System message, setting the assistant's role

   

{

"role"

:

"user"

,

"content"

:

"Who are you?"

}

,

 

User message, the question content

]

Initiate the call and return a structured response object

response

=

chatLLM.

invoke

(

messages

)

print

(

response.

model_dump_json

(

)

)

Output the result (some fields omitted):



{

  "content": "我是通义千问,由阿里云开发的大语言模型,可以回答你的问题、协助创作、提供建议等。",

  "usage": { "prompt_tokens": 12, "completion_tokens": 28, "total_tokens": 40 }

}

On success, an AIMessage object is returned, and model_dump_json() can serialize it to JSON for easy viewing of the complete response.

Python: DashScope native approach

Use the ChatTongyi integration class in the langchain-community package, which uses the native DashScope protocol and supports streaming output.

ChatTongyi comes from the langchain-community community package, which, along with dashscope, is no longer maintained.

For new projects, it is recommended to prefer the OpenAI-compatible ChatOpenAI integration, and only consider this approach when native DashScope capabilities (such as deployed models) are needed.

First install the dependencies:



pip install langchain-community dashscope

Example code:

Example

from

langchain_community.

chat_models

.

tongyi

import

ChatTongyi

from

langchain_core.

messages

import

HumanMessage

from

dotenv

import

load_dotenv  

Read the configuration from the .env file

import

os

load_dotenv

(

)

 

Load the key and other environment variables from the .env file in the project root directory

Create a Qwen chat model using the native DashScope protocol

chatLLM

=

ChatTongyi

(

    model

=

"qwen-plus"

,

 

Model name (required)

    dashscope_api_key

=

os

.

getenv

(

"DASHSCOPE_API_KEY"

)

,

 

Read the API Key from the environment variable (required)

    streaming

=

True

,

 

Enable streaming output

)

Streaming call, receiving and printing the response content segment by segment

res

=

chatLLM.

stream

(

[

HumanMessage

(

content

=

"hi"

)

]

,

streaming

=

True

)

for

r

in

res:

   

print

(

"chat resp:"

,

r.

content

)

Output result:



chat resp: 你好

chat resp: !我是通义千问,有什么可以帮您的吗?

Streaming output lets the model return content segment by segment while generating, suitable for chat interfaces that need a typewriter effect.


Text Embedding Model

Embedding models convert text into semantic vectors and are the foundation of applications such as RAG (Retrieval-Augmented Generation) and semantic search.

Model selection

Bailian provides multiple versions of embedding models; you can compare their performance using the two evaluation metrics MTEB and CMTEB, where a higher value is better.

Model MTEB MTEB (retrieval task) CMTEB CMTEB (retrieval task)
text-embedding-v1 58.30 45.47 59.84 56.59
text-embedding-v2 60.13 49.49 62.17 62.78
text-embedding-v3 (1024 dimensions) 63.39 55.41 68.92 73.23
text-embedding-v4 (1024 dimensions) 68.36 59.30 70.14 73.98

When called through LangChain, text-embedding-v3 and text-embedding-v4 cannot have their vector dimension specified; they output 1024-dimensional vectors by default.

The higher the version, the better the performance; prefer v4.

Python example

Bailian's embedding interface is compatible with the OpenAI interface specification; simply use the OpenAIEmbeddings integration class in the langchain-openai package and point base_url to Bailian's compatible endpoint.

There is no need to install langchain-community and dashscope, the two packages that are no longer maintained.

First install the dependencies:



pip install langchain-openai

OpenAIEmbeddings requires three key parameters: model (embedding model name), api_key (Bailian key), and base_url (Bailian OpenAI-compatible endpoint).

base_url is fixed to https://dashscope.aliyuncs.com/compatible-mode/v1, consistent with the chat model's compatible endpoint.

Example code:

Example

from

langchain_openai

import

OpenAIEmbeddings

from

dotenv

import

load_dotenv  

Read the configuration from the .env file

import

os

load_dotenv

(

)

 

Load the key and other environment variables from the .env file in the project root directory

Create an embedding model instance to connect to Bailian via the OpenAI-compatible protocol

chunk_size=10: Bailian's Embedding interface accepts at most 10 texts per request,

while OpenAIEmbeddings packages 1000 items at a time by default, so a slightly larger knowledge base will exceed the limit and cause an error.

embeddings

=

OpenAIEmbeddings

(

    model

=

"text-embedding-v4"

,

 

Embedding model name (required); v4 is used here as an example

    api_key

=

os

.

getenv

(

"DASHSCOPE_API_KEY"

)

,

 

Read the Bailian API Key from the environment variable (required)

    base_url

=

"https://dashscope.aliyuncs.com/compatible-mode/v1"

,

 

Bailian OpenAI-compatible endpoint (required)

    check_embedding_ctx_length

=

False

,

    chunk_size

=

10

,

)

Vectorize a single query text

text

=

"This is a test document."

query_result

=

embeddings.

embed_query

(

text

)

print

(

"Text vector length:"

,

len

(

query_result

)

,

sep

=

''

)

Vectorize multiple documents in batches

doc_results

=

embeddings.

embed_documents

(

   

[

       

"Hi there!"

,

       

"Oh, hello!"

,

       

"What's your name?"

,

       

"My friends call me World"

,

       

"Hello World!"

   

]

)

print

(

"Number of text vectors:"

,

len

(

doc_results

)

,

", text vector length:"

,

len

(

doc_results

[

0

]

)

,

sep

=

''

)

Output result:



文本向量长度:1024

文本向量数量:5 ,文本向量长度:1024

embed_query is used to vectorize the user's query, and embed_documents is used to vectorize candidate documents in batches; the two must output vectors of the same dimension in order to compute similarity.


Reranker Model

A reranker model performs a second round of scoring and ranking on retrieval results, which can significantly improve the answer quality of RAG applications.

Model parameters

Bailian provides the following reranker models; choose according to language, cost, and scenario:

Model Maximum number of Documents Maximum input per item Language support Unit price (per thousand Tokens) Applicable scenarios
qwen3-vl-rerank 100 8,000 Token 33 mainstream languages including Chinese, English, Japanese, and Korean Image 0.0018 CNY / Text 0.0007 CNY Image clustering, cross-modal search, image retrieval
qwen3-rerank 500 4,000 Token 100+ languages including Chinese, English, Spanish, French, Japanese, and Korean 0.0005 CNY Text semantic retrieval, RAG applications
gte-rerank-v2 — 30,000 Token 50+ languages including Chinese, English, Japanese, Korean, and Thai 0.0008 CNY Long-text reranking

Python example

Use the DashScopeRerank integration class in the langchain-community package.

This example uses DashScopeRerank from the langchain-community community package.

langchain-community and dashscope are no longer maintained; for new projects, please pay attention to the alternative integration methods officially provided by Bailian.

First install the dependencies:



pip install langchain-community dashscope

Example code:

Example

from

langchain_community.

document_compressors

.

dashscope_rerank

import

DashScopeRerank

from

dotenv

import

load_dotenv  

Read the configuration from the .env file

load_dotenv

(

)

 

Load the key and other environment variables from the .env file in the project root directory

Simulated list of candidate texts returned by retrieval

sequence

=

[

"runoob is a Chinese learning website that provides programming tutorials"

,

"text2"

,

"text3"

]

Create a reranker model instance

reranker

=

DashScopeRerank

(

    model

=

"gte-rerank-v2"

,

 

Reranker model name (required)

)

Rerank the candidate texts according to the query and return the top_n with the highest scores

print

(

reranker.

rerank

(

documents

=

sequence

,

query

=

"What is runoob"

,

top_n

=

2

)

)

The rerank method rescores and reorders candidate documents according to the query; top_n specifies the number to return, and it is often used in the fine-ranking stage after RAG retrieval.


JavaScript and Java Integration

JavaScript: OpenAI-compatible approach

On the Node.js side, use the ChatOpenAI integration class in the @langchain/openai package.

First install the dependencies:



npm install @langchain/openai @langchain/core

Example code:

Example

import

{

ChatOpenAI

}

from

"@langchain/openai"

;

// Create a chat model instance to connect to Bailian via the OpenAI-compatible protocol

const

llm

=

new

ChatOpenAI

(

{

  model

:

"qwen-plus"

,

 

// Model name (required); qwen-plus is used here as an example

  apiKey

:

process.

env

.

DASHSCOPE_API_KEY

,

 

// Read the Bailian API Key from the environment variable (required)

  configuration

:

{

    baseURL

:

"https://dashscope.aliyuncs.com/compatible-mode/v1"

,

 

// Bailian OpenAI-compatible interface address (required)

 

}

,

}

)

;

// Initiate the chat call and return an AI message object

const

aiMsg

=

await llm.

invoke

(

[

 

{

role

:

"system"

,

content

:

"You are a helpful assistant that translates English to French. Translate the user sentence."

}

,

 

// System message

 

{

role

:

"user"

,

content

:

"I love programming."

}

,

 

// User message

]

)

;

console.

log

(

'---------------------------'

)

;

console.

log

(

aiMsg.

content

)

;

Output result:



---------------------------

J'adore la programmation.

JavaScript: DashScope native approach

Use the ChatAlibabaTongyi integration class in the @langchain/community package.

First install the dependencies:



npm install @langchain/community @langchain/core

Example code:

Example

import

{

ChatAlibabaTongyi

}

from

"@langchain/community/chat_models/alibaba_tongyi"

;

import

{

HumanMessage

}

from

"@langchain/core/messages"

;

// The default model is qwen-turbo; only the API Key is required

const

qwenTurbo

=

new

ChatAlibabaTongyi

(

{

  alibabaApiKey

:

process.

env

.

DASHSCOPE_API_KEY

,

 

// Read the API Key from the environment variable (required)

}

)

;

// Using qwen-plus, you can additionally specify generation parameters such as temperature

const

qwenPlus

=

new

ChatAlibabaTongyi

(

{

  model

:

"qwen-plus"

,

 

// Model name (required)

  temperature

:

1

,

 

// Generation temperature; a higher value makes the output more diverse

  alibabaApiKey

:

process.

env

.

DASHSCOPE_API_KEY

,

 

// Read the API Key from the environment variable (required)

}

)

;

const

messages

=

[

new

HumanMessage

(

"Hello"

)

]

;

// Call the two models separately and print the results

const

res

=

await qwenTurbo.

invoke

(

messages

)

;

const

res2

=

await qwenPlus.

invoke

(

messages

)

;

console.

log

(

'---------------------------'

)

;

console.

log

(

res.

content

)

;

console.

log

(

'---------------------------'

)

;

console.

log

(

res2.

content

)

;

Java: OpenAI-compatible approach (LangChain4j)

The Java ecosystem uses the LangChain4j framework, connecting to Bailian through the langchain4j-open-ai module.

LangChain4j 1.0.0-beta3 requires Java 17 or above.

Compiling with Java 11 produces the error Unsupported class file major version 61; upgrading the JDK resolves it.

Add the dependency in pom.xml:







    dev.langchain4j

    langchain4j-open-ai

    1.0.0-beta3



Example code:

Example

import

dev.langchain4j.data.message.SystemMessage

;

import

dev.langchain4j.data.message.UserMessage

;

import

dev.langchain4j.model.chat.ChatLanguageModel

;

import

dev.langchain4j.model.openai.OpenAiChatModel

;

public

class

LangChainOpenAITest

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Create a chat model, reusing the OpenAI protocol to connect to Bailian

        ChatLanguageModel model

=

OpenAiChatModel.

builder

(

)

                .

apiKey

(

System

.

getenv

(

"DASHSCOPE_API_KEY"

)

)

 

// Read the API Key from the environment variable (required)

                .

baseUrl

(

"https://dashscope.aliyuncs.com/compatible-mode/v1"

)

 

// Bailian OpenAI-compatible address (required)

                .

modelName

(

"qwen-plus"

)

 

// Model name (required)

                .

build

(

)

;

        SystemMessage systemMessage

=

SystemMessage.

from

(

"You are a psychology expert"

)

;

 

// System message, setting the role

        UserMessage userMessage

=

UserMessage.

from

(

"Hello" (Chinese)

)

;

 

// User message

       

System

.

out

.

println

(

model.

chat

(

systemMessage, userMessage

)

.

aiMessage

(

)

.

text

(

)

)

;

   

}

}

Java: DashScope native approach (LangChain4j)

Use the langchain4j-community-dashscope module, which supports both normal and streaming calls.

Add the dependency in pom.xml:







    dev.langchain4j

    langchain4j-community-dashscope

    1.0.0-beta3



Example code (normal call and streaming call):

Example

import

dev.langchain4j.community.model.dashscope.QwenChatModel

;

import

dev.langchain4j.community.model.dashscope.QwenStreamingChatModel

;

import

dev.langchain4j.data.message.ChatMessage

;

import

dev.langchain4j.data.message.SystemMessage

;

import

dev.langchain4j.data.message.UserMessage

;

import

dev.langchain4j.model.chat.ChatLanguageModel

;

import

dev.langchain4j.model.chat.StreamingChatLanguageModel

;

import

dev.langchain4j.model.chat.request.ChatRequest

;

import

dev.langchain4j.model.chat.response.ChatResponse

;

import

dev.langchain4j.model.chat.response.StreamingChatResponseHandler

;

public

class

LangChainDashScopeTest

{

   

public

static

void

main

(

String

[

]

args

)

{

        chatLanguageModelTest

(

)

;

 

// Normal call

//        streamingChatLanguageModelTest();  // Streaming call; uncomment as needed

   

}

   

// Normal call: returns the complete result at once

   

public

static

void

chatLanguageModelTest

(

)

{

        ChatLanguageModel qwenModel

=

QwenChatModel.

builder

(

)

                .

apiKey

(

System

.

getenv

(

"DASHSCOPE_API_KEY"

)

)

 

// Read the API Key from the environment variable (required)

                .

modelName

(

"qwen-plus"

)

 

// Model name (required)

                .

build

(

)

;

       

// Construct the request; messages are arranged in chronological order

        ChatRequest request

=

ChatRequest.

builder

(

)

                .

messages

(

new

ChatMessage

[

]

{

                        SystemMessage.

from

(

"You are a psychology expert"

)

,  

// System message

                        UserMessage.

from

(

"Hello" (Chinese)

)

 

// User message

               

}

)

                .

build

(

)

;

       

System

.

out

.

println

(

qwenModel.

chat

(

request

)

.

aiMessage

(

)

.

text

(

)

)

;

   

}

   

// Streaming call: receives the generated text segment by segment

   

public

static

void

streamingChatLanguageModelTest

(

)

{

        StreamingChatLanguageModel model

=

QwenStreamingChatModel.

builder

(

)

                .

apiKey

(

System

.

getenv

(

"DASHSCOPE_API_KEY"

)

)

                .

modelName

(

"qwen-plus"

)

                .

build

(

)

;

        model.

chat

(

"Hello" (Chinese)

,

new

StreamingChatResponseHandler

(

)

{

            @Override

           

public

void

onPartialResponse

(

String

s

)

{

 

// Called back once for each segment generated

               

System

.

out

.

println

(

s

)

;

           

}

            @Override

           

public

void

onCompleteResponse

(

ChatResponse chatResponse

)

{

 

// Generation complete

               

System

.

out

.

println

(

"Conversation ended"

)

;

               

System

.

exit

(

0

)

;

           

}

            @Override

           

public

void

onError

(

Throwable

throwable

)

{

 

// An exception occurred

               

System

.

out

.

println

(

"An exception occurred"

)

;

               

System

.

exit

(

0

)

;

           

}

       

}

)

;

   

}

}

LangChain4j also provides a Spring Boot Starter; there is no need to manually build model objects, just configure them in application.properties.

Example

File path: application.properties

API Key (required)

langchain4j.open-ai.chat-model.api-key

=

${DASHSCOPE_API_KEY}

Model name (required)

langchain4j.open-ai.chat-model.model-name

=

qwen-plus

OpenAI-compatible interface address (required)

langchain4j.open-ai.chat-model.base-url

=

https://dashscope.aliyuncs.com/compatible-mode/v1

Service port

server.port

=

9000

The Starter configuration items for the DashScope native approach have the same names; you only need to change the prefix to langchain4j.community.dashscope.chat-model, and there is no need to configure base-url.


Notes / FAQ

For problems encountered during integration, you can use the checklist below to quickly locate them.

Java version requirements

LangChain4j 1.0.0-beta3 requires Java 17 or above.

Compiling with Java 11 produces Unsupported class file major version 61; upgrading the JDK resolves it.

OpenAI-compatible mode only supports some models

The OpenAI-compatible interface only supports some of Bailian's models; see the official documentation for the complete list.

If the model you call is not in the supported range, just switch to DashScope native mode.

Default dimension of embedding vectors

When called through LangChain, text-embedding-v3 / v4 output 1024-dimensional vectors by default, and the dimension cannot be specified manually.

When creating database tables, please reserve a 1024-dimensional vector field.

API Key security

Do not hardcode the API Key in code; inject it uniformly through the DASHSCOPE_API_KEY environment variable.

For production environments, it is recommended to use it together with Alibaba Cloud's key management service.


Reference Links

The following official documents can help you understand the relevant details in depth:

Topic link
Get an API Key https://help.aliyun.com/zh/model-studio/get-api-key
Configure Environment Variables https://help.aliyun.com/zh/model-studio/configure-api-key-through-environment-variables
Bailian model list https://help.aliyun.com/zh/model-studio/getting-started/models
OpenAI-compatible model list https://help.aliyun.com/zh/model-studio/compatibility-of-openai-with-dashscope
Python ChatOpenAI documentation https://python.langchain.com/docs/integrations/chat/openai/
Python OpenAIEmbeddings documentation https://python.langchain.com/docs/integrations/text_embedding/openai/
Python ChatTongyi documentation https://python.langchain.com/docs/integrations/chat/tongyi/
LangChain4j DashScope documentation https://docs.langchain4j.dev/integrations/language-models/dashscope