Skip to content

Commit 70ff54e

Browse files
baichuan-assistantBaiChuanHelper
andauthored
community[minor]: Add Baichuan Text Embedding Model and Baichuan Inc introduction (langchain-ai#16568)
- **Description:** Adding Baichuan Text Embedding Model and Baichuan Inc introduction. Baichuan Text Embedding ranks #1 in C-MTEB leaderboard: https://huggingface.co/spaces/mteb/leaderboard Co-authored-by: BaiChuanHelper <[email protected]>
1 parent 5b5115c commit 70ff54e

File tree

7 files changed

+252
-25
lines changed

7 files changed

+252
-25
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# Baichuan
2+
3+
>[Baichuan Inc.](https://www.baichuan-ai.com/) is a Chinese startup in the era of AGI, dedicated to addressing fundamental human needs: Efficiency, Health, and Happiness.
4+
5+
## Visit Us
6+
Visit us at https://www.baichuan-ai.com/.
7+
Register and get an API key if you are trying out our APIs.
8+
9+
## Baichuan Chat Model
10+
An example is available at [example](/docs/integrations/chat/baichuan).
11+
12+
## Baichuan Text Embedding Model
13+
An example is available at [example] (/docs/integrations/text_embedding/baichuan)
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"metadata": {},
6+
"source": [
7+
"# Baichuan Text Embeddings\n",
8+
"\n",
9+
"As of today (Jan 25th, 2024) BaichuanTextEmbeddings ranks #1 in C-MTEB (Chinese Multi-Task Embedding Benchmark) leaderboard.\n",
10+
"\n",
11+
"Leaderboard (Under Overall -> Chinese section): https://huggingface.co/spaces/mteb/leaderboard\n",
12+
"\n",
13+
"Official Website: https://platform.baichuan-ai.com/docs/text-Embedding\n",
14+
"An API-key is required to use this embedding model. You can get one by registering at https://platform.baichuan-ai.com/docs/text-Embedding.\n",
15+
"BaichuanTextEmbeddings support 512 token window and preduces vectors with 1024 dimensions. \n",
16+
"\n",
17+
"Please NOTE that BaichuanTextEmbeddings only supports Chinese text embedding. Multi-language support is coming soon.\n"
18+
]
19+
},
20+
{
21+
"cell_type": "code",
22+
"execution_count": null,
23+
"metadata": {
24+
"vscode": {
25+
"languageId": "plaintext"
26+
}
27+
},
28+
"outputs": [],
29+
"source": [
30+
"from langchain_community.embeddings import BaichuanTextEmbeddings\n",
31+
"\n",
32+
"# Place your Baichuan API-key here.\n",
33+
"embeddings = BaichuanTextEmbeddings(baichuan_api_key=\"sk-*\")\n",
34+
"\n",
35+
"text_1 = \"今天天气不错\"\n",
36+
"text_2 = \"今天阳光很好\""
37+
]
38+
},
39+
{
40+
"cell_type": "code",
41+
"execution_count": null,
42+
"metadata": {
43+
"vscode": {
44+
"languageId": "plaintext"
45+
}
46+
},
47+
"outputs": [],
48+
"source": [
49+
"query_result = embeddings.embed_query(text_1)\n",
50+
"query_result"
51+
]
52+
},
53+
{
54+
"cell_type": "code",
55+
"execution_count": null,
56+
"metadata": {
57+
"vscode": {
58+
"languageId": "plaintext"
59+
}
60+
},
61+
"outputs": [],
62+
"source": [
63+
"doc_result = embeddings.embed_documents([text_1, text_2])\n",
64+
"doc_result"
65+
]
66+
}
67+
],
68+
"metadata": {
69+
"language_info": {
70+
"name": "python"
71+
}
72+
},
73+
"nbformat": 4,
74+
"nbformat_minor": 2
75+
}

docs/docs/integrations/vectorstores/kdbai.ipynb

