首页 > 其他分享 >langchain agent with tools sample code

langchain agent with tools sample code

时间:2024-11-07 22:09:01浏览次数:1  
标签:code addr image agent sample import tools email

import asyncio

from langchain_openai import ChatOpenAI
from langchain.agents import tool
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain.agents.format_scratchpad.openai_tools import (
    format_to_openai_tool_messages,
)
from langchain.agents.output_parsers.openai_tools import OpenAIToolsAgentOutputParser
from langchain.agents import AgentExecutor

from dotenv import load_dotenv
import os

from sqlalchemy import Boolean

import base64
import httpx
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import smtplib


def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, "utf-8").encode(), addr))

def _send_email(content: str):
    from_addr = "[email protected]"
    password = ""
    to_addr = "[email protected]"
    smtp_server = "smtp.gmail.com"

    msg = MIMEText(content, "plain", "utf-8")
    msg["From"] = _format_addr("FIRE ALARMER <%s>" % from_addr)
    msg["To"] = _format_addr("ADMIN <%s>" % to_addr)
    msg["Subject"] = Header("You got one fire alarm!", "utf-8").encode()
    print("---- before login 11-----")
    server = smtplib.SMTP_SSL(smtp_server, 465)
    print("---- before login 1122-----")
    server.set_debuglevel(1)
    print("---- before login -----")
    server.login(from_addr, password)
    print("---- after login -----")
    server.sendmail(from_addr, [to_addr], msg.as_string())
    server.quit()

load_dotenv()

# llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)


@tool
def get_word_length(word: str) -> int:
    """Returns the length of a word."""
    return len(word)

# print(get_word_length.invoke("abc"))


@tool
def turn_on_light() -> Boolean:
    """
    turn on light

    Return the result of turning on light.
    """
    return True

@tool
def send_one_email(content: str) -> Boolean:
    """
    send one email to admin.

    Return the result of sending one email.
    """
    _send_email(content)

    return True

tools = [get_word_length, turn_on_light, send_one_email]


prompt = ChatPromptTemplate.from_messages(
    [
        (
            "system",
            "You are very powerful assistant, but don't know current events",
        ),
        ("user", "{input}"),
        MessagesPlaceholder(variable_name="agent_scratchpad"),
    ]
)

#
#
# prompt = ChatPromptTemplate.from_messages(
#     [
#         (
#             "system",
#             "You are very powerful assistant, but don't know current events",
#         ),
#         (
#             "user",
#             [
#                 {
#                     "type": "text",
#                     "text": "{input}"
#                 },
#                 {
#                     "type": "image_url",
#                     "image_url": {"url": "data:image/jpeg;base64,{image_data}"},
#                 }
#             ],
#         ),
#         MessagesPlaceholder(variable_name="agent_scratchpad"),
#     ]
# )


llm_with_tools = llm.bind_tools(tools)

agent = (
    {
        "input": lambda x: x["input"],
        "image_data": lambda x: x['image_data'],
        "agent_scratchpad": lambda x: format_to_openai_tool_messages(
            x["intermediate_steps"]
        ),
    }
    | prompt
    | llm_with_tools
    | OpenAIToolsAgentOutputParser()
)


agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

# image_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
image_url = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQhSUzTow_Xta3T3VF8op28XCTCM4D3boxhaA3ZrNyS5xkQXEpTNvsrUhmvfkwKOb5Z7jY&usqp=CAU"
image_data = base64.b64encode(httpx.get(image_url).content).decode("utf-8")


# async def main():
#     resp = agent_executor.stream({"input": "How many letters in the word eudca"})
#     async for one in resp:
#         print(one)
#
# asyncio.run(main())


print(agent_executor.invoke({"input": "How many letters in the word eudca", "image_data": ""}))

# list(agent_executor.stream({"input": "How many letters in the word eudca"}))

# list(agent_executor.stream({"input": "Please turn on light in this room."}))

# list(agent_executor.stream({"input": '''
# Please send one email with the following text as content:
# The fire is too heavy, please take action immediately.
# '''}))

