Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
1247 commits
Select commit Hold shift + click to select a range
1d5c0ad
update api
zhuzhongshu123 May 26, 2025
ccf8390
update api
zhuzhongshu123 May 27, 2025
a9e206a
update api
zhuzhongshu123 May 27, 2025
8442831
update markdown reader for alibaba table parent id
northmachine May 27, 2025
395db47
Merge branch 'tc_configurable_index_mng' of github.com:OpenSPG/KAG in…
northmachine May 27, 2025
103e398
update api
zhuzhongshu123 May 27, 2025
88c6507
make summary_chunk_retriever.py async
xionghuaidong May 23, 2025
3de3bda
add indexer.py for AFAC2024
xionghuaidong May 27, 2025
f8f7be2
reduce rate limit and concurrency for AFAC2024
xionghuaidong May 27, 2025
0abee08
fix some bug in reporter
royzhao May 28, 2025
0773192
update knext project create
northmachine May 28, 2025
dba10c5
support stop_token_ids in vllm
royzhao May 28, 2025
5758c09
Merge branch '0.8.0_dev' of github.com:OpenSPG/KAG into 0.8.0_dev
royzhao May 28, 2025
9b43138
update markdown reader for alibaba table parent id
northmachine May 27, 2025
bd8b7f8
Merge branch '0.8.0_dev' of github.com:OpenSPG/KAG into 0.8.0_dev
northmachine May 28, 2025
807205a
Merge remote-tracking branch 'refs/remotes/origin/configurable_index_…
caszkgui May 28, 2025
6622c79
update api
zhuzhongshu123 May 28, 2025
4b33bf4
Merge remote-tracking branch 'upstream/configurable_index_mng' into c…
zhuzhongshu123 May 28, 2025
dc58954
update api
zhuzhongshu123 May 28, 2025
b980451
add eval.py for AFAC2024
xionghuaidong May 28, 2025
e374362
specify kag_config.yaml dumping encoding and newline
xionghuaidong May 28, 2025
751ac2d
update
northmachine May 28, 2025
8061064
kag_hybrid_executor support single node flow.
fishjoy May 28, 2025
08ace90
add table_extractor
caszkgui May 28, 2025
ed378bd
Merge remote-tracking branch 'refs/remotes/origin/configurable_index_…
caszkgui May 28, 2025
45683b3
bugfix in main_solver
fishjoy May 28, 2025
6ca08bd
bugfix for reporter register
royzhao May 28, 2025
7efd641
Merge branch '0.8.0_dev' of github.com:OpenSPG/KAG into 0.8.0_dev
royzhao May 28, 2025
54768ee
update benchmark cmd
zhuzhongshu123 May 28, 2025
d4cb46f
Merge remote-tracking branch 'upstream/configurable_index_mng' into c…
zhuzhongshu123 May 28, 2025
beea481
update
northmachine May 28, 2025
7a5eafa
Merge branch '0.8.0_dev' of github.com:OpenSPG/KAG into 0.8.0_dev
northmachine May 28, 2025
90a4ac6
update
northmachine May 28, 2025
5e8409c
Merge branch 'tc_configurable_index_mng' of github.com:OpenSPG/KAG in…
northmachine May 28, 2025
e48e547
revert knext
northmachine May 28, 2025
a53099b
add knext userNo
northmachine May 28, 2025
0b15f4d
add diagram_retriever
caszkgui May 28, 2025
516f9b4
merge from 0.8.0_dev
royzhao May 29, 2025
57c6f0e
Merge branch 'configurable_index_mng' of github.com:OpenSPG/KAG into …
royzhao May 29, 2025
df8f825
support index check pipeline
royzhao May 29, 2025
ccf68c4
save afac2024 experiment: vector chunk + summary
xionghuaidong May 29, 2025
0fc4721
1、update atomic_query_retriever
caszkgui May 29, 2025
1153608
Merge remote-tracking branch 'refs/remotes/origin/tc_configurable_ind…
caszkgui May 29, 2025
038e659
Merge remote-tracking branch 'refs/remotes/origin/configurable_index_…
caszkgui May 29, 2025
7e7e183
1、pre-commit-run
caszkgui May 29, 2025
5b56eaf
feat(builder): add table_extractor for kag (#564)
caszkgui May 29, 2025
d8dc47d
1、rename diagram to table
caszkgui May 29, 2025
e6db57f
Merge remote-tracking branch 'refs/remotes/origin/configurable_index_…
caszkgui May 29, 2025
23dc28b
1、add scanignore
caszkgui May 29, 2025
df9d965
add knext user_no
northmachine May 29, 2025
7fc598f
refactor md reader
northmachine May 29, 2025
c23e707
refactor md reader
northmachine May 29, 2025
1a0a417
1、rename relatedTo to sourceChunk
caszkgui May 29, 2025
eb4bf1e
Merge remote-tracking branch 'refs/remotes/origin/configurable_index_…
caszkgui May 29, 2025
27dae6f
support kag hybrid component
royzhao May 30, 2025
c6845b0
Merge remote-tracking branch 'origin/configurable_index_mng' into con…
royzhao May 30, 2025
00220e7
1、fix bug in AFAC2024
caszkgui May 30, 2025
42d4dc2
fix planner rewrite
royzhao May 30, 2025
18ef665
bugfix in registry.
fishjoy May 30, 2025
226780c
1、临时存储AFAC2024 的改动:
caszkgui May 30, 2025
6b527bf
1、记录当前配置对应的指标:
caszkgui May 31, 2025
164f518
feat(kag): ollama vectorize model (#562)
thundax-lyp May 31, 2025
6d7a954
fix merge
royzhao Jun 1, 2025
ae45692
Update README.md add DeepWiki Badge (#532)
Like0x Jun 2, 2025
1b8cb6e
Fix: Enhance robustness and clarity in kg-solver components (#548)
thesteganos Jun 2, 2025
6b10e0b
Refactor: Improve logic and error handling in KAGIterativePipeline (#…
thesteganos Jun 2, 2025
12fab34
1、记录当前配置对应的指标(基于qwen2.5-72B):
caszkgui Jun 3, 2025
3aae984
remove namespace
zhuzhongshu123 Jun 3, 2025
108ebbe
Merge remote-tracking branch 'upstream/configurable_index_mng' into c…
zhuzhongshu123 Jun 3, 2025
b532fb6
fix circle import
royzhao Jun 3, 2025
731be72
modify hotpotqa
zhuzhongshu123 Jun 3, 2025
b1ef44e
add musique
zhuzhongshu123 Jun 3, 2025
9abca99
update config
zhuzhongshu123 Jun 3, 2025
91f8044
fix atomic query
royzhao Jun 4, 2025
70a4bff
add top p and seed
royzhao Jun 4, 2025
c847c3a
add llm backup
royzhao Jun 4, 2025
efdf62b
Merge branch '0.8.0_dev' into update_knext
northmachine Jun 4, 2025
91812ff
Merge branch 'configurable_index_mng' into xhd_configurable_index_mng
xionghuaidong Jun 4, 2025
053fc31
Merge remote-tracking branch 'origin/tc_configurable_index_mng' into …
xionghuaidong Jun 4, 2025
c3d15f0
workaround database schema and knext command mismatch; fix it later
xionghuaidong Jun 4, 2025
e5f3707
update knext
northmachine Jun 4, 2025
61a47f1
set max_concurrency to 10
xionghuaidong Jun 4, 2025
684e325
turn off SchemaFreeExtractor for the moment
xionghuaidong Jun 4, 2025
bb1ce01
1、记录 musique 当前配置对应的指标(基于qwen2.5-72B):
caszkgui Jun 4, 2025
f8bb2c6
update odps reader
northmachine Jun 4, 2025
a95db6d
update odps reader
northmachine Jun 4, 2025
17a6cac
add openai param
royzhao Jun 5, 2025
aaa30d7
Merge branch '0.8.0_dev' into update_knext
northmachine Jun 5, 2025
007caef
Merge remote-tracking branch 'origin/tc_configurable_index_mng' into …
xionghuaidong Jun 5, 2025
b4c6710
add chunk index
zhuzhongshu123 Jun 5, 2025
7c83cb8
save AFAC2024 experiment results: vector + summary + table
xionghuaidong Jun 5, 2025
172c42d
save AFAC2024 experiment results: vector + summary + table
xionghuaidong Jun 5, 2025
34ecb38
update IndexTypeEnum to include SparseVector and TextAndSparseVector
xionghuaidong May 29, 2025
664d695
add interface SparseVectorizeModelABC and implementation sparse_bge_m3
xionghuaidong May 29, 2025
89628d1
update BatchVectorizer to generate sparse embedding vectors
xionghuaidong May 29, 2025
2b92737
pass sparse vectors as strings from model
xionghuaidong Jun 5, 2025
d3e0b6c
Merge branch '0.8.0_sparse_vector_index' into 0.8.0_dev
xionghuaidong Jun 5, 2025
224620a
add protect data
royzhao Jun 5, 2025
71566b7
add hybrid index mgr
zhuzhongshu123 Jun 6, 2025
a504b61
update recall for AFAC2024
northmachine Jun 6, 2025
8292aef
Merge branch 'update_knext' into configurable_index_mng
northmachine Jun 6, 2025
f362e37
remove unused langchain dependencies
xionghuaidong Jun 6, 2025
0c9ec7c
remove unused elasticsearch dependency
xionghuaidong Jun 6, 2025
ebb068f
remove local bge model and dependency scikit-learn
xionghuaidong Jun 6, 2025
136c1b1
remove unnecessary requirement setuptools
xionghuaidong Jun 6, 2025
a5c34c0
specify kag_config.yaml dumping encoding and newline
xionghuaidong Jun 6, 2025
732c49d
Merge remote-tracking branch 'origin/xhd_configurable_index_mng' into…
xionghuaidong Jun 6, 2025
10a2af3
Merge branch '0.8.0_dev' of github.com:OpenSPG/KAG into 0.8.0_dev
royzhao Jun 9, 2025
1128e1f
Merge branch '0.8.0_dev' into 0.8.0_dev_xhd
xionghuaidong Jun 9, 2025
2899f95
add index hybrd graph
royzhao Jun 9, 2025
de3b3a6
add dependency PyYAML
xionghuaidong Jun 9, 2025
2a6a598
end sparse vector field name with '_sparse'
xionghuaidong Jun 10, 2025
12fad28
update _decode_response_data to match model result format
xionghuaidong Jun 10, 2025
2bd7cd0
update hitall 0.98
northmachine Jun 10, 2025
2976d86
update hitall 0.98
northmachine Jun 10, 2025
9d4555d
fix bug std p
royzhao Jun 10, 2025
cbe5937
fix merge conflict
royzhao Jun 10, 2025
07809cb
add answered
royzhao Jun 10, 2025
295b950
update markdown reader buildercomponentdata for aisearch
northmachine Jun 10, 2025
7b08464
fix bug std p
royzhao Jun 10, 2025
6357df4
one hop
royzhao Jun 10, 2025
e5837f5
add revert target value
royzhao Jun 10, 2025
5390340
add tc rerank
northmachine Jun 10, 2025
fa10176
fix el types
royzhao Jun 11, 2025
d021cc2
update markdown reader for aisearch
northmachine Jun 11, 2025
1c32154
fix conflict
royzhao Jun 11, 2025
0428e98
fix model
royzhao Jun 11, 2025
d5639f7
add debug log
zhuzhongshu123 Jun 11, 2025
fb3b154
add debug log
zhuzhongshu123 Jun 11, 2025
9aebaee
add kag access configer
royzhao Jun 11, 2025
4b332bc
override host_addr unconditionally to avoid incorrect host_addr on se…
xionghuaidong Jun 11, 2025
2ad70fc
add reportor
royzhao Jun 11, 2025
8845838
return str
zhuzhongshu123 Jun 11, 2025
d5a6aa5
fix executor
royzhao Jun 11, 2025
7e82cc0
update for iteration pipeline
northmachine Jun 12, 2025
4d54e8b
update for iteration pipeline
northmachine Jun 12, 2025
e33edbc
Merge branch 'jc_configurable_index_mng' into 0.8.0_dev
northmachine Jun 12, 2025
3c7ffe1
disable checkpoint
zhuzhongshu123 Jun 12, 2025
7d42d7c
file based token meter
zhuzhongshu123 Jun 12, 2025
22fcf6e
file based token meter
zhuzhongshu123 Jun 12, 2025
8791f50
file based token meter
zhuzhongshu123 Jun 12, 2025
a858655
add in memory mode
zhuzhongshu123 Jun 12, 2025
07e3640
add in memory mode
zhuzhongshu123 Jun 12, 2025
fce8172
add in memory mode
zhuzhongshu123 Jun 12, 2025
5ba5277
add in memory mode
zhuzhongshu123 Jun 12, 2025
d6edde0
add in memory mode
zhuzhongshu123 Jun 12, 2025
89566cc
remove debug log
zhuzhongshu123 Jun 13, 2025
5309f34
merge 0.8.0
zhuzhongshu123 Jun 13, 2025
23f56e1
fix
northmachine Jun 13, 2025
27e7365
pre-commit
zhuzhongshu123 Jun 13, 2025
140692a
fix readme
zhuzhongshu123 Jun 13, 2025
13eaccb
feat(kag): support index manager (#578)
zhuzhongshu123 Jun 13, 2025
6cbe528
Merge branch '0.8.0_dev' of github.com:OpenSPG/KAG into 0.8.0_dev
northmachine Jun 13, 2025
3c7c47a
Merge remote-tracking branch 'origin/0.8.0_dev' into 0.8.0_dev_xhd
xionghuaidong Jun 13, 2025
fa4e9fc
update KagIndexManager for table, summary, outline index
northmachine Jun 13, 2025
d9b5b78
Merge branch '0.8.0_dev' of github.com:OpenSPG/KAG into 0.8.0_dev
northmachine Jun 13, 2025
d7089cf
add graph
royzhao Jun 13, 2025
b2b673a
add std schema
royzhao Jun 13, 2025
ccced8d
use KAGConfigAccessor
Jun 13, 2025
1612d20
Merge branch 'configurable_index_mng_kag_config' of github.com:OpenSP…
Jun 13, 2025
d11deef
fix bug for None
royzhao Jun 13, 2025
02815db
update atomic extract _invoke
northmachine Jun 13, 2025
dea34db
use KAGConfigAccessor
Jun 16, 2025
ce9b53c
hybrid.yaml
Jun 16, 2025
3b01302
fix project id access
royzhao Jun 16, 2025
2a018d3
fix conflict
royzhao Jun 16, 2025
74e907e
import indexABC
royzhao Jun 16, 2025
859d890
commit reporter
royzhao Jun 16, 2025
55b23de
optimize
Jun 16, 2025
7954abd
add knowledge unit extra
royzhao Jun 16, 2025
536730d
Merge branch '0.8.0_dev' into configurable_index_mng_kag_config
Jun 16, 2025
807ea20
bugfix: 避免一次用多个asyncio.run,会创建多个loop,复用现有的loop
Jun 16, 2025
f3e1e94
bugfix: 取消benchmark的KAG_PROJECT_CONF修改
Jun 16, 2025
aa0c57e
添加测试进度条
Jun 16, 2025
d33cf1c
Merge pull request #585 from OpenSPG/configurable_index_mng_kag_config
wxy20152016 Jun 16, 2025
5996da2
冗余代码收拢到基类中实现,派生类直接使用
Jun 16, 2025
a0cae08
冗余代码收拢到基类中实现,派生类直接使用
Jun 16, 2025
a037a79
fix_prompt
royzhao Jun 16, 2025
2454d02
extract common function into benchmark commponent
royzhao Jun 16, 2025
b4467be
Merge remote-tracking branch 'origin/configurable_index_mng_kag_confi…
royzhao Jun 16, 2025
5fa2ac6
Merge branch '0.8.0_dev' into configurable_index_mng_kag_config
royzhao Jun 16, 2025
d188fec
merge 0.8.0_dev
royzhao Jun 16, 2025
dedab1d
format code
royzhao Jun 16, 2025
8b8d81e
format code
royzhao Jun 16, 2025
9e9d446
format code
royzhao Jun 16, 2025
19651bc
feat(solver): support knowledge unit indexer (#586)
royzhao Jun 17, 2025
5c7a60a
Merge branch '0.8.0_dev' of github.com:OpenSPG/KAG into configurable_…
royzhao Jun 17, 2025
7fb3f9a
update index manager msg
northmachine Jun 17, 2025
1b095b8
Merge branch '0.8.0_dev' of github.com:OpenSPG/KAG into 0.8.0_dev
northmachine Jun 17, 2025
9edeab4
update index manager msg
northmachine Jun 17, 2025
62df9c5
删除测试的hybrid.yaml,更新deep_thought.yaml为多retrievers
Jun 17, 2025
be5f104
fix benchmark knowledge unit
royzhao Jun 17, 2025
2ace7bf
fix node
royzhao Jun 17, 2025
48c3dba
feat(solver): add knowledge unit into benchmark yaml (#587)
royzhao Jun 17, 2025
b1717df
add common component
royzhao Jun 17, 2025
d6705eb
Revert "remove local bge model and dependency scikit-learn"
royzhao Jun 17, 2025
0a61f47
remove unused pkg
royzhao Jun 17, 2025
75594be
add decompose
royzhao Jun 18, 2025
3385d69
change hybrid default config
royzhao Jun 18, 2025
f42dafc
add trace log
royzhao Jun 18, 2025
1d99a20
merge master
royzhao Jun 18, 2025
cf83b88
feat(solver): update example solver pipeline (#588)
royzhao Jun 18, 2025
16a9654
Merge branch '0.8.0_dev' of github.com:OpenSPG/KAG into configurable_…
royzhao Jun 18, 2025
5e3e3f8
fix(solver): trace log with graph (#590)
royzhao Jun 18, 2025
533b431
affairqa { (#591)
northmachine Jun 18, 2025
383f7c7
优化spo_retrieval调用大模型耗时过长的问题,直接输出索引
Jun 18, 2025
266b830
1、添加两个mcp的README.md 以及对文件重命名
Jun 18, 2025
ff7f199
fix some bugs
royzhao Jun 18, 2025
a78c4e1
update
northmachine Jun 19, 2025
011ce6c
bugfix: 修复mcp中向量不存在的情况下出错的问题,通过get获取向量
Jun 19, 2025
9e40080
fix knext
northmachine Jun 19, 2025
6ae3ae6
Merge branch '0.8.0_dev' of github.com:OpenSPG/KAG into 0.8.0_dev
northmachine Jun 19, 2025
c9bff01
fix(kag): update examples to work under branch 0.8.0 (#593)
xionghuaidong Jun 19, 2025
09995a5
Merge branch '0.8.0_dev' of github.com:OpenSPG/KAG into configurable_…
royzhao Jun 19, 2025
bd1049a
feat(mcp): implement mcp server for kag (#594)
xionghuaidong Jun 19, 2025
b672487
fix the kb-retrieve tool
xionghuaidong Jun 19, 2025
f441d50
with prompt
royzhao Jun 19, 2025
d7ff48b
support benchmark unit
royzhao Jun 20, 2025
1d35b93
Merge branch '0.8.0_dev' of github.com:OpenSPG/KAG into configurable_…
royzhao Jun 20, 2025
aa9cbf6
support kag thinker model
royzhao Jun 20, 2025
3235927
support kag thinker model config
royzhao Jun 20, 2025
7a34cc5
remove default host addr and project id
royzhao Jun 23, 2025
56394b0
bugfix: 修复测试中table index的问题
Jun 23, 2025
239112e
add kag model infer script
royzhao Jun 23, 2025
dc73401
add kag model infer script
royzhao Jun 23, 2025
2c38a56
Merge branch '0.8.0_dev' of github.com:OpenSPG/KAG into configurable_…
royzhao Jun 23, 2025
cb1ac6e
feat(solver): add index type and modify knowledge unit solver yaml (#…
royzhao Jun 23, 2025
b0fb698
Merge branch '0.8.0_dev' of github.com:OpenSPG/KAG into configurable_…
royzhao Jun 23, 2025
6f0e89f
modify prompt for kag model
royzhao Jun 23, 2025
4e17fce
feat(solver): add kag model pipeline and modify prompt (#598)
royzhao Jun 23, 2025
197446a
update
northmachine Jun 23, 2025
984c2f4
Merge branch '0.8.0_dev' of github.com:OpenSPG/KAG into 0.8.0_dev
northmachine Jun 23, 2025
57e612f
modify hybrid index docs
royzhao Jun 23, 2025
174dbf0
fix conflict
royzhao Jun 23, 2025
714843f
use ttl cache
royzhao Jun 24, 2025
1a919b6
add retriever name property
royzhao Jun 24, 2025
b858603
fix client project
royzhao Jun 24, 2025
91ee1ed
fix knowledge unit extractor
royzhao Jun 24, 2025
60bf980
fix main solver pipeline
royzhao Jun 25, 2025
61f0fd9
fix main solver pipeline
royzhao Jun 25, 2025
f880f91
fix writer bug (#605)
royzhao Jun 26, 2025
5937653
bugfix: 修复sourceChunk和relateTo名称不一致的问题 (#606)
wxy20152016 Jun 26, 2025
96e8f5d
update examples (#607)
northmachine Jun 26, 2025
f34ef7b
fix(builder): use index manager to commit index schema (#608)
royzhao Jun 26, 2025
a58242b
merge master
royzhao Jun 26, 2025
c1bb611
add host addr
royzhao Jun 27, 2025
806a53d
add rate limiter
royzhao Jun 30, 2025
3a4c462
merge master
royzhao Jun 30, 2025
7af86d8
merge master
royzhao Jun 30, 2025
3c64e98
fix pylink
royzhao Jun 30, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions kag/common/rate_limiter.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
# or implied.

from aiolimiter import AsyncLimiter
import threading
import time
from collections import deque


class RateLimiterManger:
Expand All @@ -27,3 +30,71 @@ def get_rate_limiter(


RATE_LIMITER_MANGER = RateLimiterManger()


class SyncRateLimiter:
def __init__(self, max_rate: int, time_period: float = 1.0):
"""
Initialize the rate limiter.

:param max_rate: The maximum number of requests allowed within the time window.
:param time_period: The length of the time window in seconds.
"""
self.max_rate = max_rate
self.time_period = time_period
self.lock = threading.Lock()
self.call_timestamps = deque()

def acquire(self):
"""
Acquire a permit to proceed. If the rate limit is exceeded, block and wait until a permit becomes available.
"""
with self.lock:
now = time.time()
# Remove records outside the current time window
while (
self.call_timestamps
and now - self.call_timestamps[0] >= self.time_period
):
self.call_timestamps.popleft()

if len(self.call_timestamps) >= self.max_rate:
# Wait until the earliest request exits the window
sleep_time = self.call_timestamps[0] + self.time_period - now
if sleep_time > 0:
time.sleep(sleep_time)
now = time.time() # Update current time after waiting
# Clean up expired requests again
while (
self.call_timestamps
and now - self.call_timestamps[0] >= self.time_period
):
self.call_timestamps.popleft()

# Append the timestamp of the current request
self.call_timestamps.append(now)


class SyncRateLimiterManager:
def __init__(self):
self.limiter_map = {}
self.lock = threading.Lock()

def get_rate_limiter(
self, name: str, max_rate: int = 1000, time_period: float = 1.0
):
"""
Get or create a SyncRateLimiter instance by name in a thread-safe manner.

:param name: Unique identifier for the rate limiter.
:param max_rate: Maximum number of requests allowed within the time window.
:param time_period: Length of the time window in seconds.
:return: A thread-safe SyncRateLimiter instance.
"""
with self.lock:
if name not in self.limiter_map:
self.limiter_map[name] = SyncRateLimiter(max_rate, time_period)
return self.limiter_map[name]


SYNC_RATE_LIMITER_MANAGER = SyncRateLimiterManager()
6 changes: 5 additions & 1 deletion kag/interface/common/llm_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
from tenacity import retry, stop_after_attempt, wait_exponential
from kag.interface import PromptABC
from kag.common.registry import Registrable
from kag.common.rate_limiter import RATE_LIMITER_MANGER
from kag.common.rate_limiter import RATE_LIMITER_MANGER, SYNC_RATE_LIMITER_MANAGER
from kag.common.conf import KAGConstants, KAGConfigAccessor

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -170,6 +170,9 @@ def __init__(
):
super().__init__(**kwargs)
self.limiter = RATE_LIMITER_MANGER.get_rate_limiter(name, max_rate, time_period)
self.sync_limiter = SYNC_RATE_LIMITER_MANAGER.get_rate_limiter(
name, max_rate, time_period
)
self.enable_check = kwargs.get("enable_check", True)
self.max_tokens = kwargs.get("max_tokens", 8192)
task_id = kwargs.get(KAGConstants.KAG_QA_TASK_CONFIG_KEY, None)
Expand Down Expand Up @@ -324,6 +327,7 @@ def invoke(
if tools:
with_json_parse = False
try:
self.sync_limiter.acquire()
response = (
self.call_with_json_parse(prompt=prompt, **kwargs)
if with_json_parse
Expand Down
52 changes: 39 additions & 13 deletions kag/solver/executor/retriever/kag_hybrid_retrieval_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,11 @@
from typing import List, Optional
from concurrent.futures import ThreadPoolExecutor
from functools import partial

from tenacity import stop_after_attempt, retry, wait_exponential

from kag.common.conf import KAGConstants, KAGConfigAccessor
from kag.common.config import get_default_chat_llm_config, LogicFormConfiguration
from kag.common.config import get_default_chat_llm_config
from kag.common.parser.logic_node_parser import GetSPONode
from kag.interface import (
ExecutorABC,
Expand Down Expand Up @@ -74,6 +77,10 @@ def __init__(
{"type": "context_select_prompt"}
)

@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1))
def context_select_call(self, variables):
return self.context_select_llm.invoke(variables, self.context_select_prompt)

def context_select(self, query: str, sorted_chunks):
chunks = []
for idx, item in enumerate(sorted_chunks):
Expand All @@ -89,6 +96,24 @@ def context_select(self, query: str, sorted_chunks):
indices.append(i)
return [sorted_chunks[x] for x in indices]

@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1))
def summary_answer(
self, tag_id, task_query, deps_context, formatted_docs, **kwargs
):
return self.llm_module.invoke(
{
"cur_question": task_query,
"questions": "\n\n".join(deps_context),
"docs": "\n\n".join(formatted_docs),
},
self.summary_prompt,
with_json_parse=False,
with_except=True,
segment_name=tag_id,
tag_name=f"begin_summary_{task_query}",
**kwargs,
)

def do_retrieval(
self, task_query, tag_id, task, context: Context, **kwargs
) -> RetrieverOutput:
Expand Down Expand Up @@ -216,23 +241,24 @@ def do_summary(
selected_rel = list(set(selected_rel))
formatted_docs = [str(rel) for rel in selected_rel]
if retrieved_data.chunks:
selected_chunks = self.context_select(task_query, retrieved_data.chunks)
try:
selected_chunks = self.context_select(task_query, retrieved_data.chunks)
except Exception as e:
logger.warning(
f"select context failed {e}, we use default top 10 to summary",
exc_info=True,
)
selected_chunks = retrieved_data.chunks[:10]
for doc in selected_chunks:
formatted_docs.append(f"{doc.content}")

deps_context = format_task_dep_context(task.parents)
summary_start_time = time.time()
summary_response = self.llm_module.invoke(
{
"cur_question": task_query,
"questions": "\n\n".join(deps_context),
"docs": "\n\n".join(formatted_docs),
},
self.summary_prompt,
with_json_parse=False,
with_except=True,
segment_name=tag_id,
tag_name=f"begin_summary_{task_query}",
summary_response = self.summary_answer(
tag_id=tag_id,
task_query=task_query,
deps_context=deps_context,
formatted_docs=formatted_docs,
**kwargs,
)
retrieved_data.summary = summary_response
Expand Down
58 changes: 57 additions & 1 deletion kag/solver/planner/kag_model_planner.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied.
import json
from typing import List, Optional

from kag.common.parser.logic_node_parser import (
Expand All @@ -20,6 +21,7 @@
GetNode,
)
from kag.interface import PlannerABC, Task, LLMClient, PromptABC, Context
from kag.interface.solver.planner_abc import format_task_dep_context


def _get_dep_task_id(logic_forms):
Expand Down Expand Up @@ -77,6 +79,7 @@ def __init__(
llm: LLMClient,
system_prompt: PromptABC,
clarification_prompt: PromptABC,
rewrite_prompt: PromptABC,
**kwargs,
):
super().__init__(**kwargs)
Expand All @@ -85,6 +88,59 @@ def __init__(
self.logic_node_parser = ParseLogicForm(schema=None, schema_retrieval=None)
self.system_prompt = system_prompt
self.clarification_prompt = clarification_prompt
self.rewrite_prompt = rewrite_prompt

def check_require_rewrite(self, task: Task):
"""Determines if query rewriting is needed based on parameter patterns.

Args:
task (Task): Task to check for rewrite requirements

Returns:
bool: True if query contains dynamic parameter references (e.g., {{1.output}})
"""
return task.arguments.get("is_need_rewrite", False)

async def query_rewrite(self, task: Task, **kwargs):
"""Performs asynchronous query rewriting using LLM and context.

Args:
task (Task): Task containing the query to rewrite

Returns:
str: Rewritten query with resolved dynamic references
"""
query = task.arguments["query"]
tag_id = f"{query}_begin_task"
# print(f"Old query: {query}")
deps_context = format_task_dep_context(task.parents)
generate_context = {
"target question": kwargs.get("query"),
"history_qa": deps_context,
}
new_query = await self.llm.ainvoke(
{
"input": query,
"content": json.dumps(generate_context, indent=2, ensure_ascii=False),
},
self.rewrite_prompt,
segment_name=tag_id,
tag_name="Rewrite query",
with_json_parse=self.rewrite_prompt.is_json_format(),
**kwargs,
)
logic_form_node = task.arguments.get("logic_form_node", None)
if logic_form_node:
logic_form_node.sub_query = new_query
return {
"rewrite_query": new_query,
"origin_query": query,
"query": new_query,
"logic_form_node": logic_form_node,
}
# print(f"query rewrite context = {context}")
# print(f"New query: {new_query}")
return {"query": new_query}

async def ainvoke(self, query, **kwargs) -> List[Task]:
"""Asynchronously generates task plan using LLM.
Expand Down Expand Up @@ -146,7 +202,7 @@ async def ainvoke(self, query, **kwargs) -> List[Task]:
"arguments": {
"query": logic_form.sub_query,
"logic_form_node": logic_form,
"is_need_rewrite": False,
"is_need_rewrite": True if task_deps else False,
},
}
return Task.create_tasks_from_dag(tasks_dep)
24 changes: 17 additions & 7 deletions kag/solver/prompt/context_select_prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@
@PromptABC.register("context_select_prompt")
class ContextSelectPrompt(PromptABC):
template_en = """
The Question field is the user's question, and Context is a batch of articles retrieved from the knowledge base that may contain the answer to the question. Please carefully analyze the question and each context, and return up to 5 contexts that may contain the answer to the question, and answer the question. If you think all the retrieved contexts are irrelevant to the question, return an empty list and set the answer to UNKNOWN. The return format refers to the example:
The Question field is the user's question, and Context is a batch of articles retrieved from the knowledge base that may contain the answer to the question. Please carefully analyze the question and each context, and return up to 5 contexts that may contain the answer to the question, and answer the question. If you think all the retrieved contexts are irrelevant to the question, return an empty list and set the answer to UNKNOWN.
Note:
1. response must be json format, only json format, without explanation
2. The return format refers to the example:

Question:
who is the performer of Hello Love?
Expand Down Expand Up @@ -68,7 +71,10 @@ class ContextSelectPrompt(PromptABC):
"""

template_zh = """
问题字段是用户的问题,Context是从知识库中检索到的可能包含问题答案的一批文章。请仔细分析问题和每个上下文,返回最多5个可能包含问题答案的上下文,并回答问题。如果你认为所有检索到的上下文都与问题无关,请返回空列表并将答案设置为UNKNOWN。返回格式参考示例:
问题字段是用户的问题,Context是从知识库中检索到的可能包含问题答案的一批文章。请仔细分析问题和每个上下文,返回最多5个可能包含问题答案的上下文,并回答问题。如果你认为所有检索到的上下文都与问题无关,请返回空列表并将答案设置为UNKNOWN。
注意:
1、输出必须是json格式,只输出json格式内容,不需要带上解释
2、返回格式参考下面示例:

问题:
谁是《Hello Love》的演唱者?
Expand Down Expand Up @@ -127,13 +133,17 @@ def build_prompt(self, variables: Dict) -> str:
else:
return f"{self.template_en}\nQuestion:\n{question}\nContext:\n{context}"

def parse_response(self, response: str, **kwargs):
def parse_response(self, rsp: str, **kwargs):
if self.language == "zh":
if isinstance(response, str) and "答案:" in response:
response = response.split("答案:")[1]
if isinstance(rsp, str) and "答案:" in rsp:
response = rsp.split("答案:")[1]
else:
response = rsp
else:
if isinstance(response, str) and "Answer:" in response:
response = response.split("Answer:")[1]
if isinstance(rsp, str) and "Answer:" in rsp:
response = rsp.split("Answer:")[1]
else:
response = rsp
if isinstance(response, str):
response = json.loads(response)

Expand Down