2 篇文章带有标签 “lcel”

LangChain

介绍

LangChain 是一个用于开发由大型语言模型(LLM)支持的应用程序的框架。

LangChain 简化了 LLM 应用程序生命周期的每个阶段:

  • 开发(Development):使用 LangChain 的开源构建块和组件构建您的应用程序。使用第三方集成和模板快速启动。
  • 生产化(Productionization):使用 LangSmith 检查、监控和评估您的链,以便您可以持续优化并放心部署。
  • 部署(Deployment):使用 LangServe 将任何链转换为 API。

具体来说,该框架由以下开源库组成:

  • langchain-core: 基本抽象和 LangChain 表达语言(LangChain Expression Language)。
  • langchain-community: 第三方集成。
    • 合作伙伴包(例如 langchain-openai、langchain-anthropic 等):一些集成已进一步拆分为自己的轻量级包,这些包仅依赖于 langchain-core。
  • langchain: 构成应用程序认知架构(Cognitive Architecture)的链(Chains)、代理(Agents)和检索策略(Retrieval Strategies)。
  • langgraph: 通过将步骤建模为图中的边和节点,使用 LLM 构建强大且有状态的多参与者应用程序。
  • langserve: 将 LangChain 链部署为 REST API。

Functions, Tools and Agents with LangChain

OpenAI Function Calling (OpenAI 函数调用)

import os
import openai
import json

from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # read local .env file
openai.api_key = os.environ['OPENAI_API_KEY']


# Example dummy function hard coded to return the same weather
# In production, this could be your backend API or an external API
def get_current_weather(location, unit="fahrenheit"):
    """Get the current weather in a given location"""
    weather_info = {
        "location": location,
        "temperature": "72",
        "unit": unit,
        "forecast": ["sunny", "windy"],
    }
    return json.dumps(weather_info)

# define a function
functions = [
    {
        "name": "get_current_weather",
        "description": "Get the current weather in a given location",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "The city and state, e.g. San Francisco, CA",
                },
                "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
            },
            "required": ["location"],
        },
    }
]

messages = [
    {
        "role": "user",
        "content": "What's the weather like in Boston?"
    }
]

response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=messages,
    functions=functions
)
print(response)
{
  "id": "chatcmpl-9CK2or9rtxzcsVgbfwWmIvqi36wF0",
  "object": "chat.completion",
  "created": 1712724014,
  "model": "gpt-3.5-turbo-0125",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": null,
        "function_call": {
          "name": "get_current_weather",
          "arguments": "{\"location\":\"Boston\",\"unit\":\"celsius\"}"
        }
      },
      "logprobs": null,
      "finish_reason": "function_call"
    }
  ],
  "usage": {
    "prompt_tokens": 82,
    "completion_tokens": 20,
    "total_tokens": 102
  },
  "system_fingerprint": "fp_b28b39ffa8"
}