LangChain系列文章
如何使用LCEL编写Python代码的示例。
from langchain.prompts import PromptTemplate
from langchain_community.chat_models import ChatOpenAI
from langchain_core.runnables import ConfigurableField
# We add in a string output parser here so the outputs between the two are the same type
from langchain_core.output_parsers import StrOutputParser
from langchain.prompts import ChatPromptTemplate
from langchain.prompts import (
ChatPromptTemplate,
)
from langchain_experimental.utilities import PythonREPL
from dotenv import load_dotenv # 导入从 .env 文件加载环境变量的函数
load_dotenv() # 调用函数实际加载环境变量
from langchain.globals import set_debug # 导入在 langchain 中设置调试模式的函数
set_debug(True) # 启用 langchain 的调试模式
template = """Write some python code to solve the user's problem.
Return only python code in Markdown format, e.g.:
```python
....
```"""
prompt = ChatPromptTemplate.from_messages([("system", template), ("human", "{input}")])
model = ChatOpenAI()
def _sanitize_output(text: str):
print('text >> ', text)
_, after = text.split("```python")
return after.split("```")[0]
chain = prompt | model | StrOutputParser() | _sanitize_output | PythonREPL().run
response = chain.invoke({"input": "what is 2 plus 2"})
print('response >> ', response)
结果输出
(.venv) zgpeace@zgpeaces-MacBook-Pro git:(develop) ✗% python LCEL/code.py ~/Workspace/LLM/langchain-llm-app
[chain/start] [1:chain:RunnableSequence] Entering Chain run with input:
{
"input": "what is 2 plus 2"
}
[chain/start] [1:chain:RunnableSequence > 2:prompt:ChatPromptTemplate] Entering Prompt run with input:
{
"input": "what is 2 plus 2"
}
[chain/end] [1:chain:RunnableSequence > 2:prompt:ChatPromptTemplate] [8ms] Exiting Prompt run with output:
{
"lc": 1,
"type": "constructor",
"id": [
"langchain",
"prompts",
"chat",
"ChatPromptValue"
],
"kwargs": {
"messages": [
{
"lc": 1,
"type": "constructor",
"id": [
"langchain",
"schema",
"messages",
"SystemMessage"
],
"kwargs": {
"content": "Write some python code to solve the user's problem. \n\nReturn only python code in Markdown format, e.g.:\n\n```python\n....\n```",
"additional_kwargs": {}
}
},
{
"lc": 1,
"type": "constructor",
"id": [
"langchain",
"schema",
"messages",
"HumanMessage"
],
"kwargs": {
"content": "what is 2 plus 2",
"additional_kwargs": {}
}
}
]
}
}
[llm/start] [1:chain:RunnableSequence > 3:llm:ChatOpenAI] Entering LLM run with input:
{
"prompts": [
"System: Write some python code to solve the user's problem. \n\nReturn only python code in Markdown format, e.g.:\n\n```python\n....\n```\nHuman: what is 2 plus 2"
]
}
[llm/end] [1:chain:RunnableSequence > 3:llm:ChatOpenAI] [2.65s] Exiting LLM run with output:
{
"generations": [
[
{
"text": "```python\nresult = 2 + 2\nprint(result)\n```",
"generation_info": {
"finish_reason": "stop",
"logprobs": null
},
"type": "ChatGeneration",
"message": {
"lc": 1,
"type": "constructor",
"id": [
"langchain",
"schema",
"messages",
"AIMessage"
],
"kwargs": {
"content": "```python\nresult = 2 + 2\nprint(result)\n```",
"additional_kwargs": {}
}
}
}
]
],
"llm_output": {
"token_usage": {
"completion_tokens": 15,
"prompt_tokens": 47,
"total_tokens": 62
},
"model_name": "gpt-3.5-turbo",
"system_fingerprint": null
},
"run": null
}
[chain/start] [1:chain:RunnableSequence > 4:parser:StrOutputParser] Entering Parser run with input:
[inputs]
[chain/end] [1:chain:RunnableSequence > 4:parser:StrOutputParser] [1ms] Exiting Parser run with output:
{
"output": "```python\nresult = 2 + 2\nprint(result)\n```"
}
[chain/start] [1:chain:RunnableSequence > 5:chain:_sanitize_output] Entering Chain run with input:
{
"input": "```python\nresult = 2 + 2\nprint(result)\n```"
}
text >> `python
result = 2 + 2
print(result)
`
[chain/end] [1:chain:RunnableSequence > 5:chain:_sanitize_output] [5ms] Exiting Chain run with output:
{
"output": "\nresult = 2 + 2\nprint(result)\n"
}
[chain/start] [1:chain:RunnableSequence > 6:chain:run] Entering Chain run with input:
{
"input": "\nresult = 2 + 2\nprint(result)\n"
}
Python REPL can execute arbitrary code. Use with caution.
[chain/end] [1:chain:RunnableSequence > 6:chain:run] [66ms] Exiting Chain run with output:
{
"output": "4\n"
}
[chain/end] [1:chain:RunnableSequence] [2.76s] Exiting Chain run with output:
{
"output": "4\n"
}
response >> 4
https://github.com/zgpeace/pets-name-langchain/tree/develop
https://python.langchain.com/docs/expression_language/cookbook/code_writing