Skip to main content

Code writing

Example of how to use LCEL to write Python code.

%pip install --upgrade --quiet  langchain-core langchain-experimental langchain-openai
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import (
from langchain_experimental.utilities import PythonREPL
from langchain_openai import ChatOpenAI
template = """Write some python code to solve the user's problem. 

Return only python code in Markdown format, e.g.:

prompt = ChatPromptTemplate.from_messages([("system", template), ("human", "{input}")])

model = ChatOpenAI()
def _sanitize_output(text: str):
_, after = text.split("```python")
return after.split("```")[0]
chain = prompt | model | StrOutputParser() | _sanitize_output | PythonREPL().run
chain.invoke({"input": "whats 2 plus 2"})
Python REPL can execute arbitrary code. Use with caution.

Help us out by providing feedback on this documentation page: