Python Notes 1 - introduction with the OpenAI API Development

Official document:https://platform.openai.com/docs/api-reference/chat/create

1. Use APIfox to call APIs

2.Use PyCharm to call APIs

2.1-1 WIN OS.Configure the Enviorment variable

#HK代理环境,不需要科学上网(价格便宜、有安全风险,适合个人开发调试)
setx OPENAI_BASE_URL "https://api.openai-hk.com/v1"
setx OPENAI_API_KEY "hk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

#官方环境,需要科学上网(价格高、安全可靠,适合个人企业生产部署)
setx OPENAI_BASE_URL "https://api.openai.com/v1"
setx OPENAI_API_KEY "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

Temporaily use the API through HK proxy.

Check if environment variable is configured successfully.

import osprint(os.getenv('OPENAI_BASE_URL'))

2.1-2 MAC OS Configure the Environment variable

#HK代理环境,不需要科学上网
export OPENAI_BASE_URL='https://api.openai-hk.com/v1'
export OPENAI_API_KEY='hk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

#官方环境,需要科学上网
export OPENAI_BASE_URL='https://api.openai.com/v1'
export OPENAI_API_KEY='sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

 if Mac os is unable to read the configured environment variables,u need to modify the .zshrc file.

Refer to the URL below.

MacOS环境变量source生效但重启后又失效 - 程序员小艺 - 博客园

2.2 Call an API using PyCharm

2.2.1.as APIfox(HTTPClient):Make a POST request to call the API,similar to how it's done in APIfox.

import requests
import json
import osurl = os.getenv('OPENAI_BASE_URL') + "/chat/completions"
# print(os.getenv('OPENAI_BASE_URL'))
payload = json.dumps({"model": "gpt-4o","messages": [{"role": "system", "content": "assistant"},{"role": "user", "content": "Hello"}]
})
headers = {'Content-Type': 'application/json','Authorization': 'Bearer ' + os.getenv('OPENAI_API_KEY'),
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)

2.2.2 Use the offical SDK to call the API

First,domwload the OpenAI package using the console and import it.

# pip install openai==1.40.3

Call the API using the SDK

from openai import OpenAI
# pip install openai==1.40.3
import os
# 从环境变量中读取OPENAI_BASE_URL
print(os.getenv('OPENAI_BASE_URL'))
# 初始化 OpenAI 服务。
client = OpenAI()
completion = client.chat.completions.create(model="gpt-4o",messages=[{"role": "system", "content": "assistant"},{"role": "user", "content": "Hello"}]
)
print(completion.choices[0].message.content)

There was a problem when running the code

