Added code samples for AI-Agents
This commit is contained in:
95
scripts/export_conversations.py
Normal file
95
scripts/export_conversations.py
Normal file
@@ -0,0 +1,95 @@
|
||||
"""Скрипт для экспорта диалогов."""
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from services.cache_service import CacheService
|
||||
|
||||
|
||||
async def export_conversations(
|
||||
redis_url: str,
|
||||
output_file: str,
|
||||
conversation_ids: list[str] = None,
|
||||
):
|
||||
"""Экспортировать диалоги из Redis."""
|
||||
cache = CacheService(redis_url=redis_url)
|
||||
|
||||
try:
|
||||
if conversation_ids:
|
||||
# Экспортируем конкретные диалоги
|
||||
conversations = {}
|
||||
for conv_id in conversation_ids:
|
||||
messages = await cache.get_context(conv_id, max_messages=1000)
|
||||
if messages:
|
||||
conversations[conv_id] = {
|
||||
"id": conv_id,
|
||||
"messages": messages,
|
||||
"exported_at": datetime.now().isoformat(),
|
||||
}
|
||||
else:
|
||||
# Экспортируем все диалоги (требует доступа к Redis keys)
|
||||
print("Экспорт всех диалогов требует прямого доступа к Redis.")
|
||||
print("Используйте --ids для экспорта конкретных диалогов.")
|
||||
return
|
||||
|
||||
if not conversations:
|
||||
print("Нет диалогов для экспорта")
|
||||
return
|
||||
|
||||
# Сохраняем в файл
|
||||
output_path = Path(output_file)
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
with open(output_file, "w", encoding="utf-8") as f:
|
||||
json.dump(
|
||||
{
|
||||
"exported_at": datetime.now().isoformat(),
|
||||
"conversations": conversations,
|
||||
},
|
||||
f,
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
|
||||
print(f"Экспортировано {len(conversations)} диалогов в {output_file}")
|
||||
|
||||
finally:
|
||||
await cache.close()
|
||||
|
||||
|
||||
async def main():
|
||||
"""Главная функция."""
|
||||
parser = argparse.ArgumentParser(description="Экспорт диалогов из Redis")
|
||||
parser.add_argument(
|
||||
"--redis-url",
|
||||
type=str,
|
||||
default="redis://localhost:6379/0",
|
||||
help="URL Redis",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output",
|
||||
type=str,
|
||||
default="conversations_export.json",
|
||||
help="Файл для экспорта",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--ids",
|
||||
type=str,
|
||||
nargs="+",
|
||||
help="ID диалогов для экспорта",
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
await export_conversations(
|
||||
redis_url=args.redis_url,
|
||||
output_file=args.output,
|
||||
conversation_ids=args.ids,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
|
||||
Reference in New Issue
Block a user