Python调用OpenAI API示例

Posted buchizhuti

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python调用OpenAI API示例相关的知识,希望对你有一定的参考价值。

  1. 使用pip命令导入OpenAI 库:

pip install openai
  1. 连接API

前提:你需要要获取到API_key,自行申请。

import openai
openai.api_key = "YOUR_API_KEY"  #获取的API密钥
  1. 提问,获取反馈

使用openai.Completion.create()方法来生成文本:

import openai
openai.api_key = 'YOUR_API_KEY'

prompt = "请编一个童话故事"
response = openai.Completion.create(
    engine="text-davinci-003",
    prompt=prompt,
    temperature=0.8,
    max_tokens=1000,
    n=1,
    stop=None,
    timeout=20,
)

print(response.choices[0].text)

参数介绍:

prompt:你提问的主体和要求(需求)

engine:使用的OpenAI模型,如:davinci、text-davinci-003等,可以通过访问OpenAI官网来查看全部可用模型

temperature:是用于控制生成文本的随机性的参数,取值在0到1,数值越高,生成的结果越具有创意性

max_tokens:是生成的最大字数

n:要生成的文本的数量

stop:指定停止生成文本的条件

timeout:超时时间(以秒为单位)

当运行上面的代码时,OpenAI API将生成文本并将其存储在response.choices[0].text中,可以将其打印出来或使用它进行其他操作。

通过python 调用OpenAI api_key提交问题解答

通过python 调用OpenAI api_key提交问题解答


  • ✨可以通过网页版的jupyter notebook调用,也可以通过spyder窗口等IDE窗口.

🌼通过python 调用OpenAI api_key接口,可以避免国内网页不能访问的问题。前提是需要自己已经注册了OpenAI帐号,并且在帐号内申请了api_key才行。

jupyter notebook调用

import openai
openai.api_key = "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"
def completion(prompt):
    completions = openai.Completion.create(
        engine="text-davinci-002",
        prompt=prompt,
        max_tokens=1024,
        n=1,
        stop=None,
        temperature=0.8,
    )
    
    message = completions.choices[0].text
    return message
print(completion("基于Keil生成一个8051单片机串口通讯的代码"))
  • 📍返回的结果:
需要实现的功能

1) 串口中断,当收到第一个字节的时候,接收,直到收到数据完成的标志,保存在数组中。

2) 开启接收中断,接收一个字节,当收到第一个字节的时候,接收,直到收到数据完成的标志,保存在数组中。


#### 代码实现


#include<reg52.h>

#define FOSC 11059200L
#define BAUD 9600
#define T1MS (65536-FOSC/12/BAUD)
#define N1 0x40 
#define N2 0x00 
#define BUFFER_SIZE 16
 

sbit LED = P1^1; 
sbit rs = P3^6; 
sbit rw = P3^7; 
sbit en = P3^5; 
sbit buzzer = P2^2; 

unsigned char code table[]=
  0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46,
  0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46,
  0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46,
  0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46
  ;

void delay(int i)

    while(i--);


void write_com(unsigned char com)

    P0 = com;
    rs = 0;
    rw = 0;
    en = 1;
    delay(5);
    en = 0;


void write_dat(unsigned char dat)

    P0 = dat;
    rs = 1;
    rw = 0;
    en = 1;
    delay(5);
    en = 0;


void init()

    write_com(0x38);
    write_com(0x01);
    write_com(0x06);
    write_com(0x0c);
    write_com(0x0f);


void write_str(unsigned char y, unsigned char x, unsigned char *s)

    unsigned char addr;
    if(y == 1)
    addr = 0x80 + x - 1;
    else if(y == 2)
    addr = 0xc0 + x - 1;
    write_com(addr);
    while(*s)
    
        write_dat(*s);
        s++;
    


void write_cmd(unsigned char y, unsigned char x)

    unsigned char addr;
    if(y == 1)
    addr = 0x80 + x - 1;
    else if(y == 2)
    addr = 0xc0 + x - 1;
    write_com(addr);



void lcd_pulse()

    en=1;
    delay(5);
    en=0;



void write_com1(unsigned char command)

    rs=0;
    rw=0;
    P0=command;
    lcd_pulse();


