XXXX 本地模型替换为 两家 API
llamaindex_internlm.py
原代码
from llama_index.llms.huggingface import HuggingFaceLLM
from llama_index.core.llms import ChatMessage
llm = HuggingFaceLLM(model_name="/root/model/internlm2-chat-1_8b",tokenizer_name="/root/model/internlm2-chat-1_8b",model_kwargs={"trust_remote_code":True},tokenizer_kwargs={"trust_remote_code":True}
)rsp = llm.chat(messages=[ChatMessage(content="xtuner是什么?")])
print(rsp)
替换后
硅基API
from llama_index.core.llms import ChatMessage
import requestsurl = "https://api.siliconflow.cn/v1/chat/completions"messages = [ChatMessage(content="xtuner是什么?")]payload = {"model": "internlm/internlm2_5-7b-chat","messages": [{"role": "user", "content": msg.content} for msg in messages]
}headers = {"Authorization": "Bearer sk-XXXXXXXXXXXXXXXXXX", # 替换为API key"Content-Type": "application/json"
}response = requests.post(url, json=payload, headers=headers)response_json = response.json()assistant_message = response_json['choices'][0]['message']['content']
print(assistant_message)
运行结果
浦语API
from llama_index.core.llms import ChatMessage
import requests# API endpoint for chat completions
url = "https://internlm-chat.intern-ai.org.cn/puyu/api/v1/chat/completions"# Prepare the message using ChatMessage
messages = [ChatMessage(content="xtuner是什么?")]# Prepare the payload with the model and formatted messages
payload = {"model": "internlm2.5-latest","messages": [{"role": "user", "content": msg.content} for msg in messages],"n": 1,"temperature": 0.8,"top_p": 0.9
}# Specify the authorization token and content type in the headers
headers = {"Authorization": "Bearer eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFM1MTXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", # 替换为你的实际token"Content-Type": "application/json"
}# Send a POST request to the API
response = requests.post(url, json=payload, headers=headers)# Parse the response JSON
response_json = response.json()# Extract and print the content from the assistant's message
assistant_message = response_json['choices'][0]['message']['content']
print(assistant_message)
运行结果
llamaindex_RAG.py
原代码
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settingsfrom llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.llms.huggingface import HuggingFaceLLM#初始化一个HuggingFaceEmbedding对象,用于将文本转换为向量表示
embed_model = HuggingFaceEmbedding(
#指定了一个预训练的sentence-transformer模型的路径model_name="/root/model/sentence-transformer"
)
#将创建的嵌入模型赋值给全局设置的embed_model属性,
#这样在后续的索引构建过程中就会使用这个模型。
Settings.embed_model = embed_modelllm = HuggingFaceLLM(model_name="/root/model/internlm2-chat-1_8b",tokenizer_name="/root/model/internlm2-chat-1_8b",model_kwargs={"trust_remote_code":True},tokenizer_kwargs={"trust_remote_code":True}
)
#设置全局的llm属性,这样在索引查询时会使用这个模型。
Settings.llm = llm#从指定目录读取所有文档,并加载数据到内存中
documents = SimpleDirectoryReader("/root/llamaindex_demo/data").load_data()
#创建一个VectorStoreIndex,并使用之前加载的文档来构建索引。
# 此索引将文档转换为向量,并存储这些向量以便于快速检索。
index = VectorStoreIndex.from_documents(documents)
# 创建一个查询引擎,这个引擎可以接收查询并返回相关文档的响应。
query_engine = index.as_query_engine()
response = query_engine.query("xtuner是什么?")print(response)
修改后:
硅基API
import requests
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.core.settings import Settings# 禁用全局LLM设置中的OpenAI,不然会报错
Settings.llm = None# 初始化嵌入模型
embed_model = HuggingFaceEmbedding(model_name="/root/model/sentence-transformer"
)# 从指定目录读取所有文档,并加载数据到内存中
documents = SimpleDirectoryReader("/root/llamaindex_demo/data").load_data()# 创建一个VectorStoreIndex,指定使用自己的嵌入模型
index = VectorStoreIndex.from_documents(documents, embed_model=embed_model)# 创建一个查询引擎用于本地文档查询,并禁用LLM
query_engine = index.as_query_engine(llm=None)# 准备查询的问题
question = "xtuner是什么?"
local_response = query_engine.query(question)# 将响应转变为字符串形式
local_response_str = str(local_response) # print("本地查询结果:", local_response_str)# 使用自定义API进行外部查询
url = "https://api.siliconflow.cn/v1/chat/completions"
payload = {"model": "internlm/internlm2_5-7b-chat","messages": [{"role": "user", "content": "对以下问题和片段进行总结"+ question + " " + local_response_str}]
}
headers = {"Authorization": "Bearer sk-fzmebtdhrqnhnsnnXXXXXXXXXXXXXXXXX", # 使用你的实际API令牌代替"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)# 打印原始响应,以便调试
# print("原始API响应:", response.text)# 解析响应并提取content字段
try:response_json = response.json()content = response_json['choices'][0]['message']['content']print(content)
except Exception as e:print(f"Error: {str(e)}")
运行结果:
浦语API
import requests
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.core.settings import Settings
import json# 禁用全局LLM设置中的OpenAI,不然会报错
Settings.llm = None# 初始化嵌入模型
embed_model = HuggingFaceEmbedding(model_name="/root/model/sentence-transformer"
)# 从指定目录读取所有文档,并加载数据到内存中
documents = SimpleDirectoryReader("/root/llamaindex_demo/data").load_data()# 创建一个VectorStoreIndex,指定使用自己的嵌入模型
index = VectorStoreIndex.from_documents(documents, embed_model=embed_model)# 创建一个查询引擎用于本地文档查询,并禁用LLM
query_engine = index.as_query_engine(llm=None)# 准备查询的问题
question = "xtuner是什么?"
local_response = query_engine.query(question)# 将响应转变为字符串形式
local_response_str = str(local_response)# print("本地查询结果:", local_response_str)# 使用自定义API进行外部查询
url = "https://internlm-chat.intern-ai.org.cn/puyu/api/v1/chat/completions"
payload = {"model": "internlm2.5-latest","messages": [{"role": "user", "content": "对以下问题和片段进行总结"+ question + " " + local_response_str}],"n": 1,"temperature": 0.8,"top_p": 0.9
}
headers = {"Authorization": "Bearer eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFM1MTIifQXXXXXXXXXXXX", # 使用你的实际API令牌代替"Content-Type": "application/json"
}
response = requests.post(url, data=json.dumps(payload), headers=headers)# 打印原始响应,以便调试
# print(response.text)# 解析JSON响应并直接提取content
try:response_json = response.json()content = response_json['choices'][0]['message']['content']print(content)
except Exception as e:print(f"Error extracting content: {str(e)}")
运行结果: