环境:google的colab
问题1:
import openai
openai.api_key = "sk-xxxxxxx"
openai.api_base = "https://api.gpts.vin/v1";
优化写法:
import os
import openai
# 设置OpenAI API密钥为环境变量
os.environ["OPENAI_API_KEY"] = "sk-xxxxxxx"
# 设置OpenAI API基础网址为环境变量(可选,如果你想修改它)
os.environ["OPENAI_API_BASE"] = "https://api.gptsxxxxxxx"
# 设置openai模块的api_key和api_base为环境变量中的值
openai.api_key = os.getenv("OPENAI_API_KEY")
openai.api_base = os.getenv("OPENAI_API_BASE")
编写函数:
prompt = 'What is 1+1?'
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": prompt}
]
)
# Print the response content
print(response.choices[0].message.content)
报错:You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0 - see the README at https://github.com/openai/openai-python for the API.
You can run openai migrate
to automatically upgrade your codebase to use the 1.0.0 interface.
Alternatively, you can pin your installation to the old version, e.g. pip install openai==0.28
A detailed migration guide is available here: https://github.com/openai/openai-python/discussions/742
但是我在github上面的Usage上找到的代码运行也还是这个错误,不得已,我把openai降到了0.28版本,客服了这个问题。
初尝试:
prompt = f"""Translate the text \
that is delimited by triple backticks
into a style that is {style}.
text:```{customer_email}```
"""
print(prompt)
可以看到 上面粗俗的话语被转化成功。
接下来使用Longchain
安装:!pip install langchain
pip install langchain-community langchain-core
这两个下好后运行from langchain.chat_models import ChatOpenAI
可以看到 下面的信息展示了输入时style 和 text 后面包括了要求。
使用解析器 进阶
customer_review = """\
This leaf blower is pretty amazing.It has four settings: \
candle blower, gentle breeze, windy city,and tornado. \
It arrived in two days, just in tiem for my wife's \
anniversary present.\
I think my wife liked it so much she was sprechless. \
So far I've been the only one using it, and I've been \
using it every other morning to clear the leaves on out lawrity \
It's slightly more expensive than the other leaf blowers \
out there, but I think it's worth it for the extra features.
"""
review_template = """
For the following text,txtract the following information: \
gift:Was the item purchased as a gift for someone else?If yes, answer yes; if no or unknown, answer no.\
delivery_days:How many days didi it take for the product to arrive?If the information is not found, -1 is output.\
price_values:Extract any sentences about the value or price, \
Format the output as JSON with the following keys:
gift
delivery_days
price_value
text:{text}
"""
from langchain.prompts import ChatPromptTemplate
prompt_template = ChatPromptTemplate.from_template(review_template)
print(prompt_template)
messages = prompt_template.format_messages(text=customer_review)
chat = ChatOpenAI(temperature=0.0)
response = chat(messages)
print(response.content)