LLM代理中的输出解析为字典列表
我想从LLM代理那里获取假期及其日期,并把它们作为一个字典列表返回。下面是我用的代码:
from langchain.agents import AgentType,initialize_agent,load_tools
from langchain.prompts import ChatPromptTemplate
from langchain.output_parsers import ResponseSchema,StructuredOutputParser
from langchain_community.chat_models import ChatOpenAI
import os
tools=load_tools(["serpapi"])
llm=ChatOpenAI(model="gpt-4",temperature=0.0)
holiday=ResponseSchema(name="holiday",description="this is the name of the holiday")
date=ResponseSchema(name="holiday",description="this is the date of the holiday in datetime pattern, ex: 2024-01-01")
response_schema=[holiday, date]
output_parser=StructuredOutputParser.from_response_schemas(response_schema)
format_instruction=output_parser.get_format_instructions()
ts="""
You are an intelligent search master who can search internet using serpapi tool and retrieve the holidays in given country or region and you should find holiday and date in datetime pattern
Take the input below delimited by tripe backticks and use it to search and analyse using serapi tool
input:```{input}```
{format_instruction}
"""
prompt=ChatPromptTemplate.from_template(ts)
fs=prompt.format_messages(input="holidays in Berlin in 2024",format_instruction=format_instruction)
agent=initialize_agent(tools,llm,agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION,verbose=True, handle_parsing_errors=True)
response=agent.run(fs)
output=output_parser.parse(response)
Entering new AgentExecutor chain...
The user wants to know the holidays in Berlin in 2024. I need to search for this information and present it in a specific JSON format.
Action: Search
Action Input: holidays in Berlin in 2024
Observation: ["Berlin, Germany’s capital, dates to the 13th century. Reminders of the city's turbulent 20th-century history include its Holocaust memorial and the Berlin Wall's graffitied remains. Divided during the Cold War, its 18th-century Brandenburg Gate has become a symbol of reunification. The city's also known for its art scene and modern landmarks like the gold-colored, swoop-roofed Berliner Philharmonie, built in 1963. ― Google", 'Berlin type: Capital of Germany.', 'Berlin entity_type: cities, locations, travel, travel.', 'Berlin kgmid: /m/0156q.', 'Berlin place_id: ChIJAVkDPzdOqEcRcDteW0YgIQQ.', 'Berlin age: About 787 years.', 'Berlin founded: 1237.', 'Berlin population: 3.645 million (2019) Eurostat.', 'Berlin area_code: 030.', 'Berlin metro_population: 6,144,600.', 'Berlin mayor: Kai Wegner.', 'Berlin School Holidays & Public Holidays 2024 ; Labour Day, May 01, 2024 (Wednesday) ; Ascension Day, May 09, 2024 (Thursday) ; Whit Monday, May 20, 2024 (Monday).', 'Berlin Public Holidays 2024 ; 9 May, Thu, Ascension Day ; 20 May, Mon, Whit Monday ; 3 Oct, Thu, Day of German Unity ; 25 Dec, Wed, Christmas Day.', 'May 1, 2024 (Wednesday), Labour Day (May Day) ; May 9, 2024 (Thursday), Ascension Day ; May 20, 2024 (Monday), Whit Monday ; October 3, 2024 ( ...', "Public holidays in Berlin 2024. Public holiday, Date. New Year's Day, January 1, 2024 (Monday). International Women's Day, March 8, 2024 (Friday).", "On this page you can find the calendar of all 2024 public holidays for Berlin, Germany. New Year's DayMonday January 01, 2024. Mon January 01, 2024.", 'List of Holidays in Berlin in 2024 ; Friday, Mar 29, Good Friday ; Monday, Apr 01, Easter Monday ; Wednesday, May 01, Labour Day ; Thursday, May 09, Ascension Day ...', "Monday 1 January 2024, New Year's Day. Friday, 08 March 2024, International Women's Day / Internationaler Frauentag***. Friday, 29 March 2024, Good Friday.", 'In Berlin, the public holidays for 2024 are as follows: 1. May 1, Wednesday - Labour Day [[1](https://publicholidays.de/berlin/2024-dates/)] ...', 'The list of Berlin (Germany) public holidays in 2024 is: ; May 20, Monday, Whit Monday ; Oct 3, Thursday, German Unity Day.', "9th of November, Observance, Berlin. Nov 9, Saturday, Fall of the Berlin Wall, Observance. Nov 11, Monday, St. Martin's Day, Observance, Christian. Nov 17 ..."]
Thought:I have found the information about the holidays in Berlin in 2024. Now I need to format this information into the requested JSON format.
Final Answer:
```json
{
"holiday": "New Year's Day",
"date": "2024-01-01",
"holiday": "International Women's Day",
"date": "2024-03-08",
"holiday": "Good Friday",
"date": "2024-03-29",
"holiday": "Labour Day",
"date": "2024-05-01",
"holiday": "Ascension Day",
"date": "2024-05-09",
"holiday": "Whit Monday",
"date": "2024-05-20",
"holiday": "Day of German Unity",
"date": "2024-10-03",
"holiday": "Christmas Day",
"date": "2024-12-25"
}
```
但是我得到的输出只有一个假期:{'holiday': '圣诞节', 'date': '2024-12-25'}。我想要获取所有的假期和日期。
1 个回答
1
如果你要处理更复杂的JSON输出,你需要使用JsonOutputParser
或者PydanticOutputParser
。
示例输出:
{
"holidays": [
{ "name": "New Year's Day", "date": "2024-01-01" },
{ "name": "International Women's Day", "date": "2024-03-08" }
]
}
JsonOutputParser
from typing import List
from langchain_core.output_parsers import JsonOutputParser
from langchain_core.pydantic_v1 import BaseModel, Field
class Holiday(BaseModel):
name: str = Field(description="name of holiday")
date: str = Field(description="date of holiday")
class Holidays(BaseModel):
holidays: List[Holiday] = Field(description="list of holidays")
# configure output parser in chain or call parse()
output_parser = JsonOutputParser(pydantic_object=Holidays)
PydanticOutputParser
PydanticOutputParser
的实现方式和JsonOutputParser
差不多。你可以查看LangChain的示例文档了解更多。