Traceback (most recent call last):
  File "D:\BaiduNetdiskDownload\AIapp\sub\1_AI及LLM基础\day02_OpenAI 开发\day2-demo\sdk_call.py", line 7, in <module>
    clien = OpenAI()
  File "C:\Users\Administrator\PycharmProjects\PythonProject\.venv_learn\Lib\site-packages\openai\_client.py", line 123, in __init__
    super().__init__(
    ~~~~~~~~~~~~~~~~^
        version=__version__,
        ^^^^^^^^^^^^^^^^^^^^
    ...<6 lines>...
        _strict_response_validation=_strict_response_validation,
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "C:\Users\Administrator\PycharmProjects\PythonProject\.venv_learn\Lib\site-packages\openai\_base_client.py", line 843, in __init__
    self._client = http_client or SyncHttpxClientWrapper(
                                  ~~~~~~~~~~~~~~~~~~~~~~^
        base_url=base_url,
        ^^^^^^^^^^^^^^^^^^
    ...<5 lines>...
        follow_redirects=True,
        ^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "C:\Users\Administrator\PycharmProjects\PythonProject\.venv_learn\Lib\site-packages\openai\_base_client.py", line 741, in __init__
    super().__init__(**kwargs)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^
TypeError: Client.__init__() got an unexpected keyword argument 'proxies'

 The error could be caused by an outdated SDK versiong,trying to update SDK version

pip install --upgrade openai

After updating the SKD ,the code now runs successfully.

 SDK provide a more convenient interface;under the hood,they rely on the request libary for making HTTP request

2.3 Call the embedding(嵌入 向量数据库) API in Python

embedding transforms prompt words into vector representations(向量表示)

2.3.1 request(HTTP)

One advantage of using the request library is that it provides access to the full response,including headers,status code and body.

import requests
import json
import osurl = os.getenv('OPENAI_BASE_URL') + "/embeddings"payload = json.dumps({"model": "text-embedding-ada-002","input": "cat"
})
headers = {'Content-Type': 'application/json','Authorization': 'Bearer ' + os.getenv('OPENAI_API_KEY'),
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)

2.3.2 SDK

Meanwhile,SDK typically provide only pre-processed or pre-packaged object,which may limit access to the raw response date(原始数据). Tip:press Ctrl+B jump to the method

from openai import OpenAI# 初始化 OpenAI 服务。
client = OpenAI()# 调用嵌入 API
def get_embedding(text, model="text-embedding-ada-002"):response = client.embeddings.create(input=text,model=model)return response.data[0].embedding# 示例文本
text = "Hello, world!"# 获取嵌入向量
embedding = get_embedding(text)print("Embedding vector:", embedding)

2.4 Call the vision-endabled GPT4o using a local/online image

2.4.1 request local image

use # to comment code

import os
import base64 #use base64 transform image
import requestsdef encode_image(image_path):with open(image_path, "rb") as image_file:return base64.b64encode(image_file.read()).decode('utf-8')# Path to your image
image_path = "../images/cat.jpeg"# Getting the base64 string
base64_image = encode_image(image_path)headers = {"Content-Type": "application/json","Authorization": f"Bearer " + os.getenv('OPENAI_API_KEY')
}payload = {"model": "gpt-4o","messages": [{"role": "user","content": [{"type": "text","text": "这张照片里有什么?"},{"type": "image_url","image_url": {"url": f"data:image/jpeg;base64,{base64_image}"#input base64 format to url}}]}],"max_tokens": 300
}response = requests.post(os.getenv('OPENAI_BASE_URL') + "/chat/completions", headers=headers, json=payload)print(response.json())

2.4.2 SDK online

from openai import OpenAIclient = OpenAI()
response = client.chat.completions.create(model="gpt-4o",messages=[{"role": "user","content": [{"type": "text", "text": "这张照片里有什么?"},{"type": "image_url","image_url": {"url": "https://p7.itc.cn/q_70/images03/20220805/7a369d8407144b11bfd598091095c959.jpeg",#"url": f"data:image/jpeg;base64,{base64_image}"},},],}],max_tokens=50,
)
print(response.choices[0])

2.5 Respond whit the specified Json schema

JSON is well-suited for converting data into objects

from openai import OpenAIclient = OpenAI()response = client.chat.completions.create(model="gpt-4o",response_format={"type": "json_object"},#ensure respond is JSON schcemamessages=[{"role": "system", "content": "你是一个助手,请用中文输出JSON"},{"role": "user", "content": "帮我写一个冒泡算法?"}]
)
print(response.choices[0].message.content)

before not using JSON schema(more suitable for page display or user reading

 after using JSON schema

2.6 Seed for reproducible output(重现输出)

As the seed value adcreases,the differences become more pronounced(obvious明显)

from openai import OpenAI
client = OpenAI()for i in range(3):response = client.chat.completions.create(model="gpt-4o",# 对于三个请求中的每一个,使用相同的 seed 参数 42,同时将所有其他参数保持相同,我们便能够生成更一致的结果。seed=2, #种子temperature=0.7,max_tokens=50,messages=[{"role": "system", "content": "你是一个生成故事机器人"},{"role": "user", "content": "告诉我一个关于宇宙是如何开始的故事?"}])print(f'故事版本{i + 1}:' + response.choices[0].message.content)del response #this statement is not necessary and can be omitted

seed = 2

 seed = 40

2.7 Count tokens

Count tokens in the development console for looped chat.

Need to install the tiktoken libary

pip install --upgrade tiktoken
from openai import OpenAI
# pip install --upgrade tiktoken
#tiktoken 用来统计token使用
import tiktoken#package for count tokenclient = OpenAI()
# 初始化 tiktoken 编码器
encoder = tiktoken.encoding_for_model("gpt-4")def count_tokens(text):encoder.encode(text)# 将输入的文本text转换为对应的token列表。具体来说,它使用tiktoken库中的编码器将文本进行编码,以便后续处理。tokens = encoder.encode(text)# 统计文本中的 token 数量return len(tokens)def main():# 初始化聊天记录messages = [{"role": "system", "content": "You are a helpful assistant."}]print("开始聊天吧!输入 'exit' 退出。")total_tokens = 0while True:# 获取用户输入user_input = input("用户: ")if user_input.lower() == 'exit':break# 添加用户消息到聊天记录messages.append({"role": "user", "content": user_input})# 统计用户输入的 token 数量并累加user_tokens = count_tokens(user_input)total_tokens += user_tokens# 调用 GPT-4 模型response = client.chat.completions.create(model="gpt-4",messages=messages,max_tokens=150,temperature=0.7,top_p=1,n=1)# 获取助手的回复assistant_message = response.choices[0].message.content.strip()# 添加助手的回复到聊天记录messages.append({"role": "assistant", "content": assistant_message})# 统计助手回复的 token 数量并累加assistant_tokens = count_tokens(assistant_message)total_tokens += assistant_tokens# 输出用户输入和助手的回复print(f"助手: {assistant_message}")# 输出当前聊天记录的总 token 数量print(f"用户tokens数: {user_tokens},助手tokens数: {assistant_tokens},总token数: {total_tokens}")if __name__ == "__main__":#Only when the module is run as the main program directlymain()

2.8 Consol chat loop with session length management based on maximum token limit

from openai import OpenAI
# pip install tiktoken
import tiktokenclient = OpenAI()# 这是 API 请求和响应的总 token 数量限制。对于 GPT-4 模型,这个值通常是 4096。
MAX_TOKENS = 8  # 设置最大 token 数量
# 这是我们预留给模型响应的 token 数量。我们需要在计算对话的最大 token 数量时减去这个值,以确保有足够的空间来容纳模型的响应。
MAX_RESPONSE_TOKENS = 6  # 设置响应中预留的最大 token 数量
encoder = tiktoken.encoding_for_model("gpt-4")
def count_tokens(text):encoder.encode(text)# 将输入的文本text转换为对应的token列表。具体来说,它使用tiktoken库中的编码器将文本进行编码,以便后续处理。tokens = encoder.encode(text)# 统计文本中的 token 数量return len(tokens)
# 假设 MAX_TOKENS 是 4096,而 MAX_RESPONSE_TOKENS 是 500,那么:
# 我们希望对话历史的 token 数量不要超过 3596 (4096 - 500)。
# 这样,当我们发送对话历史给 API 时,仍然有 500 个 token 的空间用于模型生成的响应。
def manage_token_limit(messages):current_tokens = count_tokens(messages)if current_tokens > (MAX_TOKENS - MAX_RESPONSE_TOKENS):print(f"当前会话 token 数量: {current_tokens}, 超过最大 token 数量: {MAX_TOKENS - MAX_RESPONSE_TOKENS}")return Falsereturn Truedef get_gpt_response(messages):"""获取 GPT-4 的响应"""response = client.chat.completions.create(model="gpt-4",messages=messages)return response.choices[0].message.content.strip()def main():print("Chat with GPT-4. Type 'exit' to end the conversation.")while True:messages = []#this statement must be inside the while loop to ensure that the variable is reset on each iteration(每次迭代)user_input = input("用户: ")if user_input.lower() == 'exit':breakmessages.append({"role": "user", "content": user_input})# 管理用户输入以确保总 token 数量不超过限制if not manage_token_limit(user_input):continueresponse = get_gpt_response(messages)print(f"GPT: {response}")#The role of 'f' is to format string for input variablesmessages.append({"role": "assistant", "content": response})if __name__ == "__main__":main()

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/64939.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【Python其他生成随机字符串的方法】

在Python中&#xff0c;除了之前提到的方法外&#xff0c;确实还存在其他几种生成随机字符串的途径。以下是对这些方法的详细归纳&#xff1a; 方法一&#xff1a;使用random.randint结合ASCII码生成 你可以利用random.randint函数生成指定范围内的随机整数&#xff0c;这些整…

leetcode hot 100 跳跃游戏

55. 跳跃游戏 已解答 中等 相关标签 相关企业 给你一个非负整数数组 nums &#xff0c;你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。 判断你是否能够到达最后一个下标&#xff0c;如果可以&#xff0c;返回 true &#xff1b;否则…

《Vue3实战教程》40:Vue3安全

如果您有疑问&#xff0c;请观看视频教程《Vue3实战教程》 安全​ 报告漏洞​ 当一个漏洞被上报时&#xff0c;它会立刻成为我们最关心的问题&#xff0c;会有全职的贡献者暂时搁置其他所有任务来解决这个问题。如需报告漏洞&#xff0c;请发送电子邮件至 securityvuejs.org。…

01.02周二F34-Day44打卡

文章目录 1. 这家医院的大夫和护士对病人都很耐心。2. 她正跟一位戴金边眼镜的男士说话。3. 那个人是个圆脸。4. 那个就是传说中的鬼屋。5. 他是个很好共事的人。6. 我需要一杯提神的咖啡。7. 把那个卷尺递给我一下。 ( “卷尺” 很复杂吗?)8. 他收到了她将乘飞机来的消息。9.…

Spring Boot项目中使用单一动态SQL方法可能带来的问题

1. 查询计划缓存的影响 深入分析 数据库系统通常会对常量SQL语句进行编译并缓存其执行计划以提高性能。对于动态生成的SQL语句&#xff0c;由于每次构建的SQL字符串可能不同&#xff0c;这会导致查询计划无法被有效利用&#xff0c;从而需要重新解析、优化和编译&#xff0c;…

【Rust自学】10.2. 泛型

喜欢的话别忘了点赞、收藏加关注哦&#xff0c;对接下来的教程有兴趣的可以关注专栏。谢谢喵&#xff01;(&#xff65;ω&#xff65;) 题外话&#xff1a;泛型的概念非常非常非常重要&#xff01;&#xff01;&#xff01;整个第10章全都是Rust的重难点&#xff01;&#xf…

Spark-Streaming有状态计算

一、上下文 《Spark-Streaming初识》中的NetworkWordCount示例只能统计每个微批下的单词的数量&#xff0c;那么如何才能统计从开始加载数据到当下的所有数量呢&#xff1f;下面我们就来通过官方例子学习下Spark-Streaming有状态计算。 二、官方例子 所属包&#xff1a;org.…

Python 3 输入与输出指南

文章目录 1. 输入与 input()示例&#xff1a;提示&#xff1a; 2. 输出与 print()基本用法&#xff1a;格式化输出&#xff1a;使用 f-string&#xff08;推荐&#xff09;&#xff1a;使用 str.format()&#xff1a;使用占位符&#xff1a; print() 的关键参数&#xff1a; 3.…

【SQLi_Labs】Basic Challenges

什么是人生&#xff1f;人生就是永不休止的奋斗&#xff01; Less-1 尝试添加’注入&#xff0c;发现报错 这里我们就可以直接发现报错的地方&#xff0c;直接将后面注释&#xff0c;然后使用 1’ order by 3%23 //得到列数为3 //这里用-1是为了查询一个不存在的id,好让第一…

Swift Combine 学习(四):操作符 Operator

Swift Combine 学习&#xff08;一&#xff09;&#xff1a;Combine 初印象Swift Combine 学习&#xff08;二&#xff09;&#xff1a;发布者 PublisherSwift Combine 学习&#xff08;三&#xff09;&#xff1a;Subscription和 SubscriberSwift Combine 学习&#xff08;四&…

时间序列预测算法---LSTM

目录 一、前言1.1、深度学习时间序列一般是几维数据&#xff1f;每个维度的名字是什么&#xff1f;通常代表什么含义&#xff1f;1.2、为什么机器学习/深度学习算法无法处理时间序列数据?1.3、RNN(循环神经网络)处理时间序列数据的思路&#xff1f;1.4、RNN存在哪些问题? 二、…

leetcode题目(3)

目录 1.加一 2.二进制求和 3.x的平方根 4.爬楼梯 5.颜色分类 6.二叉树的中序遍历 1.加一 https://leetcode.cn/problems/plus-one/ class Solution { public:vector<int> plusOne(vector<int>& digits) {int n digits.size();for(int i n -1;i>0;-…

快速上手LangChain(三)构建检索增强生成(RAG)应用

文章目录 快速上手LangChain(三)构建检索增强生成(RAG)应用概述索引阿里嵌入模型 Embedding检索和生成RAG应用(demo:根据我的博客主页,分析一下我的技术栈)快速上手LangChain(三)构建检索增强生成(RAG)应用 langchain官方文档:https://python.langchain.ac.cn/do…

[cg] android studio 无法调试cpp问题

折腾了好久&#xff0c;native cpp库无法调试问题&#xff0c;原因 下面的Deploy 需要选Apk from app bundle!! 另外就是指定Debug type为Dual&#xff0c;并在Symbol Directories 指定native cpp的so路径 UE项目调试&#xff1a; 使用Android Studio调试虚幻引擎Android项目…

【Windows】powershell 设置执行策略(Execution Policy)禁止了脚本的运行

报错信息&#xff1a; 无法加载文件 C:\Users\11726\Documents\WindowsPowerShell\profile.ps1&#xff0c;因为在此系统上禁止运行脚本。有关详细信息&#xff0c;请参 阅 https:/go.microsoft.com/fwlink/?LinkID135170 中的 about_Execution_Policies。 所在位置 行:1 字符…

可编辑37页PPT |“数据湖”构建汽车集团数据中台

荐言分享&#xff1a;随着汽车行业智能化、网联化的快速发展&#xff0c;数据已成为车企经营决策、优化生产、整合供应链的核心资源。为了在激烈的市场竞争中占据先机&#xff0c;汽车集团亟需构建一个高效、可扩展的数据管理平台&#xff0c;以实现对海量数据的收集、存储、处…

【快速实践】类激活图(CAM,class activation map)可视化

类激活图可视化&#xff1a;有助于了解一张图像的哪一部分让卷积神经网络做出了最终的分类决策 对输入图像生成类激活热力图类激活热力图是与特定输出类别相关的二维分数网格&#xff1a;对任何输入图像的每个位置都要进行计算&#xff0c;它表示每个位置对该类别的重要程度 我…

ros2 py文件间函数调用

文章目录 写在前面的话生成python工程包命令运行python函数命令python工程包的目录结构目录结构&#xff08;细节&#xff09; 报错 1&#xff08; no module name ***&#xff09;错误示意 截图终端输出解决方法 报错 2&#xff08; AttributeError: *** object has no attrib…

Milvus×合邦电力:向量数据库如何提升15%电价预测精度

01. 全球能源市场化改革下的合邦电力 在全球能源转型和市场化改革的大背景下&#xff0c;电力交易市场正逐渐成为优化资源配置、提升系统效率的关键平台。电力交易通过市场化手段&#xff0c;促进了电力资源的有效分配&#xff0c;为电力行业的可持续发展提供了动力。 合邦电力…

OLED的显示

一、I2C I2C时序&#xff1a;时钟线SCL高电平下&#xff1a;SDA由高变低代表启动信号&#xff0c;开始发送数据&#xff1b;SCL高电平时&#xff0c;数据稳定&#xff0c;数据可以被读走&#xff0c;开始进行读操作&#xff0c;SCL低电平时&#xff0c;数据发生改变&#xff1…