当前位置:   article > 正文

python调用GPT4的API文档_gpt4 all 其他软件调用

gpt4 all 其他软件调用
导入osopenaiPython 包

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

IPython.display

  1. # Import the os package
  2. import os
  3. # Import the openai package
  4. import openai
  5. # From the IPython.display package, import display and Markdown
  6. from IPython.display import display, Markdown
  7. # Import yfinance as yf
  8. import yfinance as yf

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

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

通过API调用GPT的Code Pattern

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

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

第一次对话:生成数据集

生成示例数据集对于根据不同的数据场景测试代码或向其他人演示代码非常有用。要从 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 中。

  1. # Define the system message
  2. system_msg = 'You are a helpful assistant who understands data science.'
  3. # Define the user message
  4. 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.'
  5. # Create a dataset using GPT
  6. response = openai.ChatCompletion.create(model="gpt-3.5-turbo",
  7. messages=[{"role": "system", "content": system_msg},
  8. {"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))

  1. Here's the Python code to generate the dataset:
  2. import numpy as np
  3. import pandas as pd
  4. # Set random seed for reproducibility
  5. np.random.seed(42)
  6. # Generate random sales data
  7. sales_data = np.random.normal(loc=100000, scale=5000, size=12)
  8. # Create month abbreviation list
  9. month_abbr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  10. # Create dataframe
  11. sales_df = pd.DataFrame({'month': month_abbr, 'total_sales_usd': sales_data})
  12. # Print dataframe
  13. print(sales_df)
  14. And here's the output in markdown format:
  15. | month | total_sales_usd |
  16. |-------|----------------|
  17. | Jan | 98728.961189 |
  18. | Feb | 106931.030292 |
  19. | Mar | 101599.514152 |
  20. | Apr | 97644.534384 |
  21. | May | 103013.191014 |
  22. | Jun | 102781.514665 |
  23. | Jul | 100157.741173 |
  24. | Aug | 104849.281004 |
  25. | Sep | 100007.081991 |
  26. | Oct | 94080.272682 |
  27. | Nov | 96240.993328 |
  28. | Dec | 104719.371461 |

使用辅助函数调用 GPT

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

该函数有两个参数。

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

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

返回值是生成的内容。

  1. def chat(system, user_assistant):
  2. assert isinstance(system, str), "`system` should be a string"
  3. assert isinstance(user_assistant, list), "`user_assistant` should be a list"
  4. system_msg = [{"role": "system", "content": system}]
  5. user_assistant_msgs = [
  6. {"role": "assistant", "content": user_assistant[i]} if i % 2 else {"role": "user", "content": user_assistant[i]}
  7. for i in range(len(user_assistant))]
  8. msgs = system_msg + user_assistant_msgs
  9. response = openai.ChatCompletion.create(model="gpt-3.5-turbo",
  10. messages=msgs)
  11. status_code = response["choices"][0]["finish_reason"]
  12. assert status_code == "stop", f"The status code was {status_code}."
  13. return response["choices"][0]["message"]["content"]

该函数的用法示例是

  1. response_fn_test = chat("You are a machine learning expert.",["Explain what a neural network is."])
  2. display(Markdown(response_fn_test))
  1. 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.
  2. 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.
  3. 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.
  4. 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.

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/199380
推荐阅读
相关标签
  

闽ICP备14008679号