Ben Luo commited on
Commit
5f72ddb
·
1 Parent(s): 030c559

Adding Tongyi OpenAI demo to use Qwen

Browse files

qwen-turbo-latest (currently Qwen3) is supported by now

Signed-off-by: Ben Luo <bn0418@gmail.com>

examples/lightrag_tongyi_openai_demo.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import asyncio
3
+ from lightrag import LightRAG, QueryParam
4
+ from lightrag.utils import EmbeddingFunc
5
+ import numpy as np
6
+ from dotenv import load_dotenv
7
+ import logging
8
+ from openai import OpenAI
9
+ from lightrag.kg.shared_storage import initialize_pipeline_status
10
+
11
+ logging.basicConfig(level=logging.INFO)
12
+
13
+ load_dotenv()
14
+
15
+ LLM_MODEL = os.environ.get("LLM_MODEL", "qwen-turbo-latest")
16
+ LLM_BINDING_HOST = "https://dashscope.aliyuncs.com/compatible-mode/v1"
17
+ LLM_BINDING_API_KEY = os.getenv("LLM_BINDING_API_KEY")
18
+
19
+ EMBEDDING_MODEL = os.environ.get("EMBEDDING_MODEL", "text-embedding-v3")
20
+ EMBEDDING_BINDING_HOST = os.getenv("EMBEDDING_BINDING_HOST", LLM_BINDING_HOST)
21
+ EMBEDDING_BINDING_API_KEY = os.getenv("EMBEDDING_BINDING_API_KEY", LLM_BINDING_API_KEY)
22
+ EMBEDDING_DIM = int(os.environ.get("EMBEDDING_DIM", 1024))
23
+ EMBEDDING_MAX_TOKEN_SIZE = int(os.environ.get("EMBEDDING_MAX_TOKEN_SIZE", 8192))
24
+ EMBEDDING_MAX_BATCH_SIZE = int(os.environ.get("EMBEDDING_MAX_BATCH_SIZE", 10))
25
+
26
+ print(f"LLM_MODEL: {LLM_MODEL}")
27
+ print(f"EMBEDDING_MODEL: {EMBEDDING_MODEL}")
28
+
29
+ WORKING_DIR = "./dickens"
30
+
31
+ if os.path.exists(WORKING_DIR):
32
+ import shutil
33
+
34
+ shutil.rmtree(WORKING_DIR)
35
+
36
+ os.mkdir(WORKING_DIR)
37
+
38
+
39
+ async def llm_model_func(
40
+ prompt, system_prompt=None, history_messages=[], keyword_extraction=False, **kwargs
41
+ ) -> str:
42
+ client = OpenAI(
43
+ api_key=LLM_BINDING_API_KEY,
44
+ base_url=LLM_BINDING_HOST,
45
+ )
46
+
47
+ messages = []
48
+ if system_prompt:
49
+ messages.append({"role": "system", "content": system_prompt})
50
+ if history_messages:
51
+ messages.extend(history_messages)
52
+ messages.append({"role": "user", "content": prompt})
53
+
54
+ chat_completion = client.chat.completions.create(
55
+ model=LLM_MODEL,
56
+ messages=messages,
57
+ temperature=kwargs.get("temperature", 0),
58
+ top_p=kwargs.get("top_p", 1),
59
+ n=kwargs.get("n", 1),
60
+ extra_body={"enable_thinking": False},
61
+ )
62
+ return chat_completion.choices[0].message.content
63
+
64
+
65
+ async def embedding_func(texts: list[str]) -> np.ndarray:
66
+ client = OpenAI(
67
+ api_key=EMBEDDING_BINDING_API_KEY,
68
+ base_url=EMBEDDING_BINDING_HOST,
69
+ )
70
+
71
+ print("##### embedding: texts: %d #####" % len(texts))
72
+ max_batch_size = EMBEDDING_MAX_BATCH_SIZE
73
+ embeddings = []
74
+ for i in range(0, len(texts), max_batch_size):
75
+ batch = texts[i : i + max_batch_size]
76
+ embedding = client.embeddings.create(model=EMBEDDING_MODEL, input=batch)
77
+ embeddings += [item.embedding for item in embedding.data]
78
+
79
+ return np.array(embeddings)
80
+
81
+
82
+ async def test_funcs():
83
+ result = await llm_model_func("How are you?")
84
+ print("Resposta do llm_model_func: ", result)
85
+
86
+ result = await embedding_func(["How are you?"])
87
+ print("Resultado do embedding_func: ", result.shape)
88
+ print("Dimensão da embedding: ", result.shape[1])
89
+
90
+
91
+ asyncio.run(test_funcs())
92
+
93
+
94
+ async def initialize_rag():
95
+ rag = LightRAG(
96
+ working_dir=WORKING_DIR,
97
+ llm_model_func=llm_model_func,
98
+ embedding_func=EmbeddingFunc(
99
+ embedding_dim=EMBEDDING_DIM,
100
+ max_token_size=EMBEDDING_MAX_TOKEN_SIZE,
101
+ func=embedding_func,
102
+ ),
103
+ )
104
+
105
+ await rag.initialize_storages()
106
+ await initialize_pipeline_status()
107
+
108
+ return rag
109
+
110
+
111
+ def main():
112
+ rag = asyncio.run(initialize_rag())
113
+
114
+ with open("./book.txt", "r", encoding="utf-8") as f:
115
+ rag.insert(f.read())
116
+
117
+ query_text = "What are the main themes?"
118
+
119
+ print("Result (Naive):")
120
+ print(rag.query(query_text, param=QueryParam(mode="naive")))
121
+
122
+ print("\nResult (Local):")
123
+ print(rag.query(query_text, param=QueryParam(mode="local")))
124
+
125
+ print("\nResult (Global):")
126
+ print(rag.query(query_text, param=QueryParam(mode="global")))
127
+
128
+ print("\nResult (Hybrid):")
129
+ print(rag.query(query_text, param=QueryParam(mode="hybrid")))
130
+
131
+ print("\nResult (mix):")
132
+ print(rag.query(query_text, param=QueryParam(mode="mix")))
133
+
134
+
135
+ if __name__ == "__main__":
136
+ main()