【本件解決済】
ChatGPTのAPIに詳しい人はいませんか?
コードかけない人間なのでGPTの暴力で組んでいるのですが
"gpt-4o-mini"が使えるコードができません。
ウェブサイトのURLを読み込ませて、そこから答えさせあるのは難しいのですが
現在の最新のopenaiを使って、gpt-4o-miniを使うにはどう修正すればよろしいでしょうか?
今のコードはここです
====以下コード====
import openai
import csv
import time
import os
# 1. OpenAI APIキーの設定
openai.api_key = 'APIHERE'
# 2. Link.txt のパスを指定
link_file_path = 'Link.txt'
# Question1,Question2等各行に質問がかいてある
# 3. Link.txt が存在するか確認
if not os.path.exists(link_file_path):
raise FileNotFoundError(f"'{link_file_path}' が見つかりません。ファイルのパスを確認してください。")
# 4. Link.txt からリンクを読み込む
with open(link_file_path, 'r', encoding='utf-8') as file:
links = [line.strip() for line in file if line.strip()]
# 5. レスポンスを保存するリスト
responses = []
# 6. 各リンクに対してAPIリクエストを送信
for index, link in enumerate(links, start=1):
print(f"Processing {index}/{len(links)}: {link}")
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": f"Please provide me Answer of the question\n{link}"}
]
try:
# ChatCompletionを使用してリクエストを送信
response = openai.ChatCompletion.create(
model="gpt-4", # または "gpt-3.5-turbo" を使用可能
messages=messages,
max_tokens=500,
temperature=0.7,
)
# レスポンスを取得
text_response = response.choices[0].message['content'].strip()
# コンソールにレスポンスを出力
print(f"Response for {link}:\n{text_response}\n")
# リストに追加
responses.append((link, text_response))
except Exception as e:
print(f"Error processing link {link}: {e}")
responses.append((link, f"Error: {e}"))
# レート制限を考慮して1秒待機
time.sleep(1)
# 7. 結果をCSVファイルに書き込む
output_csv_path = 'output.csv'
with open(output_csv_path, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Link', 'gptResponse'])
writer.writerows(responses)
print(f"処理が完了しました。結果は '{output_csv_path}' に保存されています。")