You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Google Generative AI与Streamlit时IncompleteIterationError报错原因咨询

错误原因分析
  • 流式响应未完成迭代:调用generate_content时设置了stream=True,返回的是流式响应对象,必须完成内容迭代后才能获取完整文本。直接调用response.text前未处理完流数据,触发API抛出IncompleteIterationError。
  • 无效等待逻辑:使用time.sleep(20)仅固定等待时长,并未触发流式响应的内容接收与拼接,无法确保响应完成。
修复方案

方案1:关闭流式传输

若不需要实时展示生成过程,直接关闭流式模式即可:

def generate_story_from_image(self) -> list[str]:
    '''Generate story using input image, last stories (if exist), input other text'''
    self.prompt()
    model = self.configuration()
    text_prompt = str(st.session_state.model_prompt)
    image = st.session_state.uploaded_image
    # 关闭流式传输
    response = model.generate_content([text_prompt, image], stream=False)
    with st.spinner('Wait...'):
        # 无需sleep,generate_content会阻塞直到响应完成
        pass
    st.session_state.story_results.append(response.text)

方案2:正确处理流式响应

若需保留流式传输(如实时展示生成内容),可通过以下两种方式处理:

方式A:调用resolve()等待完整响应

def generate_story_from_image(self) -> list[str]:
    '''Generate story using input image, last stories (if exist), input other text'''
    self.prompt()
    model = self.configuration()
    text_prompt = str(st.session_state.model_prompt)
    image = st.session_state.uploaded_image
    response = model.generate_content([text_prompt, image], stream=True)
    with st.spinner('Wait...'):
        # 阻塞直到流式响应全部接收完成
        response.resolve()
    st.session_state.story_results.append(response.text)

方式B:迭代流式块实现实时展示

def generate_story_from_image(self) -> list[str]:
    '''Generate story using input image, last stories (if exist), input other text'''
    self.prompt()
    model = self.configuration()
    text_prompt = str(st.session_state.model_prompt)
    image = st.session_state.uploaded_image
    response = model.generate_content([text_prompt, image], stream=True)
    
    full_story = ""
    story_placeholder = st.empty()  # 用于实时更新内容
    with st.spinner('Generating story...'):
        for chunk in response:
            full_story += chunk.text
            story_placeholder.markdown(full_story)  # 实时展示生成的内容
    
    st.session_state.story_results.append(full_story)
关键说明
  • stream=True时,response.text仅在响应完全迭代后可用,否则会抛出迭代未完成错误。
  • response.resolve()会阻塞至所有流式内容接收完毕,之后可安全访问response.text。
  • 迭代流式块能实现实时内容展示,无需固定等待时间,提升用户体验。

内容的提问来源于stack exchange,提问作者Kingki19

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 07:20:25