OpenAi聊天应用

本文最后更新于:2023年8月29日 下午

本文主要是记录聊天语言模型的使用,也即gpt-3.5-turbo。

1 OpenAi是什么

(以下文本就是用gpt-3.5-turbo生成的)

OpenAI(开放人工智能)是一家人工智能研究组织,由伊隆·马斯克(Elon Musk)、萨姆·阿尔特曼(Sam Altman)、格雷格·布鲁克(Greg Brockman)等人于2015年12月共同创立。OpenAI不仅仅是一家公司,更是一个为了推动人工智能技术进步和保持人工智能安全和透明度的非盈利研究组织。

OpenAI的目标是研究和推动人工智能的发展,让它更好地服务于人类,同时预测和管理这项技术可能带来的风险。为此,OpenAI聚集了一大批人工智能、计算机科学、数学和哲学等领域的顶尖科学家,成为了一个集合了众多知名人才的实验室。

作为一个非盈利研究组织,OpenAI拥有自主的知识产权,也必须公开发表其研究成果。这一方面增加了OpenAI的研究公信力,同时也推动了整个人工智能行业向更开放、透明的方向转变。同时,OpenAI有时也会与大型互联网公司和机构合作,为商业化应用提供技术支持,这一方面也有助于增加商业应用的效益和推动人工智能技术发展。

总的来说,OpenAI是一家非盈利研究机构,致力于人工智能技术的推进和发展,并且秉持着开源、透明、可控等价值,不断推动人工智能技术的向前发展。

2 模型

以下是oepnai目前提供的模型

模型 描述
GPT-3.5 一组在 GPT-3 上改进的模型,可以理解并生成自然语言或代码
DALL·E 可以在给定自然语言提示的情况下生成和编辑图像的模型
Whisper 一种可以将音频转换为文本的模型
Embeddings 一组可以将文本转换为数字形式的模型
Codex 一组可以理解和生成代码的模型,包括将自然语言翻译成代码
Moderation 可以检测文本是否敏感或不安全的微调模型
GPT-3 一组可以理解和生成自然语言的模型

目前最强大,成本最低的模型是gpt-3.5-turbo,它针对聊天进行了优化,但是对于传统的自动填充任务也很有效。gpt-3.5-turbo-0301其实就是2023年3月1日的快照,此模型不会更新,提供3个月支持。

官方说turbo和chatgpt模型系列是相同的,也是目前对话最好的模型,所以这里也只谈对它的使用。这里的文章基本都是openAi - models的翻译,详细内容可以去里面看。

3 限制

tokens限制

在机器学习中,处理文本数据时,通常需要把文本转换成数字类型,这就需要用到 tokenization(令牌化)操作,即将文本转换为由一系列单词或符号构成的标记序列。tokens是这些标记的单位。换句话说,tokens通常表示文本中的单词、标点符号和其他符号。
在使用自然语言生成模型时,tokens的数量通常与输入的文本长度成正比。为了避免模型overfitting或者开销过大,通常会限制tokens的使用数量,所以在OpenAI的GPT-3.5模型中设定了最多4096个可用tokens。注意的是这个4096的限制是请求和应答加起来的大小。

这里有个官方提供的Tokenizer,也有关于如何计算的说明文档,想要知道规则的可以去看看。以下是用python来计算token的方式

  • 安装和导入
    1
    2
    pip install --upgrade tiktoken
    import tiktoken
  • 示例
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    def num_tokens_from_messages(messages, model="gpt-3.5-turbo-0301"):
    """Returns the number of tokens used by a list of messages."""
    try:
    encoding = tiktoken.encoding_for_model(model)
    except KeyError:
    encoding = tiktoken.get_encoding("cl100k_base")
    if model == "gpt-3.5-turbo-0301": # note: future models may deviate from this
    num_tokens = 0
    for message in messages:
    num_tokens += 4 # every message follows <im_start>{role/name}\n{content}<im_end>\n
    for key, value in message.items():
    num_tokens += len(encoding.encode(value))
    if key == "name": # if there's a name, the role is omitted
    num_tokens += -1 # role is always required and always 1 token
    num_tokens += 2 # every reply is primed with <im_start>assistant
    return num_tokens
    else:
    raise NotImplementedError(f"""num_tokens_from_messages() is not presently implemented for model {model}.
    See https://github.com/openai/openai-python/blob/main/chatml.md for information on how messages are converted to tokens.""")

    messages = [
    {"role": "system", "content": "You are a helpful, pattern-following assistant that translates corporate jargon into plain English."},
    {"role": "system", "name":"example_user", "content": "New synergies will help drive top-line growth."},
    {"role": "system", "name": "example_assistant", "content": "Things working well together will increase revenue."},
    {"role": "system", "name":"example_user", "content": "Let's circle back when we have more bandwidth to touch base on opportunities for increased leverage."},
    {"role": "system", "name": "example_assistant", "content": "Let's talk later when we're less busy about how to do better."},
    {"role": "user", "content": "This late pivot means we don't have time to boil the ocean for the client deliverable."},
    ]

    model = "gpt-3.5-turbo-0301"

    print(f"{num_tokens_from_messages(messages, model)} prompt tokens counted.")

