From 85648aaf3a9cce78f378c2922ea7c22b094915e5 Mon Sep 17 00:00:00 2001 From: luyaxi Date: Thu, 17 Oct 2024 14:43:54 +0800 Subject: [PATCH] add get method --- codelinker/events/processer.py | 34 ++++++++++++++++++++++++++++++++++ pyproject.toml | 2 +- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/codelinker/events/processer.py b/codelinker/events/processer.py index df25f1f..ae3bf3d 100644 --- a/codelinker/events/processer.py +++ b/codelinker/events/processer.py @@ -30,6 +30,40 @@ def unlisten(self, func: callable): def wait(self, tags: ChannelTag | Iterable[ChannelTag]): return self.sink.wait(tags) + + def get(self,tag: ChannelTag, return_dumper: Callable|Literal['str','json','identity'] = 'str'): + """Get last event in the channel.""" + def tag_filter(event: SEvent): + if tag is None: + return True + if isinstance(tag, ChannelTag): + if tag in event.tags: + return True + return False + if tag in event.tags: + return True + return False + + + gathered_events = list(filter(tag_filter, self.sink.all_events)) + if isinstance(return_dumper,str): + match return_dumper: + case 'str': + return_dumper = str + case 'json': + import json + return_dumper = partial(json.dumps, ensure_ascii=False,sort_keys=False) + case 'identity': + return_dumper = lambda x: x + + assert callable(return_dumper), "return_dumper must be a callable'" + + event = gathered_events[-1] + if event.source == self.name: + return {'role': 'assistant', 'content': event.content} + else: + return {'role': 'user', 'content': return_dumper(event)} + def gather(self, tags: ChannelTag | Iterable[ChannelTag] | None = None, return_dumper: Callable|Literal['str','json','identity'] = 'str') -> Iterable[dict]: def tag_filter(event: SEvent): diff --git a/pyproject.toml b/pyproject.toml index 70dfb20..71596f0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "codelinker" -version = "0.3.23" +version = "0.3.24" description = "A tool to link the code with large language models." authors = ["luyaxi "] readme = "README.md"