Spaces:
Running
Running
File size: 5,448 Bytes
78098b8 dae0ada 78098b8 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 |
import yaml
from jinja2 import Template
from textwrap import dedent
prompt_code_example = dedent("""
User: How the following repo has implemented Logging, and how can I make it compatible with Facebook Standard Logging? github url: https://github.com/askbudi/tinyagent
function_calling: run_python
run_python("task='How the following repo has implemented Logging, and how can I make it compatible with Facebook Standard Logging?'",
"repo_result = code_research(repo_url='https://github.com/askbudi/tinyagent',task='How the following repo has implemented Logging, and how can I make it compatible with Facebook Standard Logging?')",
"print(repo_result)",
"answer_for_user_review = problem_solver(task=task,context=repo_result)",
"print(answer_for_user_review)",
""")
prompt_qwen_helper = dedent("""
**Your learning from past mistakes**
- User can't directly see the response of run_python tool, so you need to use final_answer or ask_question whenever you want to show a response to the user.
Other tools calls and their responses are not visible to the user.
- run_python is a capable tool, if you need to call a function with different arguments, you can do it in one take, just like you would do in a python code you developed to be executed in one cell of Jupyter Notebook Cell.
""")
def load_template(path: str) -> str:
"""
Load the YAML file and extract its 'system_prompt' field.
"""
with open(path, "r") as f:
data = yaml.safe_load(f)
return data["system_prompt"]
def render_system_prompt(template_str: str,
tools: dict,
managed_agents: dict,
authorized_imports) -> str:
"""
Render the Jinja2 template with the given context.
"""
tmpl = Template(template_str)
return tmpl.render(
tools=tools,
managed_agents=managed_agents,
authorized_imports=authorized_imports
)
from tinyagent import tool
import asyncio
from typing import Any, Dict
import inspect
from typing import get_type_hints
def translate_tool_for_code_agent(tool_func_or_class: Any) -> Dict[str, Any]:
"""
Translate a tool decorated with @tool into a format compatible with code_agent.yaml.
Args:
tool_func_or_class: A function or class decorated with @tool
Returns:
A dictionary with the tool configuration in code_agent.yaml format
"""
def _get_type_as_string(type_hint: Any) -> str:
"""
Convert a type hint to its string representation.
Args:
type_hint: The type hint to convert
Returns:
String representation of the type
"""
if type_hint is Any:
return "Any"
# Handle common types
type_map = {
str: "str",
int: "int",
float: "float",
bool: "bool",
list: "List",
dict: "Dict",
tuple: "Tuple",
None: "None"
}
if type_hint in type_map:
return type_map[type_hint]
# Try to get the name attribute
if hasattr(type_hint, "__name__"):
return type_hint.__name__
# For generic types like List[str], Dict[str, int], etc.
return str(type_hint).replace("typing.", "")
# Check if the tool has the required metadata
if not hasattr(tool_func_or_class, '_tool_metadata'):
raise ValueError("Tool must be decorated with @tool decorator")
metadata = tool_func_or_class._tool_metadata
# Check if it's an async function
is_async = asyncio.iscoroutinefunction(tool_func_or_class)
if metadata["is_class"] and hasattr(tool_func_or_class, "__call__"):
is_async = asyncio.iscoroutinefunction(tool_func_or_class.__call__)
# Get the function signature for parameter types
if metadata["is_class"]:
func_to_inspect = tool_func_or_class.__init__
else:
func_to_inspect = tool_func_or_class
sig = inspect.signature(func_to_inspect)
type_hints = get_type_hints(func_to_inspect)
# Build inputs dictionary
inputs = {}
for name, param in sig.parameters.items():
if name in ['self', 'cls']:
continue
param_type = type_hints.get(name, Any)
param_type_str = _get_type_as_string(param_type)
# Get parameter description from schema if available
param_desc = ""
if metadata["schema"] and "properties" in metadata["schema"]:
if name in metadata["schema"]["properties"]:
param_desc = metadata["schema"]["properties"][name].get("description", "")
inputs[name] = {
"type": param_type_str,
"description": param_desc
}
# Determine output type
output_type = "Any"
if "return" in type_hints:
output_type = _get_type_as_string(type_hints["return"])
# Create the tool config
tool_config = {
"name": metadata["name"],
"description": metadata["description"],
"inputs": inputs,
"output_type": output_type,
"is_async": is_async
}
return tool_config
|