使用openai的库就简单许多了:

1
2
3
4
5
6
7
8
9
import openai

response = openai.ChatCompletion.create(
model=model,
messages=messages,
temperature=0,
)

print(f'{response["usage"]["prompt_tokens"]} prompt tokens used.')

tokens的消耗实际上是付费的,每个模型定价都不同,在这里可以看到详情,其中gpt-3.5-turbo的加个是$0.002 / 1K tokens。但是嘛,有白嫖阶段,新号有3个月18美金的免费额度。就gpt-3.5-turbo的定价,自己用想用完还是挺难的。

速率限制

免费用户每分钟可以请求20次,详细可见文档

4 API

POST地址:

1
2
3
4
5
6
7
8
9
10
11
12
https://api.openai.com/v1/chat/completions
```

简单示例:
```shell
curl https://api.openai.com/v1/chat/completions \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer YOUR_API_KEY' \
-d '{
"model": "gpt-3.5-turbo",
"messages": [{"role": "user", "content": "Hello!"}]
}'

参数:

  • model模型选择,gpt-3.5-turbo 或 gpt-3.5-turbo-0301
  • messages 聊天消息,是个对象数组,每个对象有一个角色(”system”,”user”,”assistant”)。例如:
1
2
3
4
{"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?"}

系统消息主要是设置它的行为,我一般把他当作拟定人设。用户消息和助手消息其实就是对话和应答,保存下来就可以使之后稳定能联系上下文了。

  • temperature 默认1,输出随机性的控制,介于 0 和 2 之间。较高的值(如 0.8)将使输出更加随机,而较低的值(如 0.2)将使输出更加集中和确定。
  • top_p 默认1 一种替代temperature采样的方法,称为核采样,其中模型考虑具有 top_p 概率质量的标记的结果。所以 0.1 意味着只考虑构成前 10% 概率质量的标记。
  • n 默认为1,生成几种回答
  • stream 默认为false,逐个吐出结果,还是一起。
  • stop 字符串或者数组,默认为null,当检测到会立即停止
  • max_tokens 最大token数,默认4096,前文有描述
  • presence_penalty -2.0 和 2.0 之间的数字。正值会根据到目前为止是否出现在文本中来惩罚新标记,从而增加模型谈论新主题的可能性。详见
  • frequency_penalty -2.0 和 2.0 之间的数字。正值会根据新标记在文本中的现有频率对其进行惩罚,从而降低模型逐字重复同一行的可能性。详见
  • logit_bias
  • user 唯一标识,防止滥用,我这个人账号就不需要了

应答示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"id": "chatcmpl-123",
"object": "chat.completion",
"created": 1677652288,
"choices": [{
"index": 0,
"message": {
"role": "assistant",
"content": "\n\nHello there, how may I assist you today?",
},
"finish_reason": "stop"
}],
"usage": {
"prompt_tokens": 9,
"completion_tokens": 12,
"total_tokens": 21
}
}

python的openai库

代码被开源在github,文档有对其使用说明

安装和导入:

1
2
pip install --upgrade openai
import openai

使用:

1
2
3
4
 response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=   [{"role": "user", "content": "你好"}],
            )

response的返回示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
"choices": [
{
"finish_reason": "stop",
"index": 0,
"message": {
"content": "\n\n\u4f60\u597d\uff01\u6709\u4ec0\u4e48\u6211\u53ef\u4ee5\u5e2e\u4f60\u7684\u5417\uff1f",
"role": "assistant"
}
}
],
"created": 1678137168,
"id": "chatcmpl-6rHb3F5123oHPJRtNl321hY6ZfsnVMo",
"model": "gpt-3.5-turbo-0301",
"object": "chat.completion",
"usage": {
"completion_tokens": 18,
"prompt_tokens": 9,
"total_tokens": 27
}
}

其中content保存了应答的消息,total_tokens返回了总消耗tokens

1
2
content = response.choices[0].message.content.strip()
tokens = response.usage.total_tokens

OpenAi聊天应用
https://blog.kala.love/posts/3ccded78/
作者
Lissettecarlr
发布于
2023年3月7日
许可协议