1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
|
from langchain.agents import initialize_agent, AgentType from langchain_core.tools import tool from pydantic import BaseModel, Field
class AddInputArgs(BaseModel): a: int = Field(description="first number") b: int = Field(description="second number")
@tool( description="add two numbers", args_schema=AddInputArgs, return_direct=False, ) def add(a, b): """add two numbers""" return a + b
def create_calc_tools(): return [add]
calc_tools = create_calc_tools()
import os from dotenv import load_dotenv
load_dotenv()
from langchain_openai import ChatOpenAI
qv_llm = ChatOpenAI( model=os.getenv("LLM_MODEL"), base_url=os.getenv("LLM_BASE_URL"), api_key=os.getenv("LLM_API_KEY"), streaming=True, )
class Output(BaseModel): args: str = Field(description="工具的入参") result: str = Field(description="计算的结果")
from langchain_core.output_parsers import JsonOutputParser
parser = JsonOutputParser(pydantic_object=Output)
format_instruction = parser.get_format_instructions() print('--------------------------格式化输出的内容-----------------------') print(format_instruction)
agent = initialize_agent( tools=calc_tools, llm=qv_llm, agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True, )
from langchain_core.prompts import ChatPromptTemplate, ChatMessagePromptTemplate
system_message_template = ChatMessagePromptTemplate.from_template( template="你是一位{role}专家,擅长回答{domain}领域的问题", role="system", )
human_message_template = ChatMessagePromptTemplate.from_template( template="用户问题:{question}", role="user", )
chat_prompt_template = ChatPromptTemplate.from_messages([ system_message_template, human_message_template, ])
prompt = chat_prompt_template.format_messages( role="计算", domain="使用工具进行数学计算", question=f""" 请阅读下面的问题,并返回一个严格的 JSON 对象,不要使用 Markdown 代码块包裹! 格式要求: {format_instruction}
问题: 100+100=? """ )
response = agent.invoke(prompt) print("--------------------------智能体输出-----------------------") print(response) print("--------------------------output内容-----------------------") print(response['output'])
|