tinyagent-py 0.0.7__py3-none-any.whl → 0.0.8__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tinyagent/hooks/gradio_callback.py +210 -35
- {tinyagent_py-0.0.7.dist-info → tinyagent_py-0.0.8.dist-info}/METADATA +1 -1
- {tinyagent_py-0.0.7.dist-info → tinyagent_py-0.0.8.dist-info}/RECORD +6 -6
- {tinyagent_py-0.0.7.dist-info → tinyagent_py-0.0.8.dist-info}/WHEEL +0 -0
- {tinyagent_py-0.0.7.dist-info → tinyagent_py-0.0.8.dist-info}/licenses/LICENSE +0 -0
- {tinyagent_py-0.0.7.dist-info → tinyagent_py-0.0.8.dist-info}/top_level.txt +0 -0
@@ -157,7 +157,7 @@ class GradioCallback:
|
|
157
157
|
|
158
158
|
# Add to detailed tool call info if not already present by ID
|
159
159
|
if not any(tc['id'] == tool_id for tc in self.tool_call_details):
|
160
|
-
|
160
|
+
tool_detail = {
|
161
161
|
"id": tool_id,
|
162
162
|
"name": tool_name,
|
163
163
|
"arguments": formatted_args,
|
@@ -166,7 +166,25 @@ class GradioCallback:
|
|
166
166
|
"result_token_count": 0,
|
167
167
|
"timestamp": current_time,
|
168
168
|
"result_timestamp": None
|
169
|
-
}
|
169
|
+
}
|
170
|
+
|
171
|
+
# Special handling for run_python tool - extract code_lines
|
172
|
+
if tool_name == "run_python":
|
173
|
+
try:
|
174
|
+
# Look for code in different possible field names
|
175
|
+
code_content = None
|
176
|
+
for field in ['code_lines', 'code', 'script', 'python_code']:
|
177
|
+
if field in parsed_args:
|
178
|
+
code_content = parsed_args[field]
|
179
|
+
break
|
180
|
+
|
181
|
+
if code_content is not None:
|
182
|
+
tool_detail["code_lines"] = code_content
|
183
|
+
self.logger.debug(f"Stored code content for run_python tool {tool_id}")
|
184
|
+
except Exception as e:
|
185
|
+
self.logger.error(f"Error processing run_python arguments: {e}")
|
186
|
+
|
187
|
+
self.tool_call_details.append(tool_detail)
|
170
188
|
self.logger.debug(f"Added tool call detail: {tool_name} (ID: {tool_id}, Tokens: {token_count})")
|
171
189
|
|
172
190
|
# If this is a final_answer or ask_question tool, we'll handle it specially later
|
@@ -386,19 +404,127 @@ class GradioCallback:
|
|
386
404
|
f"O {self.token_usage['completion_tokens']} | " +
|
387
405
|
f"Total {self.token_usage['total_tokens']}")
|
388
406
|
|
407
|
+
def _format_run_python_tool(self, tool_detail: dict) -> str:
|
408
|
+
"""
|
409
|
+
Format run_python tool call with proper markdown formatting for code and output.
|
410
|
+
|
411
|
+
Args:
|
412
|
+
tool_detail: Tool call detail dictionary
|
413
|
+
|
414
|
+
Returns:
|
415
|
+
Formatted markdown string
|
416
|
+
"""
|
417
|
+
tool_name = tool_detail["name"]
|
418
|
+
tool_id = tool_detail.get("id", "unknown")
|
419
|
+
code_lines = tool_detail.get("code_lines", [])
|
420
|
+
result = tool_detail.get("result")
|
421
|
+
input_tokens = tool_detail.get("token_count", 0)
|
422
|
+
output_tokens = tool_detail.get("result_token_count", 0)
|
423
|
+
total_tokens = input_tokens + output_tokens
|
424
|
+
|
425
|
+
# Start building the formatted content
|
426
|
+
parts = []
|
427
|
+
|
428
|
+
# Handle different code_lines formats
|
429
|
+
combined_code = ""
|
430
|
+
if code_lines:
|
431
|
+
if isinstance(code_lines, list):
|
432
|
+
# Standard case: list of code lines
|
433
|
+
combined_code = "\n".join(code_lines)
|
434
|
+
elif isinstance(code_lines, str):
|
435
|
+
# Handle case where code_lines is a single string
|
436
|
+
combined_code = code_lines
|
437
|
+
else:
|
438
|
+
# Convert other types to string
|
439
|
+
combined_code = str(code_lines)
|
440
|
+
|
441
|
+
# If we have code content, show it as Python code block
|
442
|
+
if combined_code.strip():
|
443
|
+
parts.append(f"**Python Code:**\n```python\n{combined_code}\n```")
|
444
|
+
else:
|
445
|
+
# Try to extract code from arguments as fallback
|
446
|
+
try:
|
447
|
+
args_dict = json.loads(tool_detail['arguments'])
|
448
|
+
# Check for different possible code field names
|
449
|
+
code_content = None
|
450
|
+
for field in ['code_lines', 'code', 'script', 'python_code']:
|
451
|
+
if field in args_dict:
|
452
|
+
code_content = args_dict[field]
|
453
|
+
break
|
454
|
+
|
455
|
+
if code_content:
|
456
|
+
if isinstance(code_content, list):
|
457
|
+
combined_code = "\n".join(code_content)
|
458
|
+
else:
|
459
|
+
combined_code = str(code_content)
|
460
|
+
|
461
|
+
if combined_code.strip():
|
462
|
+
parts.append(f"**Python Code:**\n```python\n{combined_code}\n```")
|
463
|
+
else:
|
464
|
+
# Final fallback to showing raw arguments
|
465
|
+
parts.append(f"**Input Arguments:**\n```json\n{tool_detail['arguments']}\n```")
|
466
|
+
else:
|
467
|
+
# No code found, show raw arguments
|
468
|
+
parts.append(f"**Input Arguments:**\n```json\n{tool_detail['arguments']}\n```")
|
469
|
+
except (json.JSONDecodeError, KeyError):
|
470
|
+
# If we can't parse arguments, show them as-is
|
471
|
+
parts.append(f"**Input Arguments:**\n```json\n{tool_detail['arguments']}\n```")
|
472
|
+
|
473
|
+
# Add the output if available
|
474
|
+
if result is not None:
|
475
|
+
parts.append(f"\n**Output:** ({output_tokens} tokens)")
|
476
|
+
|
477
|
+
try:
|
478
|
+
# Try to parse result as JSON for better formatting
|
479
|
+
result_json = json.loads(result)
|
480
|
+
parts.append(f"```json\n{json.dumps(result_json, indent=2)}\n```")
|
481
|
+
except (json.JSONDecodeError, TypeError):
|
482
|
+
# Handle plain text result
|
483
|
+
if isinstance(result, str):
|
484
|
+
# Replace escaped newlines with actual newlines for better readability
|
485
|
+
formatted_result = result.replace("\\n", "\n")
|
486
|
+
parts.append(f"```\n{formatted_result}\n```")
|
487
|
+
else:
|
488
|
+
parts.append(f"```\n{str(result)}\n```")
|
489
|
+
else:
|
490
|
+
parts.append(f"\n**Status:** ⏳ Processing...")
|
491
|
+
|
492
|
+
# Add token information
|
493
|
+
parts.append(f"\n**Token Usage:** {total_tokens} total ({input_tokens} input + {output_tokens} output)")
|
494
|
+
|
495
|
+
return "\n".join(parts)
|
496
|
+
|
389
497
|
async def interact_with_agent(self, user_input_processed, chatbot_history):
|
390
498
|
"""
|
391
499
|
Process user input, interact with the agent, and stream updates to Gradio UI.
|
392
500
|
Each tool call and response will be shown as a separate message.
|
393
501
|
"""
|
394
502
|
self.logger.info(f"Starting interaction for: {user_input_processed[:50]}...")
|
503
|
+
|
504
|
+
# Reset state for new interaction to prevent showing previous content
|
505
|
+
self.thinking_content = ""
|
506
|
+
self.tool_calls = []
|
507
|
+
self.tool_call_details = []
|
508
|
+
self.assistant_text_responses = []
|
509
|
+
self.token_usage = {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}
|
510
|
+
self.is_running = True
|
511
|
+
self.last_update_yield_time = 0
|
512
|
+
self.logger.debug("Reset interaction state for new conversation turn")
|
395
513
|
|
396
514
|
# 1. Add user message to chatbot history as a ChatMessage
|
397
515
|
chatbot_history.append(
|
398
516
|
ChatMessage(role="user", content=user_input_processed)
|
399
517
|
)
|
400
518
|
|
401
|
-
#
|
519
|
+
# 2. Add typing indicator immediately after user message
|
520
|
+
typing_message = ChatMessage(
|
521
|
+
role="assistant",
|
522
|
+
content="🤔 Thinking..."
|
523
|
+
)
|
524
|
+
chatbot_history.append(typing_message)
|
525
|
+
typing_message_index = len(chatbot_history) - 1
|
526
|
+
|
527
|
+
# Initial yield to show user message and typing indicator
|
402
528
|
yield chatbot_history, self._get_token_usage_text()
|
403
529
|
|
404
530
|
# Kick off the agent in the background
|
@@ -407,7 +533,7 @@ class GradioCallback:
|
|
407
533
|
|
408
534
|
displayed_tool_calls = set()
|
409
535
|
displayed_text_responses = set()
|
410
|
-
|
536
|
+
thinking_removed = False
|
411
537
|
update_interval = 0.3
|
412
538
|
min_yield_interval = 0.2
|
413
539
|
|
@@ -420,6 +546,14 @@ class GradioCallback:
|
|
420
546
|
sorted_tool_details = sorted(self.tool_call_details, key=lambda x: x.get("timestamp", 0))
|
421
547
|
sorted_text_responses = sorted(self.assistant_text_responses, key=lambda x: x.get("timestamp", 0))
|
422
548
|
|
549
|
+
# Remove typing indicator once we have actual content to show
|
550
|
+
if not thinking_removed and (sorted_text_responses or sorted_tool_details):
|
551
|
+
# Remove the typing indicator
|
552
|
+
if typing_message_index < len(chatbot_history):
|
553
|
+
chatbot_history.pop(typing_message_index)
|
554
|
+
thinking_removed = True
|
555
|
+
self.logger.debug("Removed typing indicator")
|
556
|
+
|
423
557
|
# → New assistant text chunks
|
424
558
|
for resp in sorted_text_responses:
|
425
559
|
content = resp["content"]
|
@@ -430,22 +564,6 @@ class GradioCallback:
|
|
430
564
|
displayed_text_responses.add(content)
|
431
565
|
self.logger.debug(f"Added new text response: {content[:50]}...")
|
432
566
|
|
433
|
-
# → Thinking placeholder (optional)
|
434
|
-
if self.show_thinking and self.thinking_content \
|
435
|
-
and not thinking_message_added \
|
436
|
-
and not displayed_text_responses:
|
437
|
-
thinking_msg = (
|
438
|
-
"Working on it...\n\n"
|
439
|
-
"```"
|
440
|
-
f"{self.thinking_content}"
|
441
|
-
"```"
|
442
|
-
)
|
443
|
-
chatbot_history.append(
|
444
|
-
ChatMessage(role="assistant", content=thinking_msg)
|
445
|
-
)
|
446
|
-
thinking_message_added = True
|
447
|
-
self.logger.debug("Added thinking message")
|
448
|
-
|
449
567
|
# → Show tool calls with "working..." status when they start
|
450
568
|
if self.show_tool_calls:
|
451
569
|
for tool in sorted_tool_details:
|
@@ -455,11 +573,18 @@ class GradioCallback:
|
|
455
573
|
# If we haven't displayed this tool call yet
|
456
574
|
if tid not in displayed_tool_calls and tid not in in_progress_tool_calls:
|
457
575
|
in_tok = tool.get("token_count", 0)
|
576
|
+
|
458
577
|
# Create "working..." message for this tool call
|
459
|
-
|
460
|
-
|
461
|
-
|
462
|
-
|
578
|
+
if tname == "run_python":
|
579
|
+
# Special formatting for run_python
|
580
|
+
body = self._format_run_python_tool(tool)
|
581
|
+
else:
|
582
|
+
# Standard formatting for other tools
|
583
|
+
body = (
|
584
|
+
f"**Input Arguments:**\n```json\n{tool['arguments']}\n```\n\n"
|
585
|
+
f"**Output:** ⏳ Working...\n"
|
586
|
+
)
|
587
|
+
|
463
588
|
# Add to chatbot with "working" status
|
464
589
|
msg = ChatMessage(
|
465
590
|
role="assistant",
|
@@ -483,10 +608,16 @@ class GradioCallback:
|
|
483
608
|
tot_tok = in_tok + out_tok
|
484
609
|
|
485
610
|
# Update the message with completed status and result
|
486
|
-
|
487
|
-
|
488
|
-
|
489
|
-
|
611
|
+
if tname == "run_python":
|
612
|
+
# Special formatting for completed run_python
|
613
|
+
body = self._format_run_python_tool(tool)
|
614
|
+
else:
|
615
|
+
# Standard formatting for other completed tools
|
616
|
+
body = (
|
617
|
+
f"**Input Arguments:**\n```json\n{tool['arguments']}\n```\n\n"
|
618
|
+
f"**Output:** ({out_tok} tokens)\n```json\n{tool['result']}\n```\n"
|
619
|
+
)
|
620
|
+
|
490
621
|
# Update the existing message
|
491
622
|
chatbot_history[pos] = ChatMessage(
|
492
623
|
role="assistant",
|
@@ -508,6 +639,11 @@ class GradioCallback:
|
|
508
639
|
|
509
640
|
await asyncio.sleep(update_interval)
|
510
641
|
|
642
|
+
# Remove typing indicator if still present when agent finishes
|
643
|
+
if not thinking_removed and typing_message_index < len(chatbot_history):
|
644
|
+
chatbot_history.pop(typing_message_index)
|
645
|
+
self.logger.debug("Removed typing indicator at end")
|
646
|
+
|
511
647
|
# once the agent_task is done, add its final result if any
|
512
648
|
try:
|
513
649
|
final_text = await agent_task
|
@@ -772,8 +908,8 @@ class GradioCallback:
|
|
772
908
|
return app
|
773
909
|
|
774
910
|
def clear_conversation(self):
|
775
|
-
"""Clear the conversation history (UI + agent), reset state, and update UI."""
|
776
|
-
self.logger.debug("Clearing conversation (UI + agent)")
|
911
|
+
"""Clear the conversation history (UI + agent), reset state completely, and update UI."""
|
912
|
+
self.logger.debug("Clearing conversation completely (UI + agent with new session)")
|
777
913
|
# Reset UI‐side state
|
778
914
|
self.thinking_content = ""
|
779
915
|
self.tool_calls = []
|
@@ -782,13 +918,52 @@ class GradioCallback:
|
|
782
918
|
self.token_usage = {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}
|
783
919
|
self.is_running = False
|
784
920
|
|
785
|
-
#
|
921
|
+
# Completely reset the agent state with a new session
|
786
922
|
try:
|
787
|
-
if self.current_agent
|
788
|
-
|
789
|
-
|
923
|
+
if self.current_agent:
|
924
|
+
# Generate a new session ID for a fresh start
|
925
|
+
import uuid
|
926
|
+
new_session_id = str(uuid.uuid4())
|
927
|
+
self.current_agent.session_id = new_session_id
|
928
|
+
self.logger.debug(f"Generated new session ID: {new_session_id}")
|
929
|
+
|
930
|
+
# Reset all agent state
|
931
|
+
# 1. Clear conversation history (preserve system message)
|
932
|
+
if self.current_agent.messages:
|
933
|
+
system_msg = self.current_agent.messages[0]
|
934
|
+
self.current_agent.messages = [system_msg]
|
935
|
+
else:
|
936
|
+
# Rebuild default system prompt if missing
|
937
|
+
default_system_prompt = (
|
938
|
+
"You are a helpful AI assistant with access to a variety of tools. "
|
939
|
+
"Use the tools when appropriate to accomplish tasks. "
|
940
|
+
"If a tool you need isn't available, just say so."
|
941
|
+
)
|
942
|
+
self.current_agent.messages = [{
|
943
|
+
"role": "system",
|
944
|
+
"content": default_system_prompt
|
945
|
+
}]
|
946
|
+
|
947
|
+
# 2. Reset session state
|
948
|
+
self.current_agent.session_state = {}
|
949
|
+
|
950
|
+
# 3. Reset token usage in metadata
|
951
|
+
if hasattr(self.current_agent, 'metadata') and 'usage' in self.current_agent.metadata:
|
952
|
+
self.current_agent.metadata['usage'] = {
|
953
|
+
"prompt_tokens": 0,
|
954
|
+
"completion_tokens": 0,
|
955
|
+
"total_tokens": 0
|
956
|
+
}
|
957
|
+
|
958
|
+
# 4. Reset any other accumulated state that might affect behavior
|
959
|
+
self.current_agent.is_running = False
|
960
|
+
|
961
|
+
# 5. Reset session load flag to prevent any deferred loading of old session
|
962
|
+
self.current_agent._needs_session_load = False
|
963
|
+
|
964
|
+
self.logger.info(f"Completely reset TinyAgent with new session: {new_session_id}")
|
790
965
|
except Exception as e:
|
791
|
-
self.logger.error(f"Failed to
|
966
|
+
self.logger.error(f"Failed to reset TinyAgent completely: {e}")
|
792
967
|
|
793
968
|
# Return cleared UI components: empty chat + fresh token usage
|
794
969
|
return [], self._get_token_usage_text()
|
@@ -3,7 +3,7 @@ tinyagent/mcp_client.py,sha256=9dmLtJ8CTwKWKTH6K9z8CaCQuaicOH9ifAuNyX7Kdo0,6030
|
|
3
3
|
tinyagent/memory_manager.py,sha256=tAaZZdxBJ235wJIyr04n3f2Damok4s2UXunTtur_p-4,44916
|
4
4
|
tinyagent/tiny_agent.py,sha256=_qHQc2yroSI1Ihn5Ex3FH_ml7aaSNC9-yR540C16Cxs,41125
|
5
5
|
tinyagent/hooks/__init__.py,sha256=UztCHjoqF5JyDolbWwkBsBZkWguDQg23l2GD_zMHt-s,178
|
6
|
-
tinyagent/hooks/gradio_callback.py,sha256=
|
6
|
+
tinyagent/hooks/gradio_callback.py,sha256=TS28i4UUIEWsl_e75tRXyVTOKzH7at8nmIl8d3ZTYag,53493
|
7
7
|
tinyagent/hooks/logging_manager.py,sha256=UpdmpQ7HRPyer-jrmQSXcBwi409tV9LnGvXSHjTcYTI,7935
|
8
8
|
tinyagent/hooks/rich_code_ui_callback.py,sha256=PLcu5MOSoP4oZR3BtvcV9DquxcIT_d0WzSlkvaDcGOk,19820
|
9
9
|
tinyagent/hooks/rich_ui_callback.py,sha256=5iCNOiJmhc1lOL7ZjaOt5Sk3rompko4zu_pAxfTVgJQ,22897
|
@@ -13,8 +13,8 @@ tinyagent/storage/json_file_storage.py,sha256=SYD8lvTHu2-FEHm1tZmsrcgEOirBrlUsUM
|
|
13
13
|
tinyagent/storage/postgres_storage.py,sha256=IGwan8UXHNnTZFK1F8x4kvMDex3GAAGWUg9ePx_5IF4,9018
|
14
14
|
tinyagent/storage/redis_storage.py,sha256=hu3y7wHi49HkpiR-AW7cWVQuTVOUk1WaB8TEPGUKVJ8,1742
|
15
15
|
tinyagent/storage/sqlite_storage.py,sha256=ZyOYe0d_oHO1wOIT8FxKIbc67tP_0e_8FnM2Zq8Pwj8,5915
|
16
|
-
tinyagent_py-0.0.
|
17
|
-
tinyagent_py-0.0.
|
18
|
-
tinyagent_py-0.0.
|
19
|
-
tinyagent_py-0.0.
|
20
|
-
tinyagent_py-0.0.
|
16
|
+
tinyagent_py-0.0.8.dist-info/licenses/LICENSE,sha256=YIogcVQnknaaE4K-oaQylFWo8JGRBWnwmGb3fWB_Pww,1064
|
17
|
+
tinyagent_py-0.0.8.dist-info/METADATA,sha256=NW-v0Ra2BWiKlI26hYma4lMaHxegGfkFwlR-2C04Qmg,9094
|
18
|
+
tinyagent_py-0.0.8.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
19
|
+
tinyagent_py-0.0.8.dist-info/top_level.txt,sha256=Ny8aJNchZpc2Vvhp3306L5vjceJakvFxBk-UjjVeA_I,10
|
20
|
+
tinyagent_py-0.0.8.dist-info/RECORD,,
|
File without changes
|
File without changes
|
File without changes
|