Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

code.py 4.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. #
  2. # Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import base64
  17. from abc import ABC
  18. from enum import Enum
  19. from typing import Optional
  20. from pydantic import BaseModel, Field, field_validator
  21. from agent.component.base import ComponentBase, ComponentParamBase
  22. from api import settings
  23. class Language(str, Enum):
  24. PYTHON = "python"
  25. NODEJS = "nodejs"
  26. class CodeExecutionRequest(BaseModel):
  27. code_b64: str = Field(..., description="Base64 encoded code string")
  28. language: Language = Field(default=Language.PYTHON, description="Programming language")
  29. arguments: Optional[dict] = Field(default={}, description="Arguments")
  30. @field_validator("code_b64")
  31. @classmethod
  32. def validate_base64(cls, v: str) -> str:
  33. try:
  34. base64.b64decode(v, validate=True)
  35. return v
  36. except Exception as e:
  37. raise ValueError(f"Invalid base64 encoding: {str(e)}")
  38. @field_validator("language", mode="before")
  39. @classmethod
  40. def normalize_language(cls, v) -> str:
  41. if isinstance(v, str):
  42. low = v.lower()
  43. if low in ("python", "python3"):
  44. return "python"
  45. elif low in ("javascript", "nodejs"):
  46. return "nodejs"
  47. raise ValueError(f"Unsupported language: {v}")
  48. class CodeParam(ComponentParamBase):
  49. """
  50. Define the code sandbox component parameters.
  51. """
  52. def __init__(self):
  53. super().__init__()
  54. self.lang = "python"
  55. self.script = ""
  56. self.arguments = []
  57. self.address = f"http://{settings.SANDBOX_HOST}:9385/run"
  58. self.enable_network = True
  59. def check(self):
  60. self.check_valid_value(self.lang, "Support languages", ["python", "python3", "nodejs", "javascript"])
  61. self.check_defined_type(self.enable_network, "Enable network", ["bool"])
  62. class Code(ComponentBase, ABC):
  63. component_name = "Code"
  64. def _run(self, history, **kwargs):
  65. arguments = {}
  66. for input in self._param.arguments:
  67. assert "@" in input["component_id"], "Each code argument should bind to a specific compontent"
  68. component_id = input["component_id"].split("@")[0]
  69. refered_component_key = input["component_id"].split("@")[1]
  70. refered_component = self._canvas.get_component(component_id)["obj"]
  71. for param in refered_component._param.query:
  72. if param["key"] == refered_component_key:
  73. if "value" in param:
  74. arguments[input["name"]] = param["value"]
  75. return self._execute_code(
  76. language=self._param.lang,
  77. code=self._param.script,
  78. arguments=arguments,
  79. address=self._param.address,
  80. enable_network=self._param.enable_network,
  81. )
  82. def _execute_code(self, language: str, code: str, arguments: dict, address: str, enable_network: bool):
  83. import requests
  84. try:
  85. code_b64 = self._encode_code(code)
  86. code_req = CodeExecutionRequest(code_b64=code_b64, language=language, arguments=arguments).model_dump()
  87. except Exception as e:
  88. return Code.be_output("**Error**: construct code request error: " + str(e))
  89. try:
  90. resp = requests.post(url=address, json=code_req, timeout=10)
  91. body = resp.json()
  92. if body:
  93. stdout = body.get("stdout")
  94. stderr = body.get("stderr")
  95. return Code.be_output(stdout or stderr)
  96. else:
  97. return Code.be_output("**Error**: There is no response from sanbox")
  98. except Exception as e:
  99. return Code.be_output("**Error**: Internal error in sanbox: " + str(e))
  100. def _encode_code(self, code: str) -> str:
  101. return base64.b64encode(code.encode("utf-8")).decode("utf-8")
  102. def get_input_elements(self):
  103. elements = []
  104. for input in self._param.arguments:
  105. cpn_id = input["component_id"]
  106. elements.append({"key": cpn_id, "name": input["name"]})
  107. return elements