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.pswp.cn/web/64939.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/64939.shtml
英文地址,請注明出處:http://en.pswp.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…