面向DeepSeek chat coding實錄(二)

向DeepSeek的提問

幫我設計以下兩個python class
Span
屬性:
hash值(在init函數中通過時間初始化)
創建時間:時間(在init函數中通過時間初始化)
結束時間:時間(可選,默認為空)
子Span:數組對象類型為Span
parent:父Span
狀態:打開,關閉
內容:str對象,若對象為非str類型string化。

函數
結束:如果當前Span的所有子Span都結束了,則可以結束(要求這個函數線程安全)
展示:按照當前Span和子Span的創建和時間順序發揮Span

Span_Mgr
函數
查詢最近所有的父Span,按照時間順序返回
創建一個新的Span(輸入內容),返回Span對象

你可以使用ExpiringDictStorage作為數據持久化的實現方式,以下為ExpiringDictStorage的定義

import json
import os
import threading
import timefrom filelock import FileLock
from openai.types.chat import ChatCompletionclass ExpiringDictStorage:def __init__(self, filename="data_store.json", expiry_days=7):self.filename = filenameself.expiry_days = expiry_daysself.lock = threading.Lock()self.file_lock = FileLock(filename + ".lock")self.data = self._load_data()def _load_data(self):"""加載數據并清理過期項"""with self.file_lock:if not os.path.exists(self.filename):return {"_metadata": {"last_clean": time.time()}, "data": {}}try:with open(self.filename, "r") as f:data = json.load(f)# 清理過期數據(每7天執行一次)current_time = time.time()if (current_time - data["_metadata"]["last_clean"]> self.expiry_days * 86400):data["data"] = {k: vfor k, v in data["data"].items()if current_time - v["timestamp"] <= self.expiry_days * 86400}data["_metadata"]["last_clean"] = current_timeself._save_data(data)return dataexcept (json.JSONDecodeError, KeyError):# 文件損壞時創建新文件return {"_metadata": {"last_clean": time.time()}, "data": {}}def _save_data(self, data):"""保存數據到文件"""with open(self.filename, "w") as f:json.dump(data, f, indent=2)def get(self, key, update_timestamp=True):"""獲取值:param key: 要獲取的鍵:param update_timestamp: 是否更新訪問時間戳,默認為True"""with self.lock:if key not in self.data["data"]:return Noneitem = self.data["data"][key]value = item["value"]# 如果配置為更新時間戳,則更新if update_timestamp:item["timestamp"] = time.time()self._save_data(self.data)if item.get("_type") == "ChatCompletion":return ChatCompletion.model_validate_json(value)else:return valuedef set(self, key, value):"""設置值"""with self.lock:if isinstance(value, ChatCompletion):storage_item = {"value": value.model_dump_json(),"timestamp": time.time(),"_type": "ChatCompletion",}else:storage_item = {"value": value,"timestamp": time.time(),"_type": "string",}self.data["data"][key] = storage_itemself._save_data(self.data)def clean_expired(self):"""手動清理過期數據"""with self.lock:current_time = time.time()self.data["data"] = {k: vfor k, v in self.data["data"].items()if current_time - v["timestamp"] <= self.expiry_days * 86400}self.data["_metadata"]["last_clean"] = current_timeself._save_data(self.data)def __contains__(self, key):with self.lock:return key in self.data["data"]def __getitem__(self, key):return self.get(key)def __setitem__(self, key, value):self.set(key, value)# 使用示例
if __name__ == "__main__":# 安裝依賴: pip install filelockstorage = ExpiringDictStorage(expiry_days=7)# 設置值storage["user1"] = {"name": "Alice", "age": 30}storage["user2"] = {"name": "Bob", "age": 25}# 獲取值print("當前存儲內容:")print(storage.data)print("user1的值:", storage["user1"])  # 輸出: {'name': 'Alice', 'age': 30}# 檢查鍵是否存在print("user2是否存在:", "user2" in storage)  # 輸出: True# 模擬7天前的數據print("\n模擬7天前的數據...")old_time = time.time() - 8 * 86400  # 8天前(超過7天有效期)old_data = {"_metadata": {"last_clean": old_time},"data": {"user1": {"value": {"name": "Alice", "age": 30}, "timestamp": old_time},"user2": {"value": {"name": "Bob", "age": 25}, "timestamp": old_time},},}with open(storage.filename, "w") as f:json.dump(old_data, f)# 重新加載會自動清理過期數據print("\n重新加載存儲(應自動清理過期數據)...")storage = ExpiringDictStorage(expiry_days=7)print("清理后的存儲內容:")print(storage.data)  # 現在應該看到空字典,因為所有數據都過期了# 添加新數據驗證功能正常print("\n添加新數據驗證功能正常...")storage["user3"] = "afda"print("添加后的存儲內容:")print(storage.data)

DeepSeek的回答

import time
import threading
import json
from typing import List, Optional, Dict, Any
from datetime import datetimeclass Span:def __init__(self, content: Any, parent: Optional['Span'] = None):"""初始化Span對象Args:content: 內容,如果不是字符串會被轉換為字符串parent: 父Span對象,默認為None表示根Span"""self.hash = hash(time.time_ns())  # 使用納秒時間戳生成hashself.create_time = time.time_ns()  # 創建時間(納秒)self.end_time: Optional[int] = None  # 結束時間self.children: List[Span] = []  # 子Span列表self.parent = parent  # 父Spanself.status = "open"  # 狀態:open或closedself.content = str(content)  # 內容,轉換為字符串# 如果有父Span,將自己添加到父Span的子Span列表中if parent:parent.add_child(self)# 線程安全鎖self._lock = threading.RLock()def add_child(self, child_span: 'Span') -> None:"""添加子Span(線程安全)"""with self._lock:self.children.append(child_span)def end(self) -> bool:"""結束當前Span(線程安全)Returns:bool: 是否成功結束Span"""with self._lock:# 檢查所有子Span是否都已結束for child in self.children:if child.status != "closed":return False# 所有子Span都已結束,可以結束當前Spanself.end_time = time.time_ns()self.status = "closed"return Truedef get_duration(self) -> Optional[int]:"""獲取Span持續時間(納秒),如果未結束則返回None"""if self.end_time is None:return Nonereturn self.end_time - self.create_timedef display(self, level: int = 0) -> str:"""按照層級結構展示Span及其子SpanArgs:level: 當前層級(用于縮進)Returns:str: 格式化后的Span信息"""indent = "  " * levelcreate_time_str = datetime.fromtimestamp(self.create_time / 1e9).strftime('%Y-%m-%d %H:%M:%S.%f')if self.end_time:end_time_str = datetime.fromtimestamp(self.end_time / 1e9).strftime('%Y-%m-%d %H:%M:%S.%f')duration = f", Duration: {(self.end_time - self.create_time) / 1e6:.2f}ms"else:end_time_str = "Not ended"duration = ""result = f"{indent}Span(hash={self.hash}, Status={self.status}\n"result += f"{indent}  Create: {create_time_str}, End: {end_time_str}{duration}\n"result += f"{indent}  Content: {self.content}\n"# 遞歸顯示子Spanfor child in sorted(self.children, key=lambda x: x.create_time):result += child.display(level + 1)return resultdef to_dict(self) -> Dict[str, Any]:"""將Span轉換為字典(用于序列化)"""return {"hash": self.hash,"create_time": self.create_time,"end_time": self.end_time,"children": [child.to_dict() for child in self.children],"parent_hash": self.parent.hash if self.parent else None,"status": self.status,"content": self.content}@classmethoddef from_dict(cls, data: Dict[str, Any], span_mgr: 'Span_Mgr') -> 'Span':"""從字典創建Span對象"""span = cls.__new__(cls)span.hash = data["hash"]span.create_time = data["create_time"]span.end_time = data["end_time"]span.status = data["status"]span.content = data["content"]span._lock = threading.RLock()# 重建父子關系span.parent = span_mgr.get_span_by_hash(data["parent_hash"]) if data["parent_hash"] else None# 遞歸重建子Spanspan.children = []for child_data in data["children"]:child_span = cls.from_dict(child_data, span_mgr)child_span.parent = spanspan.children.append(child_span)return spandef __str__(self) -> str:return self.display()class Span_Mgr:def __init__(self, storage_filename: str = "span_data.json", expiry_days: int = 7):"""初始化Span管理器Args:storage_filename: 存儲文件名expiry_days: 數據過期天數"""self.storage = ExpiringDictStorage(filename=storage_filename, expiry_days=expiry_days)self.root_spans: List[Span] = []  # 所有根Span(沒有父Span的Span)self.all_spans: Dict[int, Span] = {}  # 所有Span的哈希映射self._lock = threading.RLock()# 從存儲加載現有數據self._load_from_storage()def _load_from_storage(self) -> None:"""從存儲加載Span數據"""with self._lock:stored_data = self.storage.get("span_data", update_timestamp=False)if stored_data:try:# 重建所有Span對象span_dicts = stored_data.get("spans", {})temp_spans = {}# 先創建所有Span對象(不設置父子關系)for hash_str, span_data in span_dicts.items():span_hash = int(hash_str)span = Span.__new__(Span)span.hash = span_hashspan.create_time = span_data["create_time"]span.end_time = span_data["end_time"]span.status = span_data["status"]span.content = span_data["content"]span._lock = threading.RLock()span.children = []  # 暫時為空temp_spans[span_hash] = span# 設置父子關系for span_hash, span_data in span_dicts.items():span = temp_spans[int(span_hash)]parent_hash = span_data["parent_hash"]if parent_hash:span.parent = temp_spans.get(parent_hash)# 重建子Span列表for child_hash in span_data["children_hashes"]:child_span = temp_spans.get(child_hash)if child_span:span.children.append(child_span)# 重建根Span列表和所有Span映射self.root_spans = [span for span in temp_spans.values() if span.parent is None]self.all_spans = temp_spansexcept Exception as e:print(f"Error loading span data: {e}")self.root_spans = []self.all_spans = {}def _save_to_storage(self) -> None:"""保存Span數據到存儲"""with self._lock:spans_data = {}for span_hash, span in self.all_spans.items():spans_data[str(span_hash)] = {"create_time": span.create_time,"end_time": span.end_time,"parent_hash": span.parent.hash if span.parent else None,"children_hashes": [child.hash for child in span.children],"status": span.status,"content": span.content}self.storage.set("span_data", {"spans": spans_data})def create_span(self, content: Any, parent_hash: Optional[int] = None) -> Span:"""創建新的SpanArgs:content: Span內容parent_hash: 父Span的hash值,如果為None則創建根SpanReturns:Span: 新創建的Span對象"""with self._lock:parent = self.all_spans.get(parent_hash) if parent_hash else Nonenew_span = Span(content, parent)# 如果沒有父Span,添加到根Span列表if parent is None:self.root_spans.append(new_span)# 添加到所有Span映射self.all_spans[new_span.hash] = new_span# 保存到存儲self._save_to_storage()return new_spandef get_recent_parent_spans(self) -> List[Span]:"""查詢最近所有的父Span(根Span),按照創建時間順序返回Returns:List[Span]: 按創建時間排序的父Span列表"""with self._lock:return sorted(self.root_spans, key=lambda x: x.create_time, reverse=True)def get_span_by_hash(self, span_hash: int) -> Optional[Span]:"""根據hash值獲取SpanArgs:span_hash: Span的hash值Returns:Optional[Span]: 找到的Span對象,如果不存在則返回None"""with self._lock:return self.all_spans.get(span_hash)def end_span(self, span_hash: int) -> bool:"""結束指定的SpanArgs:span_hash: 要結束的Span的hash值Returns:bool: 是否成功結束Span"""with self._lock:span = self.all_spans.get(span_hash)if span and span.end():self._save_to_storage()return Truereturn Falsedef display_all_spans(self) -> str:"""顯示所有Span的層級結構"""with self._lock:result = ""for span in sorted(self.root_spans, key=lambda x: x.create_time):result += span.display()return result# 使用示例
if __name__ == "__main__":# 創建Span管理器span_mgr = Span_Mgr()# 創建一些Spanroot_span = span_mgr.create_span("Root operation")child1 = span_mgr.create_span("Child operation 1", root_span.hash)child2 = span_mgr.create_span("Child operation 2", root_span.hash)grandchild = span_mgr.create_span("Grandchild operation", child1.hash)# 顯示所有Spanprint("All spans:")print(span_mgr.display_all_spans())# 結束子Span(應該失敗,因為孫子Span還沒結束)print(f"Ending child1: {span_mgr.end_span(child1.hash)}")# 結束孫子Spanprint(f"Ending grandchild: {span_mgr.end_span(grandchild.hash)}")# 現在可以結束child1print(f"Ending child1: {span_mgr.end_span(child1.hash)}")# 結束child2print(f"Ending child2: {span_mgr.end_span(child2.hash)}")# 現在可以結束根Spanprint(f"Ending root: {span_mgr.end_span(root_span.hash)}")# 顯示最終狀態print("\nFinal state:")print(span_mgr.display_all_spans())# 查詢最近的父Spanprint("\nRecent parent spans:")for span in span_mgr.get_recent_parent_spans():create_time = datetime.fromtimestamp(span.create_time / 1e9).strftime('%Y-%m-%d %H:%M:%S')print(f"  Span(hash={span.hash}, created={create_time}, content={span.content})")

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/93855.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/93855.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/93855.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Hi3516CV610-00S 海思SOC芯片 可申請開發資料

1.1 概述Hi3516CV610 是一顆應用在安防市場的 IPC SoC。在開放操作系統、新一代視頻編解碼標準、網絡安全和隱私保護、人工智能方面引領行業發展&#xff0c;主要面向室內外場景下的槍機、球機、半球機、海螺機、槍球一體機、雙目長短焦機等產品形態&#xff0c;打造極具競爭力…

算法題Day4

目錄 13. 練習13 : 整數十位 14. 練習14 : 時間轉換 15. 練習15 : 小雨的游泳時間 13. 練習13 : 整數十位 解題方法: #include <iostream> using namespace std; int a; int main() {cin >> a;cout << a % 100 / 10 << endl;return 0; } 14. 練習…

加速你的故障排查:使用 Elasticsearch 構建家電手冊的 RAG 應用

作者&#xff1a;來自 Elastic Alessandro Brofferio 學習如何使用 Elasticsearch 構建 RAG 應用&#xff0c;輕松排查你的家電問題。 想要獲得 Elastic 認證嗎&#xff1f;來看看下一次 Elasticsearch 工程師培訓什么時候開始吧&#xff01; Elasticsearch 擁有大量新功能&am…

6.Shell腳本修煉手冊---grep命令使用指南

grep 命令&#xff1a;從文本中精準篩選信息的實用指南 文章目錄grep 命令&#xff1a;從文本中精準篩選信息的實用指南一、什么是 grep&#xff1f;為什么要用它&#xff1f;二、grep 基本語法三、常用選項詳解&#xff08;附實例&#xff09;&#xff08;一&#xff09;模式選…

