python调用AI
调用api
在python中可以引入api厂商的模块来调用api
使用chatgpt时可以在python中导入openai来调用AI
安装:pip install openai
from openai import OpenAI
client = OpenAI(
api_key="这里是获取的api_key",
base_url="这里默认是https://api.openai.com/v1" #要使用其他的可以用这个传参
)
response = client.chat.completions.create(
messages=[
# 把用户提示词传进来content
{'role': 'user', 'content': "1+1等于几?帮我说列出详细步骤。"},
#可以携带上下文与ai对话的记录
{'role': 'assistant', 'content': "1+1等于几?帮我说列出详细步骤。"},
],
model='gpt-3.5-turbo', # 调用的模型
#其他参数(不全)
stream=false # True 是流逝返回,False是非流逝返回,默认false
max_tokens= 100 #上下文最大token数量(包括提示词)
)
# stream=False的时候,打开这个,启用非流式返回
print(response.choices[0].message.content) #获取返回的内容
# stream=True的时候,启用流示返回
for chunk in response:
print(chunk.choices[0].delta.content, end="", flush=True)
langchain框架
langchain可以用来调用各个厂商的api,并且提供更好的功能
官网:www.langchain.com
教程:
--docs.langchain.com.c
--python.langchain.ac.cn
--zhuanlan.zhihu.com/p/620529542
安装:pip install langchain
以使用openai为例, 安装langchain_openai -- pip install langchain_openai
from langchain_openai import ChatOpenAI
from langchain.schema.messgae import (SystemMessage,HumanMessage,AIMessage) #系统信息,ai信息,人类信息
model = ChatOpenAI(model='模型类型',open_api_key='',其他参数)
message = [
SystemMessage(content='系统提示'),
AIMessage(content='ai对话'),
HumanMessage(conten='正常对话内容')
]
#调用api
response = model.invoke(message)
print(response.content)
使用记忆对象以及格式化
#添加记忆对象对话
from langchain.memory import ConversationBufferMemory
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder #提示模版以及历史占位符
from langchain_openai import ChatOpenAI
memory = ConversationBufferMemory(return_messages=True) #True为列表返回,False为字符串返回
memory.save_context({"input": "我的名字是littled"}, {"output": "你好,littled"}) #对话记录
#构建模版
prompt = ChatPromptTemplate.from_messages(
[
("system", "你是一个乐于助人的助手。"),
MessagesPlaceholder(variable_name="history"),
("human", "{user_input}"), #使用{变量名} 在下面解析格式的时候可以对应占位填入
]
)
history = memory.load_memory_variables({})["history"] #返回的是一个字典,使用['history'] 获取内容
#解析格式输出
message = prompt.invoke({
"user_input": user_input, #输入的信息
'history': history #历史信息
})
model = ChatOpenAI(model="gpt-3.5-turbo",api_key='')
model.invoke(message) #调用api
#上面的记忆链需要手动存储上下文
#使用记忆链可以自动存储用户的输入以及ai的输出
from langchain.chains import ConversationChain
chain = ConversationChain(llm=model, memory=memory)
chain.invoke({"input": "你好,我的名字是粒粒"}) #每次调用都会存储记忆
使用RAG
#RAG(Retrieval augment genarate) 检索增强生成
#原理: 将数据加载后分割,转换成向量存储,在输入对话时在存储里进行检索,相当于是一个知识库,减少上下文的token数量
#1.外部文件加载
#2.使用文本分割器分割加载来的数据
#3.将数据转为向量,需要使用嵌入模型,嵌入模型由各个API大模型厂商提供
#4.使用向量数据库存储向量,可以使用FAISS
RAG使用例子
需要安装的模块:
向量数据库:faiss-cpu
嵌入模型
文本分割:langchain_text_splitters
from langchain.chains import ConversationalRetrievalChain
from langchain.memory import ConversationBufferMemory #记忆链
from langchain_community.document_loaders import TextLoader #纯文本加载器
from langchain_community.vectorstores import FAISS #向量数据库
from langchain_openai import ChatOpenAI
from langchain_openai.embeddings import OpenAIEmbeddings #chatgpt的嵌入模型
from langchain_text_splitters import RecursiveCharacterTextSplitter #文本分割器
#加载纯文本数据
loader = TextLoader("./demo2.txt")
docs = loader.load()
#分割器构建
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=500,
chunk_overlap=40,
separators=["\n", "。", "!", "?", ",", "、", ""]
)
#文本分割
texts = text_splitter.split_documents(docs)
#构建嵌入模型
embeddings_model = OpenAIEmbeddings()
#存入向量库
db = FAISS.from_documents(texts, embeddings_model) #传入分割的文本以及嵌入模型
#获得检索器
retriever = db.as_retriever()
#使用大模型
model = ChatOpenAI(model="gpt-3.5-turbo",api_key='')
memory = ConversationBufferMemory(return_messages=True, memory_key='chat_history', output_key='answer')
#后面2个参数可让该记忆对象可记忆用户对话以及ai提示,不写则不记录
#检索链构建
qa = ConversationalRetrievalChain.from_llm(
llm=model, #大模型
retriever=retriever, #检索器
memory=memory, #记忆对象
chain_type='' #使用的链类型,默认stuff,有 map_reduce,map_rerank,refine
)
question = "卢浮宫这个名字怎么来的?"
response = qa.invoke({"chat_history": memory, "question": question}) #调用api
print(response.content)

浙公网安备 33010602011771号