Я учитель Python, и я создаю пример проекта, чтобы продемонстрировать, как использовать ИИ в их проектах, помимо того, что я просто попросил чаттпт создать для них код. < /p>
Итак, я Имейте следующий код (это не самый эффективный код, но это для детей младшего возраста, поэтому эффективность не является целью, как воздействие более продвинутого Python) < /p>
from google import genai
from google.genai import types
import time
# AI Connection
client = genai.Client(api_key="[KEY_HERE]")
# My attempt to deal with a "rate" issue (which turned out to not do anything useful)
print("Please wait...")
for x in range (0, 60):
percent = round(x/60 * 100)
print(str(percent) + "%")
time.sleep(1)
# Function to make calls to AI more "modular"
def askAIStream(personality, question, history):
# Variable to track history within this function call
newHistory = ""
chat = client.chats.create(
model="gemini-2.0-flash",
config = types.GenerateContentConfig(
system_instruction=personality,
),
history=history
)
response = chat.send_message_stream(question)
for chunk in response:
newHistory += chunk.text
print(chunk.text, end="")
# Return the response if we need it for a later prompt
return newHistory
personality = "No special instructions"
history = []
response = askAIStream(personality, "Give me a random 1-word response that can be used as a topic for a joke", history)
history.append(response)
response = askAIStream(personality, "Tell me a joke about " + response, history)
history.append(response)
response = askAIStream(personality, "I don't get it, can you explain this joke to me?", history)
history.append(response)
# Start the history variable over to keep track of what's going on
history.clear()
# Generate the personality of the AI
personality = """You are a classic storyteller who has a way with words.
You are weaving a story that you will get responses to that you will then
use to continue the story. All your responses should include a couple of options that the user can choose and end with 'What do you do?'
to help the story continue. You will find a way to end the story in 5
responses and then end the story with a classic 'The End'."""
# Start the story from the "askAIStream" function and attach the response to the history list
response = askAIStream(personality, "Start a random story", history)
history.append(response)
# Start a loop for the story to continue for 5 more responses
## This is the where my responses eventually break
for i in range(5):
# Prompt the user to say something
user = input("")
# Call the "askAIStream" function and attach the response to the history list
response = askAIStream(personality, user, history)
history.append(response)
< /code>
Проблема заключается в том, что текст останавливается мертвым в своих треках и ждет следующего ввода пользователя (он происходит в разных точках в цикле в конце этого кода, но Это всегда кажется циклом, где он в конечном итоге происходит):
ai -ответ показывает неполное предложение и ожидание следующего ответа пользователя из команды input () < /p>
Когда я использовать "Send_message ()" вместо "send_message_stream ()" Я, кажется, не сталкиваюсь с одними и теми же проблемами. Но мне нравится _stream, потому что это больше похоже на поля чата, к которым привыкли мои ученики, когда они обрывают в чате. Было связано с ограничениями ставки (у меня есть Google One, но мы не платим за Близнецы напрямую), поэтому я реализовал 60-секундное ожидание. Это было довольно глупо оглядываться назад, так как я бы получил ошибку «превышенной», если бы это было так. (И, конечно, "send_message ()" будет также испытывать некоторые проблемы, но это не так) < /p>
Я знаю, что у моего кода есть некоторые проблемы с эффективностью (что я намерен Укажите это, прежде чем показать это студентам), но никто из них не чувствует себя причиной, по которой мои ответы оказывают влияние, которое это такое. В?
Спасибо всем заранее!
Подробнее здесь: https://stackoverflow.com/questions/794 ... f-a-respon
Python Google Genai "send_message_stream" не возвращает полные куски ответа после нескольких сообщений чата ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение