代码编写
使用LCEL编写Python代码的示例。
%pip install --upgrade --quiet langchain-core langchain-experimental langchain-openai
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import (
ChatPromptTemplate,
)
from langchain_experimental.utilities import PythonREPL
from langchain_openai import ChatOpenAI
template = """编写一些Python代码来解决用户的问题。
只返回Markdown格式的Python代码,例如:
```python
....
```"""
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": "2加2等于多少"})
Python REPL可以执行任意代码。请谨慎使用。
'4\n'