Lines changed: 29 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -167,9 +167,9 @@
167167
],
168168
"source": [
169169
"%%time\n",
170-
"URL = 'https://www.conseil-constitutionnel.fr/node/3850/pdf'\n",
171-
"PDF = 'Déclaration_des_droits_de_l_homme_et_du_citoyen.pdf'\n",
172-
"open(PDF, 'wb').write(requests.get(URL).content)"
170+
"URL = \"https://www.conseil-constitutionnel.fr/node/3850/pdf\"\n",
171+
"PDF = \"Déclaration_des_droits_de_l_homme_et_du_citoyen.pdf\"\n",
172+
"open(PDF, \"wb\").write(requests.get(URL).content)"
173173
]
174174
},
175175
{
@@ -208,7 +208,7 @@
208208
],
209209
"source": [
210210
"%%time\n",
211-
"print('Read a PDF...')\n",
211+
"print(\"Read a PDF...\")\n",
212212
"loader = PyPDFLoader(PDF)\n",
213213
"pages = loader.load_and_split()\n",
214214
"len(pages)"
@@ -252,12 +252,14 @@
252252
],
253253
"source": [
254254
"%%time\n",
255-
"print('Create a Vector Database from PDF text...')\n",
256-
"embeddings = OpenAIEmbeddings(model='text-embedding-ada-002')\n",
255+
"print(\"Create a Vector Database from PDF text...\")\n",
256+
"embeddings = OpenAIEmbeddings(model=\"text-embedding-ada-002\")\n",
257257
"texts = [p.page_content for p in pages]\n",
258258
"metadata = pd.DataFrame(index=list(range(len(texts))))\n",
259-
"metadata['tag'] = 'law'\n",
260-
"metadata['title'] = 'Déclaration des Droits de l\\'Homme et du Citoyen de 1789'.encode('utf-8')\n",
259+
"metadata[\"tag\"] = \"law\"\n",
260+
"metadata[\"title\"] = \"Déclaration des Droits de l'Homme et du Citoyen de 1789\".encode(\n",
261+
" \"utf-8\"\n",
262+
")\n",
261263
"vectordb = KDBAI(table, embeddings)\n",
262264
"vectordb.add_texts(texts=texts, metadatas=metadata)"
263265
]
@@ -288,11 +290,13 @@
288290
],
289291
"source": [
290292
"%%time\n",
291-
"print('Create LangChain Pipeline...')\n",
292-
"qabot = RetrievalQA.from_chain_type(chain_type='stuff',\n",
293-
" llm=ChatOpenAI(model='gpt-3.5-turbo-16k', temperature=TEMP), \n",
294-
" retriever=vectordb.as_retriever(search_kwargs=dict(k=K)),\n",
295-
" return_source_documents=True)"
293+
"print(\"Create LangChain Pipeline...\")\n",
294+
"qabot = RetrievalQA.from_chain_type(\n",
295+
" chain_type=\"stuff\",\n",
296+
" llm=ChatOpenAI(model=\"gpt-3.5-turbo-16k\", temperature=TEMP),\n",
297+
" retriever=vectordb.as_retriever(search_kwargs=dict(k=K)),\n",
298+
" return_source_documents=True,\n",
299+
")"
296300
]
297301
},
298302
{
@@ -325,9 +329,9 @@
325329
],
326330
"source": [
327331
"%%time\n",
328-
"Q = 'Summarize the document in English:'\n",
329-
"print(f'\\n\\n{Q}\\n')\n",
330-
"print(qabot.invoke(dict(query=Q))['result'])"
332+
"Q = \"Summarize the document in English:\"\n",
333+
"print(f\"\\n\\n{Q}\\n\")\n",
334+
"print(qabot.invoke(dict(query=Q))[\"result\"])"
331335
]
332336
},
333337
{
@@ -362,9 +366,9 @@
362366
],
363367
"source": [
364368
"%%time\n",
365-
"Q = 'Is it a fair law and why ?'\n",
366-
"print(f'\\n\\n{Q}\\n')\n",
367-
"print(qabot.invoke(dict(query=Q))['result'])"
369+
"Q = \"Is it a fair law and why ?\"\n",
370+
"print(f\"\\n\\n{Q}\\n\")\n",
371+
"print(qabot.invoke(dict(query=Q))[\"result\"])"
368372
]
369373
},
370374
{
@@ -414,9 +418,9 @@
414418
],
415419
"source": [
416420
"%%time\n",
417-
"Q = 'What are the rights and duties of the man, the citizen and the society ?'\n",
418-
"print(f'\\n\\n{Q}\\n')\n",
419-
"print(qabot.invoke(dict(query=Q))['result'])"
421+
"Q = \"What are the rights and duties of the man, the citizen and the society ?\"\n",
422+
"print(f\"\\n\\n{Q}\\n\")\n",
423+
"print(qabot.invoke(dict(query=Q))[\"result\"])"
420424
]
421425
},
422426
{
@@ -441,9 +445,9 @@
441445
],
442446
"source": [
443447
"%%time\n",
444-
"Q = 'Is this law practical ?'\n",
445-
"print(f'\\n\\n{Q}\\n')\n",
446-
"print(qabot.invoke(dict(query=Q))['result'])"
448+
"Q = \"Is this law practical ?\"\n",
449+
"print(f\"\\n\\n{Q}\\n\")\n",
450+
"print(qabot.invoke(dict(query=Q))[\"result\"])"
447451
]
448452
},
449453
{

libs/community/langchain_community/embeddings/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
)
2121
from langchain_community.embeddings.awa import AwaEmbeddings
2222
from langchain_community.embeddings.azure_openai import AzureOpenAIEmbeddings
23+
from langchain_community.embeddings.baichuan import BaichuanTextEmbeddings
2324
from langchain_community.embeddings.baidu_qianfan_endpoint import (
2425
QianfanEmbeddingsEndpoint,
2526
)
@@ -92,6 +93,7 @@
9293
__all__ = [
9394
"OpenAIEmbeddings",
9495
"AzureOpenAIEmbeddings",
96+
"BaichuanTextEmbeddings",
9597
"ClarifaiEmbeddings",
9698
"CohereEmbeddings",
9799
"DatabricksEmbeddings",
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
from typing import Any, Dict, List, Optional
2+
3+
import requests
4+
from langchain_core.embeddings import Embeddings
5+
from langchain_core.pydantic_v1 import BaseModel, SecretStr, root_validator
6+
from langchain_core.utils import convert_to_secret_str, get_from_dict_or_env
7+
8+
BAICHUAN_API_URL: str = "http://api.baichuan-ai.com/v1/embeddings"
9+
10+
# BaichuanTextEmbeddings is an embedding model provided by Baichuan Inc. (https://www.baichuan-ai.com/home).
11+
# As of today (Jan 25th, 2024) BaichuanTextEmbeddings ranks #1 in C-MTEB
12+
# (Chinese Multi-Task Embedding Benchmark) leaderboard.
13+
# Leaderboard (Under Overall -> Chinese section): https://huggingface.co/spaces/mteb/leaderboard
14+
15+
# Official Website: https://platform.baichuan-ai.com/docs/text-Embedding
16+
# An API-key is required to use this embedding model. You can get one by registering
17+
# at https://platform.baichuan-ai.com/docs/text-Embedding.
18+
# BaichuanTextEmbeddings support 512 token window and preduces vectors with
19+
# 1024 dimensions.
20+
21+
22+
# NOTE!! BaichuanTextEmbeddings only supports Chinese text embedding.
23+
# Multi-language support is coming soon.
24+
class BaichuanTextEmbeddings(BaseModel, Embeddings):
25+
"""Baichuan Text Embedding models."""
26+
27+
session: Any #: :meta private:
28+
model_name: str = "Baichuan-Text-Embedding"
29+
baichuan_api_key: Optional[SecretStr] = None
30+
31+
@root_validator(allow_reuse=True)
32+
def validate_environment(cls, values: Dict) -> Dict:
33+
"""Validate that auth token exists in environment."""
34+
try:
35+
baichuan_api_key = convert_to_secret_str(
36+
get_from_dict_or_env(values, "baichuan_api_key", "BAICHUAN_API_KEY")
37+
)
38+
except ValueError as original_exc:
39+
try:
40+
baichuan_api_key = convert_to_secret_str(
41+
get_from_dict_or_env(
42+
values, "baichuan_auth_token", "BAICHUAN_AUTH_TOKEN"
43+
)
44+
)
45+
except ValueError:
46+
raise original_exc
47+
session = requests.Session()
48+
session.headers.update(
49+
{
50+
"Authorization": f"Bearer {baichuan_api_key.get_secret_value()}",
51+
"Accept-Encoding": "identity",
52+
"Content-type": "application/json",
53+
}
54+
)
55+
values["session"] = session
56+
return values
57+
58+
def _embed(self, texts: List[str]) -> Optional[List[List[float]]]:
59+
"""Internal method to call Baichuan Embedding API and return embeddings.
60+
61+
Args:
62+
texts: A list of texts to embed.
63+
64+
Returns:
65+
A list of list of floats representing the embeddings, or None if an
66+
error occurs.
67+
"""
68+
try:
69+
response = self.session.post(
70+
BAICHUAN_API_URL, json={"input": texts, "model": self.model_name}
71+
)
72+
# Check if the response status code indicates success
73+
if response.status_code == 200:
74+
resp = response.json()
75+
embeddings = resp.get("data", [])
76+
# Sort resulting embeddings by index
77+
sorted_embeddings = sorted(embeddings, key=lambda e: e.get("index", 0))
78+
# Return just the embeddings
79+
return [result.get("embedding", []) for result in sorted_embeddings]
80+
else:
81+
# Log error or handle unsuccessful response appropriately
82+
print(
83+
f"""Error: Received status code {response.status_code} from
84+
embedding API"""
85+
)
86+
return None
87+
except Exception as e:
88+
# Log the exception or handle it as needed
89+
print(f"Exception occurred while trying to get embeddings: {str(e)}")
90+
return None
91+
92+
def embed_documents(self, texts: List[str]) -> Optional[List[List[float]]]:
93+
"""Public method to get embeddings for a list of documents.
94+
95+
Args:
96+
texts: The list of texts to embed.
97+
98+
Returns:
99+
A list of embeddings, one for each text, or None if an error occurs.
100+
"""
101+
return self._embed(texts)
102+
103+
def embed_query(self, text: str) -> Optional[List[float]]:
104+
"""Public method to get embedding for a single query text.
105+
106+
Args:
107+
text: The text to embed.
108+
109+
Returns:
110+
Embeddings for the text, or None if an error occurs.
111+
"""
112+
result = self._embed([text])
113+
return result[0] if result is not None else None
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
"""Test Baichuan Text Embedding."""
2+
from langchain_community.embeddings.baichuan import BaichuanTextEmbeddings
3+
4+
5+
def test_baichuan_embedding_documents() -> None:
6+
"""Test Baichuan Text Embedding for documents."""
7+
documents = ["今天天气不错", "今天阳光灿烂"]
8+
embedding = BaichuanTextEmbeddings()
9+
output = embedding.embed_documents(documents)
10+
assert len(output) == 2
11+
assert len(output[0]) == 1024
12+
13+
14+
def test_baichuan_embedding_query() -> None:
15+
"""Test Baichuan Text Embedding for query."""
16+
document = "所有的小学生都会学过只因兔同笼问题。"
17+
embedding = BaichuanTextEmbeddings()
18+
output = embedding.embed_query(document)
19+
assert len(output) == 1024

libs/community/tests/unit_tests/embeddings/test_imports.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
EXPECTED_ALL = [
44
"OpenAIEmbeddings",
55
"AzureOpenAIEmbeddings",
6+
"BaichuanTextEmbeddings",
67
"ClarifaiEmbeddings",
78
"CohereEmbeddings",
89
"DatabricksEmbeddings",

0 commit comments

Comments
 (0)