import asyncio
from pathlib import Path
import sys
from google import genai
from google.genai import types
from utils import Utils
key_path = Path("./api-key.txt")
if not key_path.exists():
key_path.touch()
with open(key_path, "r") as f:
key = f.readline().strip()
if not key:
print(f"Paste your API key into {key_path.resolve()}")
sys.exit(1)
client = genai.Client(
api_key=key,
http_options={'api_version': 'v1beta'}
)
MODEL = "gemini-2.5-flash-native-audio-preview-12-2025"
get_weather_tool = {
"name": "getWeather",
"description": "gets the weather (temperature in Celsius) for a requested city",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string"}
},
"required": ["city"]
}
}
HANDLE_STORE = Path("./last_session_handle.txt")
tools_config = [types.Tool(function_declarations=[get_weather_tool])]
def load_saved_handle():
if HANDLE_STORE.exists():
return HANDLE_STORE.read_text().strip()
return None
def save_handle(token):
HANDLE_STORE.write_text(token)
saved_token = load_saved_handle()
CONFIG = types.LiveConnectConfig(
response_modalities=["AUDIO"],
output_audio_transcription={},
tools=tools_config,
session_resumption=types.SessionResumptionConfig(
handle=saved_token
),
)
def get_weather(city=""):
temp = 30
if city == "Kyiv":
temp = 25
elif city == "Paris":
temp = 34
return temp
async def run():
try:
async with client.aio.live.connect(model=MODEL, config=CONFIG) as session:
print("Connected!")
while True:
text = await asyncio.to_thread(input, "\nYou: ")
if text.lower() == "q":
break
await session.send_client_content(
turns=[types.Content(
role="user",
parts=[types.Part(text=text)]
)],
turn_complete=True
)
print("Gemini: ", end="")
async for response in session.receive():
if response.tool_call:
print("The tool was called")
function_responses = []
for fc in response.tool_call.function_calls:
print(f"F to call: {fc.name} {fc.args}")
if fc.name == "getWeather":
result = get_weather(fc.args["city"])
function_response = types.FunctionResponse(
id=fc.id,
name=fc.name,
response={"result": result}
)
function_responses.append(function_response)
await session.send_tool_response(function_responses=function_responses)
if response.go_away is not None:
# The connection will soon be terminated
print("The session will soon be terminated: ",
response.go_away.time_left)
if response.server_content:
if response.server_content.output_transcription:
print(
Utils.yellow(response.server_content.output_transcription.text), end="", flush=True)
if response.server_content.model_turn:
for part in response.server_content.model_turn.parts:
if part.text:
print(Utils.red(part.text),
end="", flush=True)
if response.session_resumption_update and response.session_resumption_update.resumable and response.session_resumption_update.new_handle:
save_handle(
response.session_resumption_update.new_handle)
print(
f"handle: {response.session_resumption_update.new_handle}")
print()
except Exception as e:
print("\nConnection failed/closed:", repr(e))
if __name__ == "__main__":
asyncio.run(run())
и сейчас у меня возникла проблема: не сохраняется мое последнее приглашение. Сначала я прошу его запомнить цифры 3, 4 и 5, затем задаю два вопроса, чтобы заполнить контекст, затем прошу его также запомнить 6, 7, 8 и завершаю сеанс, выйдя. После этого я запускаю скрипт снова, он загружает мой предыдущий сеанс, я спрашиваю ИИ о полной последовательности чисел, и он говорит мне только 3, 4 и 5. Вы можете сами посмотреть мою беседу:
[home@Latitude gemini]$ /usr/bin/env /home/home/.local/python/bin/python3 /home/home/.vscode/extensions/ms-python.debugpy-2025.18.0-linux-x64/bundled/libs/debugpy/adapter/../../debugpy/launcher 59125 -- /home/home/Projects/gemini/live.py
Connected!
You: Remember numbers 3, 4, 5
Gemini: **Storing Numerical Sequence**
I've successfully logged the sequence 3, 4, and 5 into my working memory. I'm now ready to utilize this numerical series if a relevant task is presented. The numbers are solidified and ready for recall.
Got it, I'll remember those.
You: How does AI work?
Gemini: handle: CigxNGtleGtpNXpxNTZ4NTg3aG9mNmNnZWptN2dyb3Yxb29nZ21iM3Q2
**Clarifying AI Fundamentals**
I'm currently structuring an overview of core AI concepts for the user's question. My plan involves simplifying complex ideas like machine learning, neural networks, and the training-deployment lifecycle. My goal is to break these down into digestible components for a quick, understandable answer.
AI works by using algorithms and statistical models to enable computers to learn and make decisions. Machine learning, a key component, involves training models on vast amounts of data, allowing them to identify patterns and perform tasks without being explicitly programmed. This includes deep learning, which uses neural networks to process information in complex ways.
You: What is RAM?
Gemini: handle: CihzdXFibzZ0OWt6b255NXhoc2Qxb2FleTR1eGFodmpkYnFiajBqYzAz
**Defining RAM's Purpose**
I'm now focusing on clarifying the definition of RAM. I'll explain what its acronym stands for and its core function in a computer. The aim is to make the explanation easy to understand. I'm prioritizing clarity. It's crucial for the user. I'll also stress its significance for optimal performance.
RAM stands for Random Access Memory. It's a form of computer memory that allows data to be accessed quickly and easily by the computer's processor. It's crucial for running programs and temporarily holding data that the computer is currently using, which helps with overall performance.
You: Also remember numbers 6, 7, 8
Gemini: handle: CihtandqOHR3MWc3ajlxMjMzMnF0b3QzNW9xbzdieGtxZTg1ZDhjY2Zr
**Adding New Numbers**
I've just been given three new numbers to remember: 6, 7, and 8. I've successfully integrated these with the existing set, 3, 4, and 5. I am now certain that I have stored this information appropriately.
Remembered. So now I have 3, 4, 5, 6, 7, and 8 memorized.
You: q
[home@Latitude gemini]$ cd /home/home/Projects/gemini ; /usr/bin/env /home/home/.local/python/bin/python3 /home/home/.vscode/extensions/ms-python.debugpy-2025.18.0-linux-x64/bundled/libs/debugpy/adapter/../../debugpy/launcher 49611 -- /home/home/Projects/gemini/live.py
Connected!
You: Tell me the full numbers sequence
Gemini: **Identifying the Sequence**
I've determined the user is referring to the sequence "3, 4, 5." This conclusion stems from their previous message and the current request. I'm presenting this recalled sequence as a response to their prompt for a numerical sequence.
The numbers you asked me to remember are 3, 4, 5.
You: q
Я каким-то образом пропустил последнее обновление токена? Или это просто так задумано?
Я работаю над возобновлением сеанса в [b]Gemini Live API[/b] для Python. Это мой код: [code]import asyncio from pathlib import Path import sys from google import genai from google.genai import types from utils import Utils
key_path = Path("./api-key.txt") if not key_path.exists(): key_path.touch()
with open(key_path, "r") as f: key = f.readline().strip() if not key: print(f"Paste your API key into {key_path.resolve()}") sys.exit(1)
print("Gemini: ", end="") async for response in session.receive(): if response.tool_call: print("The tool was called") function_responses = [] for fc in response.tool_call.function_calls: print(f"F to call: {fc.name} {fc.args}") if fc.name == "getWeather":
if response.go_away is not None: # The connection will soon be terminated print("The session will soon be terminated: ", response.go_away.time_left)
if response.server_content: if response.server_content.output_transcription: print( Utils.yellow(response.server_content.output_transcription.text), end="", flush=True)
if response.server_content.model_turn: for part in response.server_content.model_turn.parts: if part.text: print(Utils.red(part.text), end="", flush=True)
if response.session_resumption_update and response.session_resumption_update.resumable and response.session_resumption_update.new_handle: save_handle( response.session_resumption_update.new_handle) print( f"handle: {response.session_resumption_update.new_handle}")
print()
except Exception as e: print("\nConnection failed/closed:", repr(e))
if __name__ == "__main__": asyncio.run(run())
[/code] и сейчас у меня возникла проблема: не сохраняется мое последнее приглашение. Сначала я прошу его запомнить цифры [b]3, 4 и 5[/b], затем задаю два вопроса, чтобы заполнить контекст, затем прошу его также запомнить [b]6, 7, 8[/b] и завершаю сеанс, выйдя. После этого я запускаю скрипт снова, он загружает мой предыдущий сеанс, я спрашиваю ИИ о полной последовательности чисел, и он говорит мне только [b]3, 4 и 5[/b]. Вы можете сами посмотреть мою беседу: [code][home@Latitude gemini]$ /usr/bin/env /home/home/.local/python/bin/python3 /home/home/.vscode/extensions/ms-python.debugpy-2025.18.0-linux-x64/bundled/libs/debugpy/adapter/../../debugpy/launcher 59125 -- /home/home/Projects/gemini/live.py Connected!
I've successfully logged the sequence 3, 4, and 5 into my working memory. I'm now ready to utilize this numerical series if a relevant task is presented. The numbers are solidified and ready for recall.
Got it, I'll remember those.
You: How does AI work? Gemini: handle: CigxNGtleGtpNXpxNTZ4NTg3aG9mNmNnZWptN2dyb3Yxb29nZ21iM3Q2 **Clarifying AI Fundamentals**
I'm currently structuring an overview of core AI concepts for the user's question. My plan involves simplifying complex ideas like machine learning, neural networks, and the training-deployment lifecycle. My goal is to break these down into digestible components for a quick, understandable answer.
AI works by using algorithms and statistical models to enable computers to learn and make decisions. Machine learning, a key component, involves training models on vast amounts of data, allowing them to identify patterns and perform tasks without being explicitly programmed. This includes deep learning, which uses neural networks to process information in complex ways.
You: What is RAM? Gemini: handle: CihzdXFibzZ0OWt6b255NXhoc2Qxb2FleTR1eGFodmpkYnFiajBqYzAz **Defining RAM's Purpose**
I'm now focusing on clarifying the definition of RAM. I'll explain what its acronym stands for and its core function in a computer. The aim is to make the explanation easy to understand. I'm prioritizing clarity. It's crucial for the user. I'll also stress its significance for optimal performance.
RAM stands for Random Access Memory. It's a form of computer memory that allows data to be accessed quickly and easily by the computer's processor. It's crucial for running programs and temporarily holding data that the computer is currently using, which helps with overall performance.
You: Also remember numbers 6, 7, 8 Gemini: handle: CihtandqOHR3MWc3ajlxMjMzMnF0b3QzNW9xbzdieGtxZTg1ZDhjY2Zr **Adding New Numbers**
I've just been given three new numbers to remember: 6, 7, and 8. I've successfully integrated these with the existing set, 3, 4, and 5. I am now certain that I have stored this information appropriately.
Remembered. So now I have 3, 4, 5, 6, 7, and 8 memorized.
You: Tell me the full numbers sequence Gemini: **Identifying the Sequence**
I've determined the user is referring to the sequence "3, 4, 5." This conclusion stems from their previous message and the current request. I'm presenting this recalled sequence as a response to their prompt for a numerical sequence.
The numbers you asked me to remember are 3, 4, 5.
You: q [/code] Я каким-то образом пропустил последнее обновление токена? Или это просто так задумано?