当前位置:   article > 正文

OpenAI API 使用指南_openai api使用

openai api使用

 


接口调用

模型列表:https://platform.openai.com/docs/models

计费说明:https://openai.com/pricing

接口文档:https://platform.openai.com/docs/api-reference/introduction

淘宝上有卖,5元一个(sk-xxx)。

注意一些卖家坑,给的 OpenAI 可能没验证银行卡,导致一分钟只能回复 3 次。

api_key = '淘宝买的 (sk-xxx)'

from openai import OpenAI  # 从 openai 模块导入 OpenAI 类
client = OpenAI(api_key)  # 创建一个 OpenAI 客户端实例,使用提供的 api_key

# 使用指定的模型 "No models available" 来创建聊天完成任务
completion = client.chat.completions.create(
  model="gpt-3.5-turbo",  # 指定模型名
  messages=[
    {"role": "system", "content": "You are a helpful assistant."},  # 系统消息,设置助手的角色
    {"role": "user", "content": "Hello!"}  # 用户消息,开始对话
  ],
  stream=True  # 开启流模式,实时接收响应
)

# 循环遍历 completion 对象中的每个响应块
for chunk in completion:
  print(chunk.choices[0].delta)  # 打印每个响应块的内容
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

role 字段用来定义消息的发送者角色,具体包括三种选择:systemuser、和 assistant

  1. system(系统提示):

    • 用途:通常用于设置聊天的上下文或者提供系统级别的指示和配置信息。
    • 场景:比如在对话开始前,系统可以发送一条消息来设定对话的规则或者说明助手的功能。
  2. user(用户):

    • 用途:代表实际的用户输入,即用户向聊天系统提出的问题或者发起的对话内容。
    • 场景:用户的任何提问、命令或者交流都通过这个角色来表达,这是聊天流程中最常见的角色。
  3. assistant(智能助手):

    • 用途:代表智能助手的回复或者动作,是模型根据用户输入给出的响应。
    • 场景:在接收到用户的消息后,助手根据用户的需求提供信息、答案或者执行特定的任务。

这三种角色共同构成了聊天的完整流程,其中系统角色可用于初始化设置,用户角色表达用户需求,智能助手角色则是响应这些需求,完成交互。
 


多轮对话

from openai import OpenAI  # 从 openai 模块导入 OpenAI 类

api_key = '淘宝买的 (sk-xxx)'  # 定义API密钥
client = OpenAI(api_key)  # 创建一个 OpenAI 客户端实例,使用提供的 api_key

# 初始化消息历史,首先包含一个系统提示和一个用户的问候
messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Hello!"}
]

# 开启一个循环以处理多轮对话
while True:
    # 输出助手的最新回复(如果有)
    if messages[-1]['role'] == 'assistant':
        print('Assistant:', messages[-1]['content'])
    
    # 获取用户的输入
    user_input = input("User: ")
    # 将用户的新消息添加到消息历史中
    messages.append({"role": "user", "content": user_input})
    
    # 请求模型生成回答
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",  # 使用指定的模型
        messages=messages,  # 提供到目前为止的对话历史
        stream=False  # 设置为False,因为我们每次都等待完整的回答
    )
    
    # 提取模型的回答并添加到消息历史中
    asst_content = response.choices[0].message['content']
    messages.append({"role": "assistant", "content": asst_content})
  • 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

句子的文本嵌入:相关文本检索,根据向量相似度

接口文档:https://platform.openai.com/docs/api-reference/embeddings

可选模型:https://openai.com/blog/new-and-improved-embedding-model

api_key = '淘宝买的 (sk-xxx)'  # 定义API密钥

from openai import OpenAI                      # 从openai导入OpenAI
client = OpenAI(api_key)                             # 创建OpenAI客户端实例

res = client.embeddings.create(                     # 创建嵌入
  model="text-embedding-ada-002",             # 模型为"text-embedding-ada-002"
  input="The food was delicious and the waiter...",  # 输入文本
  encoding_format="float"                     # 编码格式为浮点数
)
print(  len(res.data[0].embedding)  )  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

相似文本召回

假设你是一个用户,想要找到关于感冒治疗的最佳建议,尤其是关于阿莫西林的使用。

场景设定

用户查询:“感冒吃什么药效果好?可以吃阿莫西林吗?”

备选问题文本集合:

  • “什么叫感冒? / 感冒是一种什么病?”
  • “感冒一般是由什么引起的?/ 什么会导致感冒?”
  • “感冒会有哪些症状?/ 感冒有哪些临床表现?”
  • “感冒吃什么药好得快?/ 感冒怎么治?”
  • “得了感冒去医院挂什么科室的号?”
  • “感冒要怎么预防?”
  • “感冒换着有什么禁忌?/ 感冒不能吃什么?”
  • “感冒要做哪些检查?”
  • “感冒能治好吗?/ 感冒治好的几率有多大?”
  • “感冒的并发症有哪些?”
  • “阿莫西林能治那些病?”

实施步骤

  1. 查询语句向量化: 用户的查询被转化为一个数字向量,代表其语义内容。
  2. 备选文本向量化: 上述每个问题也被转化为数字向量。
  3. 计算欧式距离: 使用欧式距离公式计算查询向量与每个问题向量之间的距离。
  4. 选择最相似的文本: 根据计算出的距离,选择三个最接近的问题作为回答。

示例输出

假设在距离计算后,三个最相似的问题是:

  • “感冒吃什么药好得快?/ 感冒怎么治?”
  • “阿莫西林能治那些病?”
  • “感冒的并发症有哪些?”

当用户的查询处理完毕后,这三个问题的文本将被显示给用户,帮助他们获得关于感冒治疗的具体信息,尤其是关于是否可以使用阿莫西林的详细解答。

这个过程有效地将用户的自然语言查询转化为可以操作的数据(向量),通过数学方法找到最相关的回答,从而提供具体而有用的医疗建议。

from openai import OpenAI
import numpy as np

api_key = '淘宝买的 (sk-xxx)'  # 定义API密钥
# Create an instance of the OpenAI client
client = OpenAI(api_key)

# User query
query = '感冒吃什么药效果好?可以吃阿莫西林吗?'

# Vectorize the query
query_resp = client.embeddings.create(
    model="text-embedding-ada-002",
    input=query
)
query_vec = np.array(query_resp.data[0].embedding)

# List of potential questions (备选文本)
question_texts = [
    '什么叫感冒? / 感冒是一种什么病?',
    '感冒一般是由什么引起的?/ 什么会导致感冒?',
    '感冒会有哪些症状?/ 感冒有哪些临床表现?',
    '感冒吃什么药好得快?/ 感冒怎么治?',
    '得了感冒去医院挂什么科室的号?',
    '感冒要怎么预防?',
    '感冒换着有什么禁忌?/ 感冒不能吃什么?',
    '感冒要做哪些检查?',
    '感冒能治好吗?/ 感冒治好的几率有多大?',
    '感冒的并发症有哪些?',
    '阿莫西林能治那些病?'
]

# Vectorize the questions
question_resp = client.embeddings.create(
    model="text-embedding-ada-002",
    input=question_texts
)
question_vecs = [np.array(item.embedding) for item in question_resp.data]

# Calculate Euclidean distances
l2_distances = np.linalg.norm(query_vec - question_vecs, axis=1)

# Get indices of the three closest questions
closest_indices = np.argsort(l2_distances)[:3]

# Output the most similar questions
for idx in closest_indices:
    print(question_texts[idx])
  • 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
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/1007645
推荐阅读
相关标签
  

闽ICP备14008679号