# list(agent_executor.stream({"input": "please understand this image as of fire alarm, if any fire risk then send email with that fire description, otherwise do not send alarm email.", "image_data": image_data}))

# _send_email("The fire is too heavy, please take action immediately.")

 

标签:code,addr,image,agent,sample,import,tools,email
From: https://www.cnblogs.com/lightsong/p/18534108

相关文章

  • 代码随想录算法训练营第九天|LeetCode151.翻转字符串里的单词、卡码网:55.右旋转字符串
    前言打卡代码随想录算法训练营第49期第九天︿( ̄︶ ̄)︿首先十分推荐学算法的同学可以先了解一下代码随想录,可以在B站卡哥B站账号、代码随想录官方网站代码随想录了解,卡哥清晰易懂的算法教学让我直接果断关注,也十分有缘和第49期的训练营大家庭一起进步。今日题目LeetCode151翻转字......
  • CODESYS可视化桌面屏保-动态气泡制作详细案例
    #一个用于可视化(HMI)界面的动态屏保的详细制作案例程序#前言:在工控自动化设备上,为了防止由于人为误触发或操作引起的故障,通常在触摸屏(HMI)增加屏幕保护界面,然而随着PLC偏IT化的发展,在控制界面上的美观程度也逐渐向上位机或网页前端方面发展,本篇模仿Windows系统的屏幕保护背......
  • LeetCode 1137[第N个泰波那契数]
    题目链接LeetCode1137[第N个泰波那契数]详情实例实例1实例2提示题解思路一[递归]当n为0,1,2时,直接返回对应的值当n大于2时,开始用f(n+3)=f(n)+f(n+1)+f(n+2)来递归求值代码一[此代码在力扣会超出时间限制]classSolution{public:inttrib......
  • Codeforces Global Round 27
    Preface这场其实是上周六VP的,但因为后面连着好几天组队训练就一直没补题,拖到今天才补这场VP的时候写了A~E,F感觉会了但是急着吃饭就跑了,今天写了下F发现贼好写写完就过了,亏麻了A.Sliding签到,手玩下式子即可#include<cstdio>#include<iostream>#defineintlonglon......
  • Code Block学习
      CodeBlock 可以用CodeBlock直接输入数字,字符和公式 调用内置函数我们可以在CodeBlock中直接调用内置函数。比如,在空间中创建一个点,我们可以使用Point.ByCoordinates这样的节点,该节点可以通过输入x,y两个值来确定要创建点的位置。Point.ByCoordinates(10,10)......
  • Codeforces Round 982 (Div. 2)(A~C)
    对dp还不是特别熟练只做到了C(还是太菜了),开始前刚好各种事情来了,vp晚了10多分钟开才始做题,喜提排名(不是)3000+,后面有时间就尽量把dp补掉A.RectangleArrangement你需要在一个无限的方格网格上涂色,所有格子最初都是白色的。为了完成这项任务,你有\(n\)个印章。每个印章是一个......
  • LeetCode LCR135[报数]
    题目链接LeetCodeLCR135[报数]详情实例题解思路通过pow函数对10进行幂运算,来获取报数范围然后循环遍历通过push_back方法将数字加入到容器内代码classSolution{public:vector<int>countNumbers(intcnt){vector<int>iRetVec;......
  • 【LeetCode】返回链表的中间结点、删除链表的倒数第 N 个结点
    主页:HABUO......
  • AtCoder Beginner Contest 378 ——F
    https://atcoder.jp/contests/abc378/tasks/abc378_fhttps://atcoder.jp/contests/abc378/editorial/11307#include<bits/stdc++.h>#definexfirst#defineysecond#defineall(x)(x).begin(),(x).end()#definelowbit(x)(x)&-(x)usingnamespacestd;ty......
  • 95_api_intro_websitetools_readability
    网页可读内容抽取API数据接口智能提取文章关键元素信息,智能抽取,多种元素信息。1.产品功能智能提取网页可阅读内容;提供网页可阅读内容的HTML代码;支持传递网页HTML或网页URL参数;支持多种元素信息抽取,包括文章标题、作者、文字方向、语言、内容、内容(不包含HTML标......