当前位置: 首页 > news >正文

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)}")

运行结果:


http://www.mrgr.cn/news/63119.html

相关文章:

  • 在MySQL中存储IP地址的最佳实践
  • C#入坑JAVA MyBatis入门 CURD 批量 联表分页查询
  • 程序中怎样用最简单方法实现写excel文档
  • [java][高级]FilterListenerAjax
  • 【SSM-Day5】SpringMVC入门
  • [论文精读]LoRA: Low-Rank Adaptation of Large Language Models
  • 环境变量——用户变量和系统变量
  • (实战)WebApi第9讲:EFCore性能优化(IQueryable延迟查询、取消跟踪机制)
  • Python爬虫必备利器:urllib库全面解析
  • 在树莓派 Raspbian 11 上使用 pyenv 安装 Python 3.9
  • Maven 插件
  • 基于单片机的宠物自动喂食系统的设计
  • Vue 动态属性 []
  • 2024年10月总结及随笔之漏更及失而复得
  • 多线程和线程同步基础篇学习笔记(Linux)
  • 微服务实战系列之玩转Docker(十七)
  • 【2024工业图像异常检测文献】SuperSimpleNet: 统一无监督和监督式学习检测快速可靠的表面缺陷检测方法
  • 数字信号处理Python示例(1)使用Python生成正弦信号
  • 模板初阶及STL简介
  • OpenAI推出搜索GPT,进军搜索引擎领域
  • c++/qt连接阿里云视觉智能开发平台
  • 【图书介绍】案例可借鉴的Spring应用开发书
  • RabbitMQ的发布订阅模式
  • CSS 动画:网页设计的动态之美
  • 流水线(Pipeline)技术
  • ARKit读取LiDAR点云