python调用GPT4的API文档

导入osopenaiPython 包

若使用的是 Jupyter Notebook(例如 DataCamp Workspace),从 导入一些函数也很有帮助

IPython.display

# Import the os package
import os

# Import the openai package
import openai

# From the IPython.display package, import display and Markdown
from IPython.display import display, Markdown

# Import yfinance as yf
import yfinance as yf

另一个设置任务是将刚刚创建的环境变量放在 openai 包可以看到的位置。

# Set openai.api_key to the OPENAI environment variable
openai.api_key = os.environ["OPENAI"]

通过API调用GPT的Code Pattern

调用 OpenAI API 并获取聊天响应的代码模式如下:

response = openai.ChatCompletion.create(
              model="MODEL_NAME",
              messages=[{"role": "system", "content": 'SPECIFY HOW THE AI ASSISTANT SHOULD BEHAVE'},
                        {"role": "user", "content": 'SPECIFY WANT YOU WANT THE AI ASSISTANT TO SAY'}
              ])

第一次对话:生成数据集

生成示例数据集对于根据不同的数据场景测试代码或向其他人演示代码非常有用。要从 GPT 获得有用的响应,您需要精确并指定数据集的详细信息,包括:

  • 行数和列数

  • 列的名称

  • 每列包含内容的描述

  • 数据集的输出格式

eg.

Create a small dataset about total sales over the last year. 
The format of the dataset should be a data frame with 12 rows and 2 columns. 
The columns should be called "month" and "total_sales_usd". 
The "month" column should contain the shortened forms of month names 
from "Jan" to "Dec". The "total_sales_usd" column should 
contain random numeric values taken from a normal distribution 
with mean 100000 and standard deviation 5000. Provide Python code to 
generate the dataset, then provide the output in the format of a markdown table.

让我们将此消息包含在前面的 Code Pattern 中。

# Define the system message
system_msg = 'You are a helpful assistant who understands data science.'

# Define the user message
user_msg = 'Create a small dataset about total sales over the last year. The format of the dataset should be a data frame with 12 rows and 2 columns. The columns should be called "month" and "total_sales_usd". The "month" column should contain the shortened forms of month names from "Jan" to "Dec". The "total_sales_usd" column should contain random numeric values taken from a normal distribution with mean 100000 and standard deviation 5000. Provide Python code to generate the dataset, then provide the output in the format of a markdown table.'

# Create a dataset using GPT
response = openai.ChatCompletion.create(model="gpt-3.5-turbo",
                                        messages=[{"role": "system", "content": system_msg},
                                         {"role": "user", "content": user_msg}])
检查 GPT 的响应是否正常

GPT 模型返回带有四个值之一的状态代码,这些值记录在聊天文档的响应格式部分中。

  • stop:API返回完整的模型输出

  • length:由于 max_tokens 参数或 token 限制导致模型输出不完整

  • content_filter:由于我们的内容过滤器中的标记而省略了内容

  • null:API 响应仍在进行中或不完整

GPT API 以 JSON 格式将数据发送到 Python,因此响应变量包含深度嵌套的列表和字典。工作起来有点痛苦!

对于名为 的响应变量response,状态代码存储在以下位置。

response["choices"][0]["finish_reason"]

响应内容可以像平常一样打印print(content),但它是 Markdown 内容,Jupyter 笔记本可以通过以下方式渲染:display(Markdown(content))

Here's the Python code to generate the dataset:

import numpy as np
import pandas as pd
# Set random seed for reproducibility
np.random.seed(42)
# Generate random sales data
sales_data = np.random.normal(loc=100000, scale=5000, size=12)
# Create month abbreviation list
month_abbr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
# Create dataframe
sales_df = pd.DataFrame({'month': month_abbr, 'total_sales_usd': sales_data})
# Print dataframe
print(sales_df)

And here's the output in markdown format:

| month | total_sales_usd |

|-------|----------------|

| Jan | 98728.961189 |

| Feb | 106931.030292 |

| Mar | 101599.514152 |

| Apr | 97644.534384 |

| May | 103013.191014 |

| Jun | 102781.514665 |

| Jul | 100157.741173 |

| Aug | 104849.281004 |

| Sep | 100007.081991 |

| Oct | 94080.272682 |

| Nov | 96240.993328 |

| Dec | 104719.371461 |

使用辅助函数调用 GPT

希望 OpenAI 能够改进其 Python 包的接口,以便内置此类功能。同时,请随意在您自己的代码中使用它。

该函数有两个参数。

  • system:包含系统消息的字符串。

  • user_assistant:交替用户消息和助理消息的字符串数组。

返回值是生成的内容。

def chat(system, user_assistant):
  assert isinstance(system, str), "`system` should be a string"
  assert isinstance(user_assistant, list), "`user_assistant` should be a list"
  system_msg = [{"role": "system", "content": system}]
  user_assistant_msgs = [
      {"role": "assistant", "content": user_assistant[i]} if i % 2 else {"role": "user", "content": user_assistant[i]}
      for i in range(len(user_assistant))]

  msgs = system_msg + user_assistant_msgs
  response = openai.ChatCompletion.create(model="gpt-3.5-turbo",
                                          messages=msgs)
  status_code = response["choices"][0]["finish_reason"]
  assert status_code == "stop", f"The status code was {status_code}."
  return response["choices"][0]["message"]["content"]

