python操作OpenAI
bash
pip install -U openai
代码:
python
from openai import OpenAI
# 解决请求超时问题
import os
os.environ["http_proxy"] = "http://localhost:7890"
os.environ["https_proxy"] = "http://localhost:7890"
# 需要在实例化OpenAI对象时候,指定秘钥
client = OpenAI(api_key="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")
completion = client.chat.completions.create(
model="gpt-3.5-turbo", # 指定使用的大模型是谁,gpt-3.5-turbo 是chatgpt3.5,
messages=[ # 提示词,
{"role": "system", "content": "你是一个老师."}, # 让chatgpt充当什么身份
{"role": "user", "content": "编写一段歌颂元宵节的歌词"}, # 具体要chatgpt完成的操作了。
# {"role": "assistant", "content": "在这元宵佳节临,灯火闪烁映星河。\n汇聚亲情团圆欢,共享团圆喜庆多。\n饮甜汤圆舒心意,挂灯花灯亮明朗。\n传统民俗传千古,文化传承爱不忘。\n元宵圆圆思亲亲,喜庆团圆共欢颜。"}, # 约束条件或基于什么条件
]
)
print(completion.choices[0].message)
使用langchain调用OpenAI
bash
pip install -U langchain
pip install -U langchain-openai
python
# 解决请求超时问题
import os, openai
from langchain_openai import ChatOpenAI
os.environ["http_proxy"] = "http://localhost:7890"
os.environ["https_proxy"] = "http://localhost:7890"
llm = ChatOpenAI(
openai_api_key="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", # 从OpenAI官方申请秘钥[可以是用户秘钥,也可以是项目秘钥]
model_name="gpt-3.5-turbo" # 默认是gpt-3.5-turbo
)
response = llm.invoke("你是谁?") ## 通过 invoke 传入对话
print(response.content)
response = llm.invoke("编写一段歌颂劳动节的歌词?")
print(response.content)
AI会话
安装模块如下:
bash
pip install -U openai
pip install -U langchain-openai
pip install -U tiktoken # 可视化界面工具 gradio框架的核心模块
代码:
python
import os, openai, gradio as gr
from langchain_openai import OpenAI
from langchain_openai import ChatOpenAI
from langchain.chains import ConversationChain
from langchain.memory import ConversationSummaryBufferMemory
# 解决请求超时问题
os.environ["http_proxy"] = "http://localhost:7890"
os.environ["https_proxy"] = "http://localhost:7890"
os.environ["OPENAI_API_KEY"] = "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"
openai.api_key = os.environ["OPENAI_API_KEY"]
memory = ConversationSummaryBufferMemory(
llm=ChatOpenAI(
# openai_api_key="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", # 从OpenAI官方申请秘钥[可以是用户秘钥,也可以是项目秘钥]
# model_name="gpt-3.5-turbo" # 默认是gpt-3.5-turbo
),
max_token_limit=2048
)
conversation = ConversationChain(
llm=OpenAI(
# api_key="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",
max_tokens=2048,
temperature=0.5),
memory=memory,
)
"""基于记忆体实现对话的历史上下文管理"""
def chat(input, history=[]):
history.append(input)
response = conversation.predict(input=input)
history.append(response)
# history[::2] 切片语法,每隔两个元素提取一个元素,即提取出所有的输入,
# history[1::2]表示从历史记录中每隔2个元素提取一个元素,即提取出所有的输出
# zip函数把两个列表元素打包为元组的列表的方式
responses = [(u, b) for u, b in zip(history[::2], history[1::2])]
print("用户输入:", history[::2])
print("AI回答:", history[1::2])
print("上下文:", responses)
return responses, history
"""可视化界面中实现AI对话"""
with gr.Blocks(css="#chatbot{height:800px} .overflow-y-auto{height:800px}") as demo:
chatbot = gr.Chatbot(elem_id="chatbot")
state = gr.State([])
with gr.Row():
txt = gr.Textbox(show_label=False, placeholder="请输入你的问题.")
txt.submit(chat, [txt, state], [chatbot, state])
# 启动项目
demo.launch(share=True)