题意:使用 openai-api 时出现 TypeError(类型错误)
问题背景:
Using the code below and openai version 0.28.0 i get an error which i can't resolve:
使用以下代码和 openai 版本 0.28.0 时,我遇到了一个无法解决的错误:
File "", line 11, in TypeError: string indices must be integers, not 'str'
文件“”,第 11 行,出现 TypeError:字符串索引必须是整数,而不是 'str'
Which indice is it complaining about. Seems I'm a little blind today...
它在抱怨哪个索引呢?看来我今天有点盲目…
import requests
from bs4 import BeautifulSoup
from docx import Document
import openai
# Set your OpenAI API key
openai.api_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
# URL of the website you want to scrape
website_url = "https://somesite.com"
# Send a GET request to the website
response = requests.get(website_url)
# Parse the HTML content of the website using BeautifulSoup
soup = BeautifulSoup(response.content, "html.parser")
# Extract text blocks larger than 100 characters
text_blocks = []
for paragraph in soup.find_all("p"):
text = paragraph.get_text().strip()
if len(text) >= 100:
text_blocks.append(text)
# Translate text blocks from English to German using OpenAI's Chat API
translated_text_blocks = []
for text_block in text_blocks:
chat_input = f"Translate the following English text to German: '{text_block}'"
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo", # Use the language model
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": chat_input},
],
)
# Extract translated text from the API response
translated_text = response.choices[0].message["content"]["body"]
translated_text_blocks.append(translated_text)
# Create a new Word document
document = Document()
# Add translated text blocks to the Word document
for translated_text in translated_text_blocks:
document.add_paragraph(translated_text)
# Save the Word document
document.save("translated_content.docx")
The full console output is: 完整的控制台输出信息如下
>>> # Send a GET request to the website
>>>
>>> response = requests.get(website_url)
>>> # Parse the HTML content of the website using BeautifulSoup
>>>
>>> soup = BeautifulSoup(response.content, "html.parser")
>>> # Extract text blocks larger than 100 characters
>>>
>>> text_blocks = []
>>> for paragraph in soup.find_all("p"):
... text = paragraph.get_text().strip()
... if len(text) >= 100:
... text_blocks.append(text)
... # Translate text blocks from English to German using OpenAI's Chat API
...
>>> translated_text_blocks = []
>>> for text_block in text_blocks:
... chat_input = f"Translate the following English text to German: '{text_block}'"
... response = openai.ChatCompletion.create(
... model="gpt-3.5-turbo", # Use the language model
... messages=[
... {"role": "system", "content": "You are a helpful assistant."},
... {"role": "user", "content": chat_input},
... ],
... )
... # Extract translated text from the API response
... translated_text = response.choices[0].message["content"]["body"]
... translated_text_blocks.append(translated_text)
... # Create a new Word document
...
Traceback (most recent call last):
File "<stdin>", line 11, in <module>
TypeError: string indices must be integers, not 'str'
>>> document = Document()
>>> # Add translated text blocks to the Word document
>>>
>>> for translated_text in translated_text_blocks:
... document.add_paragraph(translated_text)
... # Save the Word document
...
>>> document.save("translated_content.docx")
>>> print("Translated text blocks have been saved to 'translated_content.docx'.")
Translated text blocks have been saved to 'translated_content.docx'.
问题解决:
Your problem is caused by this line of code:
你的问题是由这行代码引起的:
translated_text = response.choices[0].message["content"]["body"]
response.choices[0].message["content"]
is already your response from openai api in str type and so you are getting this error because you are trying to get item from str by key what is wrong.
response.choices[0].message['content']
已经是来自 OpenAI API 的字符串类型响应,因此你遇到这个错误是因为你试图通过键从字符串中获取项目,这是不正确的。
So just replace this line on this line:
所以只需将这一行替换为这一行:
translated_text = response.choices[0].message["content"]