Python day51

浙大疏錦行 Python day51 復習日&#xff0c;DDPM class DenoiseDiffusion():def __init__(self, eps_model: nn.Module, n_steps: int, device: torch.device):super().__init__()self.eps_model eps_modelself.n_steps n_stepsself.device deviceself.beta torch.linsp…

數據結構:生成 (Generating) 一棵 AVL 樹

目錄 搭建“創世”的舞臺 注入序列&#xff0c;觀察演化 注入 10 注入 20 注入 30 注入 40 注入 50 注入 25 再次審視 上一講&#xff0c;我們已經從最根本的邏輯出發&#xff0c;推導出了 AVL 樹失衡時所必需的修復操作——旋轉 (Rotation)。 現在&#xff0c;我們將…

github 上傳代碼步驟

登錄GitHub → 點擊右上角 ?? → New Repository??。填寫倉庫名稱&#xff08;建議與本地項目同名&#xff09;&#xff0c;選擇 ??Public/Private??。??關鍵&#xff1a;不要勾選?? “Initialize with README”&#xff08;避免與本地倉庫沖突&#xff09;。點擊 …

陪診小程序系統開發:開啟智慧就醫新時代

在數字化浪潮的推動下&#xff0c;智慧醫療正逐漸成為現實。陪診小程序系統的開發&#xff0c;作為智慧醫療領域的一次重要創新&#xff0c;正以其獨特的魅力與優勢&#xff0c;引領著就醫新時代的到來。它不僅改變了傳統就醫模式&#xff0c;更以科技的力量&#xff0c;讓醫療…

朝花夕拾(七)--------從混淆矩陣到分類報告全面解析?

目錄 ??機器學習模型評估指南&#xff1a;從混淆矩陣到分類報告全面解析?? ??1. 引言?? ??2. 混淆矩陣&#xff1a;模型評估的基石?? ??2.1 什么是混淆矩陣&#xff1f;?? 2.2二分類問題的混淆矩陣 ??二分類場景下的具體案例? ?分析案例: 1.??案例…

Python讀取和設置PNG圖片的像素值

在Python中&#xff0c;可以使用Pillow庫或OpenCV庫來讀取和寫入PNG圖片的像素值。以下是兩種方法的詳細說明&#xff1a;1. 使用Pillow庫Pillow是Python中常用的圖像處理庫&#xff0c;支持多種圖像格式&#xff0c;包括PNG。讀取像素值from PIL import Imageimg Image.open(…

SkyWalking + Elasticsearch8 容器化部署指南:國內鏡像加速與生產級調優

SkyWalking Elasticsearch8 Docker 部署文檔本文提供在 Ubuntu 服務器上&#xff0c;使用 Docker Compose 部署 SkyWalking&#xff08;OAPUI&#xff09;與 Elasticsearch 8 的完整步驟&#xff0c;數據/日志落地到 /media/disk2 前置條件 Ubuntu&#xff0c;已具備 sudo 權限…

有符號和無符號的區別

有符號&#xff08;Signed&#xff09;和無符號&#xff08;Unsigned&#xff09;是計算機編程中用來描述整數數據類型能否表示負數的兩個概念。它們的主要區別在于能否表示負數以及數值的表示范圍。以下是它們的核心區別&#xff1a;1. 能否表示負數有符號&#xff08;Signed&…

8月21日作業

1、Makefile中頭文件發生過修改的解決&#xff1a; 處插入*.h依賴&#xff0c;對.h文件打的時間戳進行檢查2、頭刪和輸出//五、頭刪 void delete_head(seq_p s) {empty(s);for(int i1;i<s->len;i){s->data[i-1]s->data[i];}s->len--; }//六、輸出 void output(s…

Lucene 8.5.0 的 `.pos` 文件**邏輯結構**

Lucene 8.5.0 的 .pos 文件**邏輯結構**&#xff08;按真實實現重新整理&#xff09; .pos 文件 ├─ Header (CodecHeader) ├─ TermPositions TermCount ← 每個 term 一段&#xff0c;順序由詞典隱式決定 │ ├─ PackedPosDeltaBlock N ← 僅當 **無 payl…

基于Matlab多技術融合的紅外圖像增強方法研究

紅外圖像在低照度、強干擾和復雜環境下具有較強的成像能力&#xff0c;但受傳感器噪聲、成像條件及大氣衰減等因素影響&#xff0c;原始紅外圖像往往存在對比度低、細節模糊及光照不均等問題。本文針對紅外圖像質量退化的特點&#xff0c;提出了一種基于多算法融合的紅外圖像增…

【時時三省】集成測試 簡介

山不在高,有仙則名。水不在深,有龍則靈。 ----CSDN 時時三省 目錄 1,集成測試含義 2,集成測試 驗證方法 3,集成測試 用例設計方法 4,集成測試輸出物 5,集成測試注意點 1,集成測試含義 單元測試在以V模型的流程中,對應的是架構設計階段。在 單元測試 和 架構設計…

leetcode 76 最小覆蓋子串

一、題目描述二、解題思路整體思路&#xff1a;模擬尋找最小覆蓋子集的過程&#xff0c;由于可借助同向雙指針且可以做到指針不回退&#xff0c;所以可以用滑動窗口的思想來解決這個問題。具體思路&#xff1a;(1)數組hash1用于統計t中每一個字符出現的頻次&#xff0c;變量kin…

阿里云ECS服務器的公網IP地址

文章目錄環境背景查詢公網IP地址阿里云控制臺阿里云客戶端工具&#xff08;圖形界面&#xff09;阿里云CLI工具&#xff08;命令行&#xff09;其它方法元數據服務器ipinfo.io參考注&#xff1a;本文介紹了如何獲取阿里云ECS服務器的公網IP地址&#xff0c;可以順便了解一下和阿…

IPSec 與 IKE 核心知識點總結

一、IPSec 安全基礎IPSec 是保障 IP 數據傳輸安全的核心協議&#xff0c;其核心圍繞密鑰管理和安全策略約定展開&#xff0c;具體包括以下關鍵內容&#xff1a;1. 對稱密鑰的作用與要求對稱密鑰是 IPSec 實現加密、驗證的基礎&#xff0c;主要用于三個場景&#xff1a;加密 / 解…

C2ComponentStore

1. C2ComponentStore這是 Codec 2.0 HAL 的抽象接口&#xff08;frameworks/av/media/codec2/core/include/C2ComponentStore.h&#xff09;。代表一個「組件工廠」&#xff0c;負責&#xff1a;枚舉當前可用的 Codec2 組件&#xff08;解碼器、編碼器&#xff09;。創建組件&a…