TypeError when using openai-api

题意:使用 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"]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

营赢盈英

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值