Spaces:
Sleeping
Sleeping
Add CodeExecutionTool for generating and running Python code
Browse files- tools/code_execution.py +66 -0
tools/code_execution.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Optional
|
| 2 |
+
from langchain_core.callbacks import CallbackManagerForToolRun
|
| 3 |
+
from langchain_core.tools import BaseTool
|
| 4 |
+
from langchain_core.tools.base import ArgsSchema
|
| 5 |
+
from pydantic import BaseModel, Field
|
| 6 |
+
from google.genai.types import Tool, ToolCodeExecution, GenerateContentConfig, Content, Part
|
| 7 |
+
from google import genai
|
| 8 |
+
|
| 9 |
+
class CodeExectionInput(BaseModel):
|
| 10 |
+
task: str = Field(description="The task to be executed")
|
| 11 |
+
|
| 12 |
+
class CodeExecutionTool(BaseTool):
|
| 13 |
+
name: str = "code_execution"
|
| 14 |
+
description: str = "Useful for generate and execute python code for a given task"
|
| 15 |
+
args_schema: Optional[ArgsSchema] = CodeExectionInput
|
| 16 |
+
client: Any = None
|
| 17 |
+
model_id: str = "gemini-2.0-flash"
|
| 18 |
+
return_direct: bool = False
|
| 19 |
+
code_execution_tool: Any = None
|
| 20 |
+
|
| 21 |
+
def __init__(self, api_key: Optional[str] = None, **kwargs):
|
| 22 |
+
super().__init__(**kwargs)
|
| 23 |
+
self.client = genai.Client(api_key=api_key)
|
| 24 |
+
self.code_execution_tool = Tool(code_execution=ToolCodeExecution())
|
| 25 |
+
|
| 26 |
+
def _run(self, task: str, run_manager: Optional[CallbackManagerForToolRun]=None) -> str:
|
| 27 |
+
"""Generate and execute python code for a given task"""
|
| 28 |
+
try:
|
| 29 |
+
response = self.client.models.generate_content(
|
| 30 |
+
model=self.model_id,
|
| 31 |
+
contents=f"Task: {task} "
|
| 32 |
+
"Plan on how to solve the task. Generate and run code to solve the task.",
|
| 33 |
+
config=GenerateContentConfig(
|
| 34 |
+
tools=[self.code_execution_tool],
|
| 35 |
+
response_modalities=["TEXT"]
|
| 36 |
+
)
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
result = ""
|
| 40 |
+
for part in response.candidates[0].content.parts:
|
| 41 |
+
if part.executable_code is not None:
|
| 42 |
+
result += part.executable_code.code
|
| 43 |
+
if part.code_execution_result is not None:
|
| 44 |
+
result += "\n\n" + part.code_execution_result.output
|
| 45 |
+
|
| 46 |
+
return result
|
| 47 |
+
except Exception as e:
|
| 48 |
+
return f"Error performing code execution: {str(e)}"
|
| 49 |
+
|
| 50 |
+
async def _arun(self, query: str, run_manager: Optional[CallbackManagerForToolRun]=None) -> str:
|
| 51 |
+
"""Run the code execution tool asynchronously."""
|
| 52 |
+
return self._run(query, run_manager=run_manager.get_sync())
|
| 53 |
+
|
| 54 |
+
# Example usage
|
| 55 |
+
if __name__ == "__main__":
|
| 56 |
+
from dotenv import load_dotenv
|
| 57 |
+
|
| 58 |
+
# Load API key from environment variables
|
| 59 |
+
load_dotenv()
|
| 60 |
+
|
| 61 |
+
# Create the Google Search runnable
|
| 62 |
+
code_execution = CodeExecutionTool()
|
| 63 |
+
|
| 64 |
+
# Run a search query
|
| 65 |
+
result = code_execution.invoke({"task": "What is the sum of the first 50 prime numbers?"})
|
| 66 |
+
print(result)
|