void write_dat1(unsigned char dat)

    rs=1;
    rw=0;
    P0=dat;
    lcd_pulse();



void lcd_init()

    write_com1(0x38);
    write_com1(0x06);
    write_com1(0x0c);
    write_com1(0x01);
    write_com1(0x80);


void write_char(unsigned char c)

    write_dat1(c);


void write_string(unsigned char *s)

    while(*s)
    
        write_char(*s);
        s++;
    



void timer0_init(void) 

    TMOD = 0x01; 
    TH0=T1MS;TL0=T1MS;
    ET0=1; 
    EA=1;
    TR0=1; 


unsigned char hours;
unsigned char minutes;
unsigned char seconds;
unsigned char t;
unsigned char time_update;
unsigned char count;
unsigned char data[BUFFER_SIZE];
unsigned char *p;
void timer0_interrupt() interrupt 1//模拟中断,每1s中断一次 

    TH0=T1MS;TL0=T1MS;
    write_cmd(1,1);
    write_char(table[hours/10]);
    write_char(table[hours%10]);
    write_char(':');
    write_char(table[minutes/10]);
    write_char(table[minutes%10]);
    write_char(':');
    write_char(table[seconds/10]);
    write_char(table[seconds%10]);
    seconds++;
    time_update=1;


void timer1_init()

    TH1=N1;TL1=N2;
    ET1=1;
    EA=1;
    TR1=1;



void timer1_interrupt() interrupt 3

    TH1=N1;TL1=N2;
    if(seconds==60)
    
        seconds=0;
        minutes++;
    
    if(minutes==60)
    
        minutes=0;
        hours++;
    
    if(hours==24)
        hours=0;


void init_serial()

    TMOD=0x20;
    SCON=0x50;
    TL1=N1;TH1=N2;
    ES=1;
    EA=1;
    TR1=1;
    count=0;
    p=data;


void serial_interrupt(void)   interrupt 4 

    if(TI==1)
    
        TI=0;
        count=0;
        p=data;
    
    else
    
        SBUF=0x41+count;
        count++;
        if(count==BUFFER_SIZE)
        
            count=0;
            p=data;
        
        else
            p++;
        RI=0;
    



void main()
  
    write_cmd(1,1);
    write_str(2,1,"  TEMPERATURE  ");
    timer1_init();
    timer0_init();
    lcd_init();
    init_serial();
    while(1)
    
        if(count==BUFFER_SIZE)
        
            write_cmd(1,1);
            write_str(2,1,"  TEMPERATURE  ");
            write_str(1,9,p);
            write_str(2,9,p+8);
        
    

🌻spyder窗口调用

# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

import openai
openai.api_key = "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"

def completion(prompt):
    completions = openai.Completion.create(
        engine="text-davinci-002",
        prompt=prompt,
        max_tokens=2048,
        n=1,
        stop=None,
        temperature=0.8,
    )
    
    message = completions.choices[0].text
    return message

print(completion("stm32f103vct6串口1初始化代码"))
  • 📜openai调用,提问stm32f103vct6串口1初始化代码返回数据:
波特率为115200

//串口初始化函数
//bound:波特率
void uart1_init(u32 bound)

  //GPIO端口设置
  GPIO_InitTypeDef GPIO_InitStructure;
	USART_InitTypeDef USART_InitStructure;
	NVIC_InitTypeDef NVIC_InitStructure;
	 
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1|RCC_APB2Periph_GPIOA|RCC_APB2Periph_AFIO, ENABLE);	//使能USART1,GPIOA,AFIO时钟
  	GPIO_PinRemapConfig(GPIO_Remap_USART1, DISABLE);          //取消复用
	
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; //PA.09
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;	//复用推挽输出
	GPIO_Init(GPIOA, &GPIO_InitStructure); //初始化PA9

	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//浮空输入
	GPIO_Init(GPIOA, &GPIO_InitStructure);//初始化PA10

  //Usart1 NVIC 配置
  NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;//串口1中断通道
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3 ;//抢占优先级3
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;		//子优先级3
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;			//IRQ通道使能
	NVIC_Init(&NVIC_InitStructure);	//根据指定的参数初始化VIC寄存器

   //USART 初始化设置

	USART_InitStructure.USART_BaudRate = bound;//串口设置波特率
	USART_InitStructure.USART_WordLength = USART_WordLength_8b;//字长为8位数据格式
	USART_InitStructure.USART_StopBits = USART_StopBits_1;//一个停止位
	USART_InitStructure.USART_Parity = USART_Parity_No;//无奇偶校验位
	USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//无硬件数据流控制
	USART_InitStructure.USART_Mode = USART_Mode_Tx|USART_Mode_Rx;	//收发模式
	USART_Init(USART1, &USART_InitStructure); //初始化串口1

	USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);//开启串口接受中断
	USART_Cmd(USART1, ENABLE);                    //使能串口1


