つまり、現在のアプリケーションは台本のある劇のようなものです。すべてのセリフとアクションがコードに書かれています。LLM を呼び出す際、特定のセリフを読むよう依頼しているだけです。LLM が自ら判断を行っていないため、Observability for AI の計装はそれを自律的なエージェントとして認識しません。
# Begin: Tool Definitions@tooldefmock_search_flights(origin:str,destination:str,departure:str)->str:"""Return mock flight options for a given origin/destination pair."""# create a local random.Random instanceseed=hash((origin,destination,departure))%(2**32)rng=random.Random(seed)airline=rng.choice(["SkyLine","AeroJet","CloudNine"])fare=rng.randint(700,1250)return(f"Top choice: {airline} non-stop service {origin}->{destination}, "f"depart {departure} 09:15, arrive {departure} 17:05. "f"Premium economy fare ${fare} return.")@tooldefmock_search_hotels(destination:str,check_in:str,check_out:str)->str:"""Return mock hotel recommendation for the stay."""seed=hash((destination,check_in,check_out))%(2**32)rng=random.Random(seed)name=rng.choice(["Grand Meridian","Hotel Lumière","The Atlas"])rate=rng.randint(240,410)return(f"{name} near the historic centre. Boutique suites, rooftop bar, "f"average nightly rate ${rate} including breakfast.")@tooldefmock_search_activities(destination:str)->str:"""Return a short list of signature activities for the destination."""data=DESTINATIONS.get(destination.lower(),DESTINATIONS["paris"])bullets="\n".join(f"- {item}"foritemindata["highlights"])returnf"Signature experiences in {destination.title()}:\n{bullets}"# End: Tool Definitions
ヒントvi エディタで大量の行をまとめて削除するには、Shift + v を押して Visual Line モードにし、下矢印キーで削除したい行をすべて選択してから、d を押して
選択した行を削除します。
defcoordinator_node(state:PlannerState)->PlannerState:llm=_create_llm("coordinator",temperature=0.2,session_id=state["session_id"])agent=_create_react_agent(llm,tools=[]).with_config({"run_name":"coordinator","tags":["agent","agent:coordinator"],"metadata":{"agent_name":"coordinator","session_id":state["session_id"],},})system_message=SystemMessage(content=("You are the lead travel coordinator. Extract the key details from the ""traveller's request and describe the plan for the specialist agents."))result=agent.invoke({"messages":[system_message]+list(state["messages"])})final_message=result["messages"][-1]state["messages"].append(final_messageifisinstance(final_message,BaseMessage)elseAIMessage(content=str(final_message)))state["current_agent"]="flight_specialist"returnstatedefflight_specialist_node(state:PlannerState)->PlannerState:llm=_create_llm("flight_specialist",temperature=0.4,session_id=state["session_id"])agent=_create_react_agent(llm,tools=[mock_search_flights]).with_config({"run_name":"flight_specialist","tags":["agent","agent:flight_specialist"],"metadata":{"agent_name":"flight_specialist","session_id":state["session_id"],},})step=(f"Find an appealing flight from {state['origin']} to {state['destination']} "f"departing {state['departure']} for {state['travellers']} travellers.")# IMPORTANT: pass a proper list of messages (not stringified)messages=[SystemMessage(content="You are a flight booking specialist. Provide concise options."),HumanMessage(content=step),]result=agent.invoke({"messages":messages})final_message=result["messages"][-1]state["flight_summary"]=final_message.contentifisinstance(final_message,BaseMessage)elsestr(final_message)state["messages"].append(final_messageifisinstance(final_message,BaseMessage)elseAIMessage(content=str(final_message)))state["current_agent"]="hotel_specialist"returnstatedefhotel_specialist_node(state:PlannerState)->PlannerState:llm=_create_llm("hotel_specialist",temperature=0.5,session_id=state["session_id"])agent=_create_react_agent(llm,tools=[mock_search_hotels]).with_config({"run_name":"hotel_specialist","tags":["agent","agent:hotel_specialist"],"metadata":{"agent_name":"hotel_specialist","session_id":state["session_id"],},})step=(f"Recommend a boutique hotel in {state['destination']} between {state['departure']} "f"and {state['return_date']} for {state['travellers']} travellers.")# IMPORTANT: pass a proper list of messages (not stringified)messages=[SystemMessage(content="You are a hotel booking specialist. Provide concise options."),HumanMessage(content=step),]result=agent.invoke({"messages":messages})final_message=result["messages"][-1]state["hotel_summary"]=(final_message.contentifisinstance(final_message,BaseMessage)elsestr(final_message))state["messages"].append(final_messageifisinstance(final_message,BaseMessage)elseAIMessage(content=str(final_message)))state["current_agent"]="activity_specialist"returnstatedefactivity_specialist_node(state:PlannerState)->PlannerState:llm=_create_llm("activity_specialist",temperature=0.6,session_id=state["session_id"])agent=_create_react_agent(llm,tools=[mock_search_activities]).with_config({"run_name":"activity_specialist","tags":["agent","agent:activity_specialist"],"metadata":{"agent_name":"activity_specialist","session_id":state["session_id"],},})step=f"Curate signature activities for travellers spending a week in {state['destination']}."# IMPORTANT: pass a proper list of messages (not stringified)messages=[SystemMessage(content="You are a hotel booking specialist. Provide concise options."),HumanMessage(content=step),]result=agent.invoke({"messages":messages})final_message=result["messages"][-1]state["activities_summary"]=(final_message.contentifisinstance(final_message,BaseMessage)elsestr(final_message))state["messages"].append(final_messageifisinstance(final_message,BaseMessage)elseAIMessage(content=str(final_message)))state["current_agent"]="plan_synthesizer"returnstatedefplan_synthesizer_node(state:PlannerState)->PlannerState:llm=_create_llm("plan_synthesizer",temperature=0.3,session_id=state["session_id"])agent=_create_react_agent(llm,tools=[]).with_config({"run_name":"plan_synthesizer","tags":["agent","agent:plan_synthesizer"],"metadata":{"agent_name":"plan_synthesizer","session_id":state["session_id"],},})system_content=("You are the travel plan synthesiser. Combine the specialist insights into a ""concise, structured itinerary covering flights, accommodation and activities.")content=json.dumps({"flight":state["flight_summary"],"hotel":state["hotel_summary"],"activities":state["activities_summary"],},indent=2,)out=agent.invoke({"messages":[SystemMessage(content=system_content),HumanMessage(content=(f"Traveller request: {state['user_request']}\n\n"f"Origin: {state['origin']} | Destination: {state['destination']}\n"f"Dates: {state['departure']} to {state['return_date']}\n\n"f"Specialist summaries:\n{content}")),]})# 1) Extract the assistant's final textfinal_msg=next(mforminreversed(out["messages"])ifisinstance(m,AIMessage))state["final_itinerary"]=final_msg.content# 2) Append the new messages to your ongoing conversationstate["messages"].extend(out["messages"])# or append just final_msgstate["current_agent"]="completed"returnstate