forked from Archives/langchain
combine python files (#256)
parent
98fb19b535
commit
f5c665a544
@ -1,51 +0,0 @@
|
||||
"""Chain that runs python code.
|
||||
|
||||
Heavily borrowed from https://replit.com/@amasad/gptpy?v=1#main.py
|
||||
"""
|
||||
import sys
|
||||
from io import StringIO
|
||||
from typing import Dict, List
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from langchain.chains.base import Chain
|
||||
from langchain.python import PythonREPL
|
||||
|
||||
|
||||
class PythonChain(Chain, BaseModel):
|
||||
"""Chain to run python code.
|
||||
|
||||
Example:
|
||||
.. code-block:: python
|
||||
|
||||
from langchain import PythonChain
|
||||
python_chain = PythonChain()
|
||||
"""
|
||||
|
||||
input_key: str = "code" #: :meta private:
|
||||
output_key: str = "output" #: :meta private:
|
||||
|
||||
@property
|
||||
def input_keys(self) -> List[str]:
|
||||
"""Expect input key.
|
||||
|
||||
:meta private:
|
||||
"""
|
||||
return [self.input_key]
|
||||
|
||||
@property
|
||||
def output_keys(self) -> List[str]:
|
||||
"""Return output key.
|
||||
|
||||
:meta private:
|
||||
"""
|
||||
return [self.output_key]
|
||||
|
||||
def _call(self, inputs: Dict[str, str]) -> Dict[str, str]:
|
||||
python_repl = PythonREPL()
|
||||
old_stdout = sys.stdout
|
||||
sys.stdout = mystdout = StringIO()
|
||||
python_repl.run(inputs[self.input_key])
|
||||
sys.stdout = old_stdout
|
||||
output = mystdout.getvalue()
|
||||
return {self.output_key: output}
|
@ -1,15 +0,0 @@
|
||||
"""Test python chain."""
|
||||
|
||||
from langchain.chains.python import PythonChain
|
||||
|
||||
|
||||
def test_functionality() -> None:
|
||||
"""Test correct functionality."""
|
||||
chain = PythonChain(input_key="code1", output_key="output1")
|
||||
code = "print(1 + 1)"
|
||||
output = chain({"code1": code})
|
||||
assert output == {"code1": code, "output1": "2\n"}
|
||||
|
||||
# Test with the more user-friendly interface.
|
||||
simple_output = chain.run(code)
|
||||
assert simple_output == "2\n"
|
Loading…
Reference in New Issue