该函数的用法示例是

response_fn_test = chat("You are a machine learning expert.",["Explain what a neural network is."])

display(Markdown(response_fn_test))
A neural network is a type of machine learning model that is inspired by the architecture of the human brain. It consists of layers of interconnected processing units, called neurons, that work together to process and analyze data.

Each neuron receives input from other neurons or from external sources, processes that input using a mathematical function, and then produces an output that is passed on to other neurons in the network.

The structure and behavior of a neural network can be adjusted by changing the weights and biases of the connections between neurons. During the training process, the network learns to recognize patterns and make predictions based on the input it receives.

Neural networks are often used for tasks such as image classification, speech recognition, and natural language processing, and have been shown to be highly effective at solving complex problems that are difficult to solve with traditional rule-based programming methods.

  • 24
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 如果您想通过Python调用OpenAI的GPT-3模型,您可以使用OpenAI的SDK,它提供了一个简单的Python接口来访问GPT-3。 首先,您需要注册一个OpenAI账户,然后创建一个API密钥,您可以在此密钥中找到您的API ID和API密码。 接下来,您可以使用以下代码安装OpenAI的SDK: ``` pip install openai ``` 接下来,您可以使用以下代码导入OpenAI的SDK并调用GPT-3: ``` import openai # Set up the OpenAI API client openai.api_key = "YOUR_API_KEY" # Generate text from the GPT-3 model model_engine = "text-davinci-002" prompt = "Hello, world!" completions = openai.Completion.create( engine=model_engine, prompt=prompt, max_tokens=1024, n=1, stop=None, temperature=0.5, ) message = completions.choices[0].text print(message) ``` 在上面的代码中,您可以替换`YOUR_API_KEY`为您的API密钥,并调整其他参数以满足您的需求。 请注意,OpenAI对GPT-3的使用是收费的,并且您可能需要订阅更高级别的计划才能访问更多功能。 ### 回答2: 要使用Python调用chatGPTAPI,你需要按照以下步骤进行: 1. 首先,确保已安装好Python,并安装了相关库和软件包,如requests和json等库。 2. 确保你已经获取了chatGPTAPI密钥。如果没有,请访问OpenAI的官方网站,并按照他们提供的指导获取API密钥。 3. 创建一个Python脚本,并导入所需的库。你需要使用requests库来发送HTTP请求,并使用json库来处理返回的JSON数据。 4. 在Python脚本中,使用requests库发送POST请求到chatGPTAPI端点。使用requests.post()方法,并传入API端点的URL作为参数。同时,将API密钥作为HTTP头的Authorization字段进行传递。 5. 在POST请求的正文中,包含一个JSON对象,以传递你要询问的聊天内容。这个JSON对象应该包含一个"messages"键,并传入一个包含聊天对话的列表。每个聊天对话应该包含一个"role"和"content"字段,分别表示角色和对话内容。 6. 发送请求后,使用response.json()方法获取返回的JSON数据,并解析它以获取聊天GPT的回复。你可以使用json库的方法来从返回的JSON数据中提取回复。 7. 最后,根据需要处理和使用chatGPT的回复。 这样,你就可以使用Python调用chatGPTAPI进行聊天。记得妥善处理你的API密钥,并根据需要进行错误处理和数据处理。 ### 回答3: 要使用Python调用ChatGPTAPI,需要首先导入所需的库。你可以使用`requests`库来发送HTTP请求。然后,你需要创建一个Python函数,该函数将接收你要发送的聊天消息,并发送POST请求到ChatGPTAPI端点。以下是一个简单的示例: ```python import requests def call_chatGPT_api(message): # 定义API端点 api_endpoint = "https://api.openai.com/v1/chat/completions" # 设置请求头 headers = { "Content-Type": "application/json", "Authorization": "Bearer YOUR_API_KEY" } # 设置请求数据 data = { "messages": [{"role": "system", "content": "你是一个助手"}, {"role": "user", "content": message}] } # 发送POST请求 response = requests.post(api_endpoint, headers=headers, json=data) # 处理响应 if response.status_code == 200: output = response.json() return output['choices'][0]['message']['content'] else: return "请求失败" # 调用以上函数发送聊天消息,并获取响应 response = call_chatGPT_api("你好") print(response) ``` 在上述代码的`YOUR_API_KEY`处,需要替换成你自己的ChatGPT API密钥。你可以在openai.com上的API设置中找到此密钥。代码中的`call_chatGPT_api`函数接受一个消息作为参数,并将其发送到API。然后,它将返回API的响应中的回复消息。 请确保你已安装`requests`库(可以使用`pip install requests`命令)。记得要根据ChatGPT API文档进行调整,以满足你的具体需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值