//串口1中断服务程序
//注意,读取USARTx->SR能避免莫名其妙的错误
void USART1_IRQHandler(void)                	//串口1中断服务程序

	u8 Res;
#if SYSTEM_SUPPORT_OS 	//如果使用OS,由于串口接收中断优先级不能设置过高,因此当遇到串口错误时直接调用OS的相应服务
	OSIntEnter();    
#endif
	if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)  //接收中断(接收到的数据必须是0x0d 0x0a结尾)
	
#if EN_USART1_RX			//如果使能接收
		Res =USART_ReceiveData(USART1);//(USART1->DR);	//读取接收到的数据
		if((USART_RX_STA&0x8000)==0)//接收未完成
		
			if(USART_RX_STA&0x4000)//接收到了0x0d
			
				if(Res!=0x0a)USART_RX_STA=0;//接收错误,重新开始
				else USART_RX_STA|=0x8000;	//接收完成了 
			
			else //还没收到0X0D
				
				if(Res==0x0d)USART_RX_STA|=0x4000;
				else
				
					USART_RX_BUF[USART_RX_STA&0X3FFF]=Res ;
					USART_RX_STA++;
					if(USART_RX_STA>(USART_REC_LEN-1))USART_RX_STA=0;//接收数据错误,重新开始接收	  
						 
			
		   		 
    	if(USART_RX_STA&0x8000)//接收完成
    	
			USART_RX_BUF[USART_RX_STA&0X3FFF]=0;//添加结束符
			memcpy(USART_TX_BUF,USART_RX_BUF,USART_REC_LEN);
			USART_RX_STA=0;//接收状态标记清零	  
    	
#endif 
		
	else if(USART_GetITStatus(USART1, USART_IT_TXE) != RESET)  //发送中断
	
#if EN_USART1_TX			//如果使能了接收
		USART1->DR = Tx1Buffer[Tx1Counter++]; //写DR寄存器数据发送
		if(Tx1Counter == Tx1Count)
			USART1->CR1 &= ~USART_CR1_TXEIE;		//关闭TX发送中断
		
#endif
	


print(completion("stm32f103vct6串口1初始化代码"))
,总线资源申请好后,调用这个函数初始化
	return 0;



//不使用串口,释放资源
static void __exit uart_exit(void)

	//释放设备号
	unregister_chrdev(dev_no,DEV_NAME);
	
	//释放设备结构体
	cdev_del(&uart_cdev);
	
	//删除设备类
	device_destroy(uart_class,MKDEV(dev_no,0));
	
	//释放设备类
	class_destroy(uart_class);

	//释放资源
	
	//1.释放硬件资源:释放ioremap的空间
	iounmap(va);
	
	//2.释放设备号
	release_region(0x40011000,0x400);


module_init(uart_init);
module_exit(uart_exit);
MODULE_LICENSE("GPL");

🍁以上不管那种方式调用,都需要提前安装好openai模块

openai模块安装

  • openai模块安装命令: pip install openai

jupyter notebook安装

  • 安装指令:pip install jupyter
  • 🚩安装完成后,启动命令:jupyter notebook

spyder安装

  • spyder安装命令:pip install spyder
  • 🚩安装完成后,启动命令:spyder

以上是关于Python调用OpenAI API示例的主要内容,如果未能解决你的问题,请参考以下文章

用Python调用OpenAI API做有趣的事

通过python 调用OpenAI api_key提交问题解答

Python调用GPT3.5接口的最新方法

OpenAI模型的API调用与使用-测试

Python 3.X 调用多线程C模块,并在C模块中回调python函数的示例

python 调用 chatgpt