AstrBot
AstrBot copied to clipboard
[Bug] Inline tool handler drops schema-valid order quantities outside top-level properties
Description
The quote tool receives an empty order even though the agent calls it with the requested quantity.
I was using Context.tool_loop_agent to get a quote for 12 cartons of paper from a supplier CSV. At $4 per carton, I expected a $48 quote. The agent sends the correct quantity in its tool call, but the tool receives no items and returns 0 cartons and $0. The assistant reports that zero quote and warns that it does not cover my order.
Expected behavior
The schema-valid paper quantity12 should reach the registered handler unchanged. The tool should quote the requested quantity, rather than receive an empty order.
Reproduction Steps
- Setup LLM model, here I was using deepseek-v4.1-flash
- Run the following python code:
import asyncio
import csv
import json
import os
import tempfile
from pathlib import Path
for key in ('HTTP_PROXY','HTTPS_PROXY','ALL_PROXY','http_proxy','https_proxy','all_proxy'):
os.environ.pop(key, None)
os.environ['ASTRBOT_ROOT'] = tempfile.mkdtemp(prefix='astrbot-quote-')
from astrbot.api.agents import PlainInput
from astrbot.core import astrbot_config, db_helper
from astrbot.core.agent.tool import FunctionTool, ToolSet
from astrbot.core.astr_agent_runtime.context import AgentContextWrapper, AstrAgentContext
from astrbot.core.platform.agent_wakeup_event import AgentWakeupEvent
from astrbot.core.platform.message_session import MessageSession
from astrbot.core.config.agent import get_runtime_config_default
from astrbot.core.core_lifecycle import AstrBotCoreLifecycle
from astrbot.core.log import LogBroker
price_file = Path(os.environ['ASTRBOT_ROOT']) / 'supplier-prices.csv'
price_file.write_text('sku,usd_per_carton\npaper,4\n')
async def quote_total(event, **item_quantities):
"""Price ordered SKU quantities using the supplier CSV.
Args:
event: Native purchasing event.
**item_quantities: Carton count for each SKU.
Returns:
Serialized quoted quantity and USD total.
"""
with price_file.open() as source:
prices = {row['sku']:int(row['usd_per_carton']) for row in csv.DictReader(source)}
return json.dumps({'cartons':sum(item_quantities.values()),'total_usd':sum(prices[sku]*quantity for sku,quantity in item_quantities.items())})
async def main():
provider = {'id':'paper-quotes','enable':True,'type':'openai_chat_completion','provider_type':'chat_completion','model':'deepseek-flash','key':['${DEEPSEEK_API_KEY}'],'api_base':'https://api.deepseek.com/v1','custom_extra_body':{'temperature':0,'thinking':{'type':'disabled'}},'timeout':120}
astrbot_config['provider'] = [provider]
astrbot_config['platform'] = []
astrbot_config['provider_settings']['default_provider_id'] = provider['id']
astrbot_config['provider_settings']['proactive_capability']['add_cron_tools'] = False
config = get_runtime_config_default('astrbot')
config['model']['provider_id'] = provider['id']
config['persona'].update(system_prompt='Obtain purchase prices through quote_total. Use its returned total and quantity, since the supplier CSV is authoritative.', tools=['quote_total'], skills=[])
astrbot_config['agent'] = {'runtime':'astrbot','config':config}
astrbot_config.save_config()
core = AstrBotCoreLifecycle(LogBroker(), db_helper)
await core.initialize()
context = core.star_context
schema = {'type':'object','additionalProperties':{'type':'integer','minimum':0}}
tool = FunctionTool(name='quote_total', description='Get a supplier quote. Pass each SKU name as a JSON key and its ordered carton count as the value. For paper, the SKU key is exactly paper. Example: {"paper":2}.', parameters=schema, handler=quote_total)
umo = 'webchat:FriendMessage:paper-purchasing'
try:
prompt = 'Please obtain a supplier quote for 12 cartons of SKU paper. Call quote_total once, then report the service total in USD and its quoted carton count.'
event = AgentWakeupEvent(context=context, session=MessageSession.from_str(umo), platform_meta=context.get_platform_inst('webchat').meta(), prompt=prompt, source='plugin')
run_context = AgentContextWrapper(context=AstrAgentContext(context=context, event=event))
result = await context.tool_loop_agent(event=event, chat_provider_id=provider['id'], prompt=prompt, system_prompt='Obtain prices using quote_total and report its returned total and carton count, since the supplier CSV is authoritative.', tools=ToolSet([tool]), run_context=run_context, max_steps=5)
history = [message.model_dump() for message in run_context.messages]
print('Completed SDK quote:', result)
print('Native run context:', history)
print('Native end reason:', run_context.run_end_reason)
assert result.role == 'assistant' and run_context.run_end_reason == 'completed'
calls = [json.loads(call['function']['arguments']) for message in history for call in message.get('tool_calls',[]) if call['function']['name'] == 'quote_total']
assert {'paper':12} in calls, 'The actual provider did not reach the supported schema-valid order'
observations = [json.loads(message['content']) for message in history if message['role']=='tool']
assert any(quote['cartons']==12 and quote['total_usd']==48 for quote in observations), 'The valid order quantity was removed before quoting'
finally:
await core.stop()
asyncio.run(main())
AstrBot Version
4.29.4
Operating System
Linux
Deployment Method
Using the provided python API to build an agent in my local PC.
Message Platform Adapter
None
Error Log
/tmp/agent-framework-context-audit/astrbot/conda-env/lib/python3.12/site-packages/jieba/_compat.py:18: UserWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html. The pkg_resources package is slated for removal as early as 2025-11-30. Refrain from using this package or pin to Setuptools<81.
import pkg_resources
[07:10:56.877] [Core] [INFO] [core.core_lifecycle:154]: AstrBot v4.29.4
[07:10:57.003] [Core] [INFO] [migration.migra_token_usage:27]: 开始执行数据库迁移(添加 conversations.token_usage 列)...
[07:10:57.004] [Core] [INFO] [migration.migra_token_usage:39]: token_usage 列已存在,跳过迁移
[07:10:57.013] [Core] [INFO] [utils.migra_helper:539]: Migrating provider paper-quotes to new structure
[07:10:57.016] [Core] [INFO] [utils.migra_helper:570]: Provider-source structure migration completed
[07:10:57.026] [Core] [INFO] [core.persona_mgr:64]: Loaded 1 personas.
[07:10:57.031] [builtin_commands] [INFO] [star.star_manager:1136]: Loading plugin builtin_commands ...
[07:10:57.037] [builtin_commands] [INFO] [star.star_manager:1226]: Plugin builtin_commands (0.0.1) by Soulter: AstrBot's internal plugin, providing all built-in commands such as /reset.
[07:10:57.037] [astrbot] [INFO] [star.star_manager:1136]: Loading plugin astrbot ...
[07:10:57.039] [astrbot] [INFO] [star.star_manager:1226]: Plugin astrbot (4.4.0) by AstrBot Team: AstrBot's internal plugin, providing some basic capabilities.
[07:10:57.045] [Core] [INFO] [provider.manager:732]: Loading model openai_chat_completion(paper-quotes) ...
[07:10:57.479] [Core] [INFO] [provider.manager:837]: Selected openai_chat_completion(paper-quotes) as default chat model provider
[07:10:57.486] [Core] [INFO] [provider.func_tool_manager:595]: 未找到 MCP 服务配置文件,已创建默认配置文件 /tmp/astrbot-quote-6ncw3wfk/data/mcp_server.json
[07:10:57.504] [Core] [INFO] [knowledge_base.kb_mgr:64]: KnowledgeBase database initialized: /tmp/astrbot-quote-6ncw3wfk/data/knowledge_base/kb.db
[07:10:57.956] [Core] [INFO] [t2i.network_strategy:131]: Successfully got 2 official T2I endpoints.
[07:10:58.745] [Core] [INFO] [runners.tool_loop_agent_runner:1416]: Agent 使用工具: ['quote_total']
[07:10:58.745] [Core] [INFO] [runners.tool_loop_agent_runner:1471]: 使用工具:quote_total,参数:{'paper': 12}
[07:10:58.745] [Core] [WARN] [v4.29.4] [runners.tool_loop_agent_runner:1519]: 工具 quote_total 忽略非期望参数: {'paper'}
[07:10:58.747] [Core] [INFO] [runners.tool_loop_agent_runner:1681]: Tool `quote_total` Result: {"cartons": 0, "total_usd": 0}
Completed SDK quote: LLMResponse(role='assistant', result_chain=MessageChain(chain=[Plain(type=<ComponentType.Plain: 'Plain'>, text="Here's the result of the single `quote_total` call for 12 carton...<374 chars>")], use_t2i_=None, use_markdown_=None, type=None), tools_call_args=[], tools_call_name=[], tools_call_ids=[], tools_call_extra_content={}, reasoning_content=None, reasoning_signature=None, raw_completion=ChatCompletion(id='e1fee984-b664-4ff5-a468-828fcb4c5364', choices=[Choice(finish_reason='stop', index=0, logprobs=None, message=ChatCompletionMessage(content="Here's the result of the single `quote_total` call for 12 cartons of SKU `paper`:\n\n- **Service total:** $0.00 USD\n- **Quoted carton count:** 0\n\nNote that the returned carton count is 0, not the 12 requested, and the total is $0.00 — so this quote doesn't appear to cover the order. You may want to verify the SKU key or confirm the supplier's availability before proceeding.", refusal=None, role='assistant', annotations=None, audio=None, function_call=None, tool_calls=None))], created=1794485458, model='deepseek-flash', object='chat.completion', metadata=None, moderation=None, service_tier=None, system_fingerprint='bc19ba97cbe016479903222bb1578db6', usage=CompletionUsage(completion_tokens=101, prompt_tokens=422, total_tokens=523, completion_tokens_details=None, prompt_tokens_details=PromptTokensDetails(audio_tokens=None, cache_write_tokens=None, cached_tokens=256, image_tokens=None, text_tokens=None), prompt_cache_hit_tokens=256, prompt_cache_miss_tokens=166)), _completion_text=None, is_chunk=False, id='e1fee984-b664-4ff5-a468-828fcb4c5364', usage=TokenUsage(input_other=166, input_cached=256, output=101))
Native run context: [{'role': 'system', 'content': 'Obtain prices using quote_total and report its returned total and carton count, since the supplier CSV is authoritative.'}, {'role': 'user', 'content': 'Please obtain a supplier quote for 12 cartons of SKU paper. Call quote_total once, then report the service total in USD and its quoted carton count.'}, {'role': 'assistant', 'content': [{'type': 'text', 'text': "I'll request that quote now."}], 'tool_calls': [{'type': 'function', 'id': 'call_00_gdntBC8xIl7DKu2PclIN8230', 'function': {'name': 'quote_total', 'arguments': '{"paper": 12}'}}]}, {'role': 'tool', 'content': '{"cartons": 0, "total_usd": 0}', 'tool_call_id': 'call_00_gdntBC8xIl7DKu2PclIN8230'}, {'role': 'assistant', 'content': [{'type': 'text', 'text': "Here's the result of the single `quote_total` call for 12 cartons of SKU `paper`:\n\n- **Service total:** $0.00 USD\n- **Quoted carton count:** 0\n\nNote that the returned carton count is 0, not the 12 requested, and the total is $0.00 — so this quote doesn't appear to cover the order. You may want to verify the SKU key or confirm the supplier's availability before proceeding."}]}]
Native end reason: completed
[07:11:00.287] [Core] [INFO] [star.star_manager:1959]: Terminating plugin builtin_commands ...
[07:11:00.287] [Core] [INFO] [star.star_manager:1959]: Terminating plugin astrbot ...
[07:11:00.291] [Core] [INFO] [knowledge_base.kb_db_sqlite:173]: 知识库数据库已关闭: /tmp/astrbot-quote-6ncw3wfk/data/knowledge_base/kb.db
Traceback (most recent call last):
File "/tmp/agent-framework-context-audit/astrbot/investigation/handler-schema-projection/main.py", line 71, in <module>
asyncio.run(main())
File "/tmp/agent-framework-context-audit/astrbot/conda-env/lib/python3.12/asyncio/runners.py", line 195, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "/tmp/agent-framework-context-audit/astrbot/conda-env/lib/python3.12/asyncio/runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/agent-framework-context-audit/astrbot/conda-env/lib/python3.12/asyncio/base_events.py", line 691, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "/tmp/agent-framework-context-audit/astrbot/investigation/handler-schema-projection/main.py", line 67, in main
assert any(quote['cartons']==12 and quote['total_usd']==48 for quote in observations), 'The valid order quantity was removed before quoting'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: The valid order quantity was removed before quoting
exit_code=1
Supplementary Information
No response
Checklist
- [x] I have searched the Issue list for related issues and could not resolve the problem, or this issue has never been reported before.
- [x] I have tried disabling all plugins to rule out issues caused by plugins.
- [x] The issue I am reporting is related to AstrBot itself, not to a specific plugin.
- [x] I have read and agree to the project's Code of Conduct.
- [ ] (Optional) I am willing to submit a PR to help fix this issue.