LangChain 63 深入理解LangChain 表达式语言26 生成代码code并执行 LangChain Expression Language (LCEL)

LangChain系列文章

  1. LangChain 36 深入理解LangChain 表达式语言优势一 LangChain Expression Language (LCEL)
  2. LangChain 37 深入理解LangChain 表达式语言二 实现prompt+model+output parser LangChain Expression Language (LCEL)
  3. LangChain 38 深入理解LangChain 表达式语言三 实现RAG检索增强生成 LangChain Expression Language (LCEL)
  4. LangChain 39 深入理解LangChain 表达式语言四 为什么要用LCEL LangChain Expression Language (LCEL)
  5. LangChain 40 实战Langchain访问OpenAI ChatGPT API Account deactivated的另类方法,访问跳板机API
  6. LangChain 41 深入理解LangChain 表达式语言五 为什么要用LCEL调用大模型LLM LangChain Expression Language (LCEL)
  7. LangChain 42 深入理解LangChain 表达式语言六 Runtime调用不同大模型LLM LangChain Expression Language (LCEL)
  8. LangChain 43 深入理解LangChain 表达式语言七 日志和Fallbacks异常备选方案 LangChain Expression Language (LCEL)
  9. LangChain 44 深入理解LangChain 表达式语言八 Runnable接口输入输出模式 LangChain Expression Language (LCEL)
  10. LangChain 45 深入理解LangChain 表达式语言九 Runnable 调用、流输出、批量调用、异步处理 LangChain Expression Language (LCEL)
  11. LangChain 46 深入理解LangChain 表达式语言十 Runnable 调用中间状态调试日志 LangChain Expression Language (LCEL)
  12. LangChain 47 深入理解LangChain 表达式语言十一 Runnable 并行处理 LangChain Expression Language (LCEL)
  13. LangChain 48 终极解决 实战Langchain访问OpenAI ChatGPT API Account deactivated的另类方法,访问跳板机API
  14. LangChain 49 深入理解LangChain 表达式语言十二 Runnable 透传数据保持输入不变 LangChain Expression Language (LCEL)
  15. LangChain 50 深入理解LangChain 表达式语言十三 自定义pipeline函数 LangChain Expression Language (LCEL)
  16. LangChain 51 深入理解LangChain 表达式语言十四 自动修复配置RunnableConfig LangChain Expression Language (LCEL)
  17. LangChain 52 深入理解LangChain 表达式语言十五 Bind runtime args绑定运行时参数 LangChain Expression Language (LCEL)
  18. LangChain 53 深入理解LangChain 表达式语言十六 Dynamically route动态路由 LangChain Expression Language (LCEL)
  19. LangChain 54 深入理解LangChain 表达式语言十七 Chains Route动态路由 LangChain Expression Language (LCEL)
  20. LangChain 55 深入理解LangChain 表达式语言十八 function Route自定义动态路由 LangChain Expression Language (LCEL)
  21. LangChain 56 深入理解LangChain 表达式语言十九 config运行时选择大模型LLM LangChain Expression Language (LCEL)
  22. LangChain 57 深入理解LangChain 表达式语言二十 LLM Fallbacks速率限制备份大模型 LangChain Expression Language (LCEL)
  23. LangChain 58 深入理解LangChain 表达式语言21 Memory消息历史 LangChain Expression Language (LCEL)
  24. LangChain 59 深入理解LangChain 表达式语言22 multiple chains多个链交互 LangChain Expression Language (LCEL)
  25. LangChain 60 深入理解LangChain 表达式语言23 multiple chains链透传参数 LangChain Expression Language (LCEL)
  26. LangChain 61 深入理解LangChain 表达式语言24 multiple chains链透传参数 LangChain Expression Language (LCEL)
  27. LangChain 62 深入理解LangChain 表达式语言25 agents代理 LangChain Expression Language (LCEL)

在这里插入图片描述

1. 生成代码Code

如何使用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

你可能感兴趣的:(LLM-Large,Language,Models,langchain,chatgpt,python,人工智能)