发布时间:2023-04-19 文章分类:电脑百科 投稿人:樱花 字号: 默认 | | 超大 打印

目录

文章目录

  • 目录
  • OpenAI Python SDK
  • openai.ChatCompletion 模块
    • openai.ChatCompletion.create 函数
  • OpenAPI client 代码示例

OpenAI Python SDK

OpenAI Python SDK 用于开发与 OpenAI RESTful API 进行交互的客户端应用程序,包含了 OpenAI 的各种人工智能模型的 API。

OpenAI Python SDK 提供了多个模块,每个模块都具有一套自包含的 APIs,包括:

openai.ChatCompletion 模块

OpenAI ChatCompletion 模块用于访问 ChatGPT 语言模型,用于实现对话式(Chat)AI 应用程序。

openai.ChatCompletion.create 函数

函数作用:与 ChatGPT 进行 C/S 交互,返回 AI 模型生成的对话文本。注意,该接口是 Stateless 的,每次调用都不包含对话的上下文。这意味着需要客户端应用程序自己维护 “聊天记录“。

函数原型

def create(
    model: str,
    messages: str,
    max_tokens: Optional[int] = None,
    temperature: Union[int, float] = 0.5,
    top_p: Union[int, float] = 1.0,
    frequency_penalty: Union[int, float] = 0,
    presence_penalty: Union[int, float] = 0,
    stop: Optional[Union[str, List[str]]] = None,
    n: Optional[int] = 1,
    max_examples: Optional[int] = None,
    logprobs: Optional[int] = None,
    echo: bool = True,
    **kwargs,
) -> Dict[str, Union[str, List[str]]]:
    pass
curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -d '{
     "model": "gpt-3.5-turbo",
     "messages": [{"role": "user", "content": "Say this is a test!"}],
     "temperature": 0.7
   }'
{
   "id":"chatcmpl-abc123",
   "object":"chat.completion",
   "created":1677858242,
   "model":"gpt-3.5-turbo-0301",
   "usage":{
      "prompt_tokens":13,
      "completion_tokens":7,
      "total_tokens":20
   },
   "choices":[
      {
         "message":{
            "role":"assistant",
            "content":"\n\nThis is a test!"
         },
         "finish_reason":"stop",
         "index":0
      }
   ]
}
messages = [
     {"role": "system", "content": "You are a helpful assistant."},
     {"role": "user", "content": "Who won the world series in 2020?"},
     {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
     {"role": "user", "content": "Where was it played?"}
]

OpenAPI client 代码示例

import openai
import configparser
import time
config = configparser.ConfigParser()
config.read('./config.ini')
class OpenAIClient(object):
    def __init__(self):
        super(OpenAIClient, self).__init__()
        openai.api_key = config.get('OpenAI', 'API_SECRET_KEY')
        self.max_retry = 3
        self.retry_delay = 5
        self.timeout = 10
    def _make_request(self, role, content):
        print("*************************************")
        print("request role: ", role)
        print("request content: ", content)
        print("*************************************")
        if role not in ['user', 'system', 'assistant']:
            print(f'role [{role}] not found.')
            raise
        retry_count = 0
        while retry_count < self.max_retry:
            try:
                response = openai.ChatCompletion.create(
                    model=config.get('OpenAI', 'MODEL'),
                    messages=[{"role": role, "content": content}],
                    max_tokens=2048,
                    n=1,
                    stop=None,
                    temperature=0.7,
                    timeout=self.timeout
                )
                return response
            except Exception as e:
                print(f"Failed to connect to API server, detail error as {e}, retrying in {self.retry_delay} seconds ({retry_count+1}/{self.max_retry})")
                time.sleep(self.retry_delay)
                retry_count += 1
    def chat_request(self, content):
        role = "user"
        return self._make_request(role, content)
    def prompt_request(self, content):
        role = "system"
        return self._make_request(role, content)
    def parser_response(self, response):
        result = []
        choices = response.choices
        for cho in choices:
            result.append(
                {
                    'index': cho['index'],
                    'role': cho['message']['role'],
                    'content': cho['message']['content']
                }
            )
        return result
if __name__ == '__main__':
    cli = OpenAIClient()
    resp = cli.chat_request(content='hello!')
    print("Test response: ", cli.parser_response(resp))
[OpenAI]
API_SECRET_KEY = your_api_key
MODEL = gpt-3.5-turbo