├── src
├── config
│ ├── __init__.py
│ ├── logging.py
│ └── setup.py
├── patterns
│ ├── dynamic_sharding
│ │ ├── agent.py
│ │ ├── pipeline.py
│ │ ├── delegates.py
│ │ ├── coordinator.py
│ │ └── README.md
│ ├── task_decomposition
│ │ ├── agent.py
│ │ ├── pipeline.py
│ │ ├── README.md
│ │ ├── delegates.py
│ │ └── coordinator.py
│ ├── dynamic_decomposition
│ │ ├── agent.py
│ │ ├── pipeline.py
│ │ ├── delegates.py
│ │ └── README.md
│ ├── semantic_router
│ │ ├── agent.py
│ │ ├── pipeline.py
│ │ ├── delegates
│ │ │ ├── hotel_search.py
│ │ │ ├── flight_search.py
│ │ │ └── car_rental_search.py
│ │ └── README.md
│ ├── parallel_delegation
│ │ ├── agent.py
│ │ ├── pipeline.py
│ │ ├── README.md
│ │ └── delegates
│ │ │ ├── flight_search.py
│ │ │ ├── hotel_search.py
│ │ │ └── car_rental_search.py
│ ├── reflection
│ │ ├── utils.py
│ │ └── README.md
│ ├── web_access
│ │ ├── factory.py
│ │ ├── tasks.py
│ │ ├── README.md
│ │ └── summarize.py
│ └── dag_orchestration
│ │ ├── pipeline.py
│ │ ├── README.md
│ │ └── agent.py
├── commons
│ └── message.py
├── llm
│ └── factory.py
└── memory
│ └── manage.py
├── data
└── patterns
│ ├── semantic_router
│ ├── delegate
│ │ ├── hotel_search
│ │ │ ├── user_instructions.txt
│ │ │ ├── response_schema.json
│ │ │ └── system_instructions.txt
│ │ ├── car_rental_search
│ │ │ ├── user_instructions.txt
│ │ │ ├── response_schema.json
│ │ │ └── system_instructions.txt
│ │ └── flight_search
│ │ │ ├── user_instructions.txt
│ │ │ ├── response_schema.json
│ │ │ └── system_instructions.txt
│ ├── output
│ │ ├── coordinator
│ │ │ ├── route
│ │ │ │ └── route.json
│ │ │ └── consolidate
│ │ │ │ └── consolidate.txt
│ │ └── delegate
│ │ │ └── hotel_search
│ │ │ ├── hotel_search.json
│ │ │ └── hotel_search.txt
│ └── coordinator
│ │ ├── route
│ │ ├── user_instructions.txt
│ │ ├── response_schema.json
│ │ └── system_instructions.txt
│ │ └── consolidate
│ │ ├── user_instructions.txt
│ │ └── system_instructions.txt
│ ├── parallel_delegation
│ ├── delegates
│ │ ├── hotel_search
│ │ │ ├── user_instructions.txt
│ │ │ ├── response_schema.json
│ │ │ └── system_instructions.txt
│ │ ├── car_rental_search
│ │ │ ├── user_instructions.txt
│ │ │ ├── response_schema.json
│ │ │ └── system_instructions.txt
│ │ └── flight_search
│ │ │ ├── user_instructions.txt
│ │ │ ├── response_schema.json
│ │ │ └── system_instructions.txt
│ ├── output
│ │ ├── delegate
│ │ │ ├── flight_search
│ │ │ │ ├── flight_search.json
│ │ │ │ └── flight_search.txt
│ │ │ ├── hotel_search
│ │ │ │ ├── hotel_search.json
│ │ │ │ └── hotel_search.txt
│ │ │ └── car_rental_search
│ │ │ │ ├── car_rental_search.json
│ │ │ │ └── car_rental_search.txt
│ │ └── coordinator
│ │ │ ├── ner
│ │ │ └── ner.json
│ │ │ └── consolidate
│ │ │ └── consolidate.txt
│ └── coordinator
│ │ ├── ner
│ │ ├── user_instructions.txt
│ │ ├── system_instructions.txt
│ │ └── response_schema.json
│ │ └── consolidate
│ │ ├── user_instructions.txt
│ │ └── system_instructions.txt
│ ├── web_access
│ ├── search
│ │ ├── user_instructions.txt
│ │ └── system_instructions.txt
│ ├── summarize
│ │ ├── user_instructions.txt
│ │ └── system_instructions.txt
│ └── output
│ │ ├── summarize
│ │ └── dd98fb7e26e193dde3e562f56a96f4f3.txt
│ │ └── search
│ │ └── dd98fb7e26e193dde3e562f56a96f4f3.json
│ ├── dag_orchestration
│ ├── schemas
│ │ ├── compile.json
│ │ ├── summarize.json
│ │ ├── preprocess.json
│ │ ├── collect.json
│ │ └── extract.json
│ ├── trace
│ │ ├── task4.json
│ │ ├── task3.json
│ │ ├── task2.json
│ │ └── task1.json
│ ├── docs
│ │ ├── doc2.txt
│ │ ├── doc1.txt
│ │ └── doc3.txt
│ └── dag.yml
│ ├── reflection
│ ├── actor
│ │ ├── draft
│ │ │ ├── user_instructions.txt
│ │ │ ├── response_schema.json
│ │ │ └── system_instructions.txt
│ │ └── revise
│ │ │ ├── response_schema.json
│ │ │ ├── user_instructions.txt
│ │ │ └── system_instructions.txt
│ ├── critic
│ │ ├── review
│ │ │ ├── user_instructions.txt
│ │ │ ├── response_schema.json
│ │ │ └── system_instructions.txt
│ │ └── revise
│ │ │ ├── response_schema.json
│ │ │ ├── system_instructions.txt
│ │ │ └── user_instructions.txt
│ └── output
│ │ ├── feedback
│ │ ├── v1.json
│ │ ├── v0.json
│ │ └── v2.json
│ │ └── draft
│ │ └── v0.json
│ └── dynamic_sharding
│ └── entities.txt
├── img
├── agentic.png
└── framework
│ ├── reflection.png
│ ├── web_access.png
│ ├── dynamic_sharding.png
│ ├── semantic_router.png
│ ├── dag_orchestration.png
│ ├── task_decomposition.png
│ ├── dynamic_decomposition.png
│ └── parallel_delegation.png
├── config
├── setup.yml
└── patterns
│ ├── web_access.yml
│ ├── reflection.yml
│ ├── semantic_router.yml
│ └── parallel_delegation.yml
├── LICENSE
├── requirements.txt
├── mermaid
├── dynamic_decomposition.mmd
├── dynamic_sharding.mmd
├── reflection.mmd
├── dag_orchestration.mmd
├── task_decomposition.mmd
├── semantic_router.mmd
├── web_access.mmd
└── parallel_delegation.mmd
└── .gitignore
/src/config/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/data/patterns/semantic_router/delegate/hotel_search/user_instructions.txt:
--------------------------------------------------------------------------------
1 | User provided query: `{query}`
--------------------------------------------------------------------------------
/data/patterns/parallel_delegation/delegates/hotel_search/user_instructions.txt:
--------------------------------------------------------------------------------
1 | User provided query: `{query}`
--------------------------------------------------------------------------------
/data/patterns/semantic_router/delegate/car_rental_search/user_instructions.txt:
--------------------------------------------------------------------------------
1 | User provided query: `{query}`
--------------------------------------------------------------------------------
/data/patterns/semantic_router/delegate/flight_search/user_instructions.txt:
--------------------------------------------------------------------------------
1 | User provided query: `{query}`
--------------------------------------------------------------------------------
/img/agentic.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ashishpatel26/Agentic-Workflow-Patterns/main/img/agentic.png
--------------------------------------------------------------------------------
/data/patterns/parallel_delegation/delegates/car_rental_search/user_instructions.txt:
--------------------------------------------------------------------------------
1 | User provided query: `{query}`
--------------------------------------------------------------------------------
/data/patterns/parallel_delegation/delegates/flight_search/user_instructions.txt:
--------------------------------------------------------------------------------
1 | User provided query: `{query}`
--------------------------------------------------------------------------------
/img/framework/reflection.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ashishpatel26/Agentic-Workflow-Patterns/main/img/framework/reflection.png
--------------------------------------------------------------------------------
/img/framework/web_access.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ashishpatel26/Agentic-Workflow-Patterns/main/img/framework/web_access.png
--------------------------------------------------------------------------------
/img/framework/dynamic_sharding.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ashishpatel26/Agentic-Workflow-Patterns/main/img/framework/dynamic_sharding.png
--------------------------------------------------------------------------------
/img/framework/semantic_router.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ashishpatel26/Agentic-Workflow-Patterns/main/img/framework/semantic_router.png
--------------------------------------------------------------------------------
/img/framework/dag_orchestration.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ashishpatel26/Agentic-Workflow-Patterns/main/img/framework/dag_orchestration.png
--------------------------------------------------------------------------------
/img/framework/task_decomposition.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ashishpatel26/Agentic-Workflow-Patterns/main/img/framework/task_decomposition.png
--------------------------------------------------------------------------------
/config/setup.yml:
--------------------------------------------------------------------------------
1 | # This is project-level config params
2 | project_id: arun-genai-bb
3 | credentials_json: ./credentials/key.json
4 | region: us-central1
--------------------------------------------------------------------------------
/img/framework/dynamic_decomposition.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ashishpatel26/Agentic-Workflow-Patterns/main/img/framework/dynamic_decomposition.png
--------------------------------------------------------------------------------
/img/framework/parallel_delegation.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ashishpatel26/Agentic-Workflow-Patterns/main/img/framework/parallel_delegation.png
--------------------------------------------------------------------------------
/data/patterns/web_access/search/user_instructions.txt:
--------------------------------------------------------------------------------
1 | For the user-provided query `{query}`, extract key entities to format as function arguments for Google Search API calls.
--------------------------------------------------------------------------------
/data/patterns/semantic_router/output/coordinator/route/route.json:
--------------------------------------------------------------------------------
1 | {
2 | "intent": "HOTEL",
3 | "query": "Could you recommend some hotels in Santa Barbara, California for a stay next week?"
4 | }
--------------------------------------------------------------------------------
/data/patterns/semantic_router/coordinator/route/user_instructions.txt:
--------------------------------------------------------------------------------
1 | Analyze the user query `{query}` to determine if the intent is for **Flight Search**, **Hotel Search**, **Car Rental Search**, or **NA** (Not Applicable).
--------------------------------------------------------------------------------
/data/patterns/parallel_delegation/output/delegate/flight_search/flight_search.json:
--------------------------------------------------------------------------------
1 | {
2 | "user_query": "FLIGHT: {'destination': 'Dallas', 'origin': 'New York'}",
3 | "web_search_query": "Flights from New York to Dallas"
4 | }
--------------------------------------------------------------------------------
/data/patterns/dag_orchestration/schemas/compile.json:
--------------------------------------------------------------------------------
1 | {
2 | "type": "object",
3 | "properties": {
4 | "report": {
5 | "type": "string"
6 | }
7 | },
8 | "required": ["report"]
9 | }
10 |
--------------------------------------------------------------------------------
/data/patterns/parallel_delegation/output/delegate/hotel_search/hotel_search.json:
--------------------------------------------------------------------------------
1 | {
2 | "user_query": "HOTEL: {'date': 'next week', 'destination': 'downtown Dallas'}",
3 | "web_search_query": "Hotels in downtown Dallas next week"
4 | }
--------------------------------------------------------------------------------
/data/patterns/parallel_delegation/output/delegate/car_rental_search/car_rental_search.json:
--------------------------------------------------------------------------------
1 | {
2 | "user_query": "CAR_RENTAL: {'date': 'next week', 'pickup_location': 'Dallas'}",
3 | "web_search_query": "Car rental in Dallas next week"
4 | }
--------------------------------------------------------------------------------
/data/patterns/reflection/actor/draft/user_instructions.txt:
--------------------------------------------------------------------------------
1 | Write a one-page academic article on the given topic below and its significance, suitable for graduate students and researchers.
2 | Balance technical depth with clarity.
3 |
4 | Topic: `{topic}`
--------------------------------------------------------------------------------
/data/patterns/semantic_router/output/delegate/hotel_search/hotel_search.json:
--------------------------------------------------------------------------------
1 | {
2 | "user_query": "Could you recommend some hotels in Santa Barbara, California for a stay next week?",
3 | "web_search_query": "Hotels in Santa Barbara, California next week"
4 | }
--------------------------------------------------------------------------------
/data/patterns/parallel_delegation/coordinator/ner/user_instructions.txt:
--------------------------------------------------------------------------------
1 | Analyze the user query `{query}` to identify intents and extract relevant entities for flight, hotel, and car rental searches simultaneously, handling multiple intents per query and classifying out-of-scope requests as unknown.
--------------------------------------------------------------------------------
/data/patterns/web_access/summarize/user_instructions.txt:
--------------------------------------------------------------------------------
1 | Given the user-provided query `{query}` and the accompanying scraped content from relevant webpages below,
2 | please follow the provided guidelines to generate a comprehensive summary with appropriate citations:
3 |
4 | {scraped_content}
--------------------------------------------------------------------------------
/data/patterns/reflection/actor/draft/response_schema.json:
--------------------------------------------------------------------------------
1 | {
2 | "type": "object",
3 | "properties": {
4 | "topic": {
5 | "type": "string"
6 | },
7 | "article": {
8 | "type": "string"
9 | }
10 | },
11 | "required": ["topic", "article"]
12 | }
--------------------------------------------------------------------------------
/data/patterns/semantic_router/coordinator/consolidate/user_instructions.txt:
--------------------------------------------------------------------------------
1 | Synthesize the user query `{query}` with web search results (provided below) to provide a clear, informative, and user-friendly response that directly addresses the user's needs.
2 |
3 | ### Web search results
4 |
5 | `{summary}`
--------------------------------------------------------------------------------
/data/patterns/reflection/actor/revise/response_schema.json:
--------------------------------------------------------------------------------
1 | {
2 | "type": "object",
3 | "properties": {
4 | "topic": {
5 | "type": "string"
6 | },
7 | "article": {
8 | "type": "string"
9 | },
10 | "edits": {
11 | "type": "string"
12 | }
13 | },
14 | "required": ["topic", "article", "edits"]
15 | }
--------------------------------------------------------------------------------
/data/patterns/parallel_delegation/output/coordinator/ner/ner.json:
--------------------------------------------------------------------------------
1 | {
2 | "CAR_RENTAL": {
3 | "date": "next week",
4 | "pickup_location": "Dallas"
5 | },
6 | "FLIGHT": {
7 | "destination": "Dallas",
8 | "origin": "New York"
9 | },
10 | "HOTEL": {
11 | "date": "next week",
12 | "destination": "downtown Dallas"
13 | }
14 | }
--------------------------------------------------------------------------------
/data/patterns/reflection/critic/review/user_instructions.txt:
--------------------------------------------------------------------------------
1 | Please review the following research article:
2 |
3 | {article}
4 |
5 | Provide a comprehensive peer review following the structure and guidelines outlined in the previous instructions.
6 | Your review should include a summary, assessment of strengths and weaknesses, detailed comments, and an overall recommendation.
--------------------------------------------------------------------------------
/data/patterns/dynamic_sharding/entities.txt:
--------------------------------------------------------------------------------
1 | Tom Hanks
2 | Meryl Streep
3 | Leonardo DiCaprio
4 | Jennifer Lawrence
5 | Denzel Washington
6 | Cate Blanchett
7 | Brad Pitt
8 | Viola Davis
9 | Robert Downey Jr.
10 | Charlize Theron
11 | Morgan Freeman
12 | Scarlett Johansson
13 | Johnny Depp
14 | Natalie Portman
15 | Will Smith
16 | Emma Stone
17 | Hugh Jackman
18 | Angelina Jolie
--------------------------------------------------------------------------------
/config/patterns/web_access.yml:
--------------------------------------------------------------------------------
1 | tools:
2 | search:
3 | system_instructions: './data/patterns/web_access/search/system_instructions.txt'
4 | user_instructions: './data/patterns/web_access/search/user_instructions.txt'
5 | summarize:
6 | system_instructions: './data/patterns/web_access/summarize/system_instructions.txt'
7 | user_instructions: './data/patterns/web_access/summarize/user_instructions.txt'
8 |
--------------------------------------------------------------------------------
/data/patterns/parallel_delegation/coordinator/consolidate/user_instructions.txt:
--------------------------------------------------------------------------------
1 | Synthesize the user query `{query}` with web search results (provided below) to provide a clear, informative, and user-friendly response that directly addresses the user's needs.
2 |
3 | ## Web search results
4 | ### Flight summary:
5 | {flight_summary}
6 |
7 | #### otel summary:
8 | {hotel_summary}
9 |
10 | ## Car rental summary:
11 | {car_rental_summary}
--------------------------------------------------------------------------------
/data/patterns/semantic_router/coordinator/route/response_schema.json:
--------------------------------------------------------------------------------
1 | {
2 | "type": "object",
3 | "properties": {
4 | "query": {
5 | "type": "string",
6 | "description": "The original user query."
7 | },
8 | "intent": {
9 | "type": "string",
10 | "description": "The detected intent of the query.",
11 | "enum": ["FLIGHT", "HOTEL", "CAR_RENTAL", "UNKNOWN"]
12 | }
13 | },
14 | "required": ["query", "intent"]
15 | }
16 |
--------------------------------------------------------------------------------
/data/patterns/semantic_router/delegate/hotel_search/response_schema.json:
--------------------------------------------------------------------------------
1 | {
2 | "type": "object",
3 | "properties": {
4 | "user_query": {
5 | "type": "string",
6 | "description": "The original user-provided query."
7 | },
8 | "web_search_query": {
9 | "type": "string",
10 | "description": "The query transformed for optimized web search."
11 | }
12 | },
13 | "required": ["user_query", "web_search_query"]
14 | }
--------------------------------------------------------------------------------
/data/patterns/dag_orchestration/schemas/summarize.json:
--------------------------------------------------------------------------------
1 | {
2 | "type": "object",
3 | "properties": {
4 | "summaries": {
5 | "type": "array",
6 | "items": {
7 | "type": "object",
8 | "properties": {
9 | "id": { "type": "string" },
10 | "summary": { "type": "string" }
11 | },
12 | "required": ["id", "summary"]
13 | }
14 | }
15 | },
16 | "required": ["summaries"]
17 | }
18 |
--------------------------------------------------------------------------------
/data/patterns/parallel_delegation/delegates/hotel_search/response_schema.json:
--------------------------------------------------------------------------------
1 | {
2 | "type": "object",
3 | "properties": {
4 | "user_query": {
5 | "type": "string",
6 | "description": "The original user-provided query."
7 | },
8 | "web_search_query": {
9 | "type": "string",
10 | "description": "The query transformed for optimized web search."
11 | }
12 | },
13 | "required": ["user_query", "web_search_query"]
14 | }
--------------------------------------------------------------------------------
/data/patterns/semantic_router/delegate/car_rental_search/response_schema.json:
--------------------------------------------------------------------------------
1 | {
2 | "type": "object",
3 | "properties": {
4 | "user_query": {
5 | "type": "string",
6 | "description": "The original user-provided query."
7 | },
8 | "web_search_query": {
9 | "type": "string",
10 | "description": "The query transformed for optimized web search."
11 | }
12 | },
13 | "required": ["user_query", "web_search_query"]
14 | }
--------------------------------------------------------------------------------
/data/patterns/semantic_router/delegate/flight_search/response_schema.json:
--------------------------------------------------------------------------------
1 | {
2 | "type": "object",
3 | "properties": {
4 | "user_query": {
5 | "type": "string",
6 | "description": "The original user-provided query."
7 | },
8 | "web_search_query": {
9 | "type": "string",
10 | "description": "The query transformed for optimized web search."
11 | }
12 | },
13 | "required": ["user_query", "web_search_query"]
14 | }
15 |
--------------------------------------------------------------------------------
/data/patterns/parallel_delegation/delegates/car_rental_search/response_schema.json:
--------------------------------------------------------------------------------
1 | {
2 | "type": "object",
3 | "properties": {
4 | "user_query": {
5 | "type": "string",
6 | "description": "The original user-provided query."
7 | },
8 | "web_search_query": {
9 | "type": "string",
10 | "description": "The query transformed for optimized web search."
11 | }
12 | },
13 | "required": ["user_query", "web_search_query"]
14 | }
--------------------------------------------------------------------------------
/data/patterns/parallel_delegation/delegates/flight_search/response_schema.json:
--------------------------------------------------------------------------------
1 | {
2 | "type": "object",
3 | "properties": {
4 | "user_query": {
5 | "type": "string",
6 | "description": "The original user-provided query."
7 | },
8 | "web_search_query": {
9 | "type": "string",
10 | "description": "The query transformed for optimized web search."
11 | }
12 | },
13 | "required": ["user_query", "web_search_query"]
14 | }
15 |
--------------------------------------------------------------------------------
/data/patterns/dag_orchestration/schemas/preprocess.json:
--------------------------------------------------------------------------------
1 | {
2 | "type": "object",
3 | "properties": {
4 | "preprocessed_docs": {
5 | "type": "array",
6 | "items": {
7 | "type": "object",
8 | "properties": {
9 | "id": { "type": "string" },
10 | "title": { "type": "string" },
11 | "content": { "type": "string" }
12 | },
13 | "required": ["id", "title", "content"]
14 | }
15 | }
16 | },
17 | "required": ["preprocessed_docs"]
18 | }
19 |
--------------------------------------------------------------------------------
/data/patterns/reflection/critic/review/response_schema.json:
--------------------------------------------------------------------------------
1 | {
2 | "type": "object",
3 | "properties": {
4 | "summary": {
5 | "type": "string"
6 | },
7 | "strengths": {
8 | "type": "string"
9 | },
10 | "weaknesses": {
11 | "type": "string"
12 | },
13 | "minor_issues": {
14 | "type": "string"
15 | },
16 | "overall_recommendation": {
17 | "type": "string"
18 | }
19 | },
20 | "required": ["summary", "strengths", "weaknesses", "minor_issues", "overall_recommendation"]
21 | }
--------------------------------------------------------------------------------
/data/patterns/reflection/critic/revise/response_schema.json:
--------------------------------------------------------------------------------
1 | {
2 | "type": "object",
3 | "properties": {
4 | "summary": {
5 | "type": "string"
6 | },
7 | "strengths": {
8 | "type": "string"
9 | },
10 | "weaknesses": {
11 | "type": "string"
12 | },
13 | "minor_issues": {
14 | "type": "string"
15 | },
16 | "overall_recommendation": {
17 | "type": "string"
18 | }
19 | },
20 | "required": ["summary", "strengths", "weaknesses", "minor_issues", "overall_recommendation"]
21 | }
--------------------------------------------------------------------------------
/data/patterns/dag_orchestration/schemas/collect.json:
--------------------------------------------------------------------------------
1 | {
2 | "type": "object",
3 | "properties": {
4 | "docs": {
5 | "type": "array",
6 | "items": {
7 | "type": "object",
8 | "properties": {
9 | "id": { "type": "string" },
10 | "title": { "type": "string" },
11 | "content": { "type": "string" },
12 | "filename": { "type": "string" }
13 | },
14 | "required": ["id", "title", "content", "filename"]
15 | }
16 | }
17 | },
18 | "required": ["docs"]
19 | }
20 |
21 |
--------------------------------------------------------------------------------
/data/patterns/semantic_router/coordinator/consolidate/system_instructions.txt:
--------------------------------------------------------------------------------
1 | # AI Assistant Task
2 |
3 | You are an AI assistant tasked with providing informative and user-friendly responses by combining user queries with web search results. Your role is to:
4 |
5 | 1. Analyze the user's query: `{query}`
6 | 2. Review the summary of web search results: `{summary}`
7 | 3. Synthesize this information into a coherent, helpful response for the user
8 |
9 | Your response should:
10 |
11 | - Directly address the user's query
12 | - Incorporate relevant information from the web search results
13 | - Be clear, concise, and easy to understand
14 |
15 | **IMPORTANT:** Do not ask follow up questions.
--------------------------------------------------------------------------------
/data/patterns/parallel_delegation/coordinator/consolidate/system_instructions.txt:
--------------------------------------------------------------------------------
1 | You are an AI assistant tasked with providing informative and user-friendly responses by combining user queries with web search results. Your role involves:
2 |
3 | Analyzing the provided user query
4 | Reviewing the summary of web search results, which includes three summaries:
5 |
6 | Flight summary
7 | Hotel summary
8 | Car rental summary
9 |
10 |
11 | Synthesizing this information into a coherent, helpful response for the user
12 |
13 | Your response should:
14 |
15 | Directly address the user's query
16 | Incorporate relevant information from the web search results
17 | Be clear, concise, and easy to understand
18 |
19 | IMPORTANT: Do not ask follow-up questions.
--------------------------------------------------------------------------------
/data/patterns/parallel_delegation/output/coordinator/consolidate/consolidate.txt:
--------------------------------------------------------------------------------
1 | Your trip to Dallas next week can be arranged easily! For your flight from New York to Dallas, expect to pay around $139 for a round trip from New York LaGuardia Airport to Dallas/Fort Worth Airport. Booking your flight by Thursday and at least a month in advance may help you find a cheaper fare. Once in Dallas, you'll find a variety of hotels in the downtown area, including popular options like the Omni Dallas Hotel and Fairmont Dallas. Remember to book in advance as hotels tend to fill up quickly. To navigate Dallas with ease, consider renting a car. You can find rentals starting at $31 per day. Due to potential traffic and distances between attractions, larger vehicles like SUVs are recommended by some. Enjoy your trip!
--------------------------------------------------------------------------------
/data/patterns/semantic_router/output/coordinator/consolidate/consolidate.txt:
--------------------------------------------------------------------------------
1 | Santa Barbara has a great selection of hotels to choose from, with options for all budgets and preferences. You can find beachfront properties, downtown accommodations, Spanish Colonial-style bungalows, luxury resorts, contemporary hotels, affordable motels, neighborhood inns, vacation rentals, and even beachside camping spots.
2 |
3 | Here are some popular hotels in Santa Barbara:
4 |
5 | * La Playa Inn Santa Barbara
6 | * Marina Beach Motel
7 | * Simpson House Inn
8 | * Hotel Milo Santa Barbara
9 | * Hyatt Place Santa Barbara
10 | * Sandpiper Lodge
11 | * Avania Inn of Santa Barbara
12 | * Inn By The Harbor
13 |
14 | These hotels typically offer amenities like free WiFi, continental breakfast, outdoor pools, hot tubs, and fitness centers.
--------------------------------------------------------------------------------
/data/patterns/web_access/search/system_instructions.txt:
--------------------------------------------------------------------------------
1 | # You Are Google Search Query Assistant
2 |
3 | ## Overview
4 | Your primary responsibility is to extract relevant entities from user queries. These entities will serve as function arguments for Google Search API calls.
5 |
6 | ## Key Responsibilities
7 | 1. **Analyze User Queries**: Carefully examine the user's query to understand its intent.
8 | 2. **Identify and Extract Entities**: Pinpoint key entities, topics, and concepts within the query that are essential for search.
9 | 3. **Format for API**: Present the extracted entities in a format suitable for use as parameters in API function arguments.
10 |
11 | ## Focus
12 | - Ensure accurate extraction of entities that will be directly usable in API calls.
13 | - Your role is to prepare the query for search tools, not to perform the search or provide search results.
14 |
--------------------------------------------------------------------------------
/data/patterns/reflection/actor/revise/user_instructions.txt:
--------------------------------------------------------------------------------
1 | ## History
2 | {history}
3 |
4 | Based on the provided history above, revise the latest version of the draft using the guide below.
5 |
6 | # Revision Guide
7 |
8 | ## Review and Analyze
9 | - Examine conversation history
10 | - Focus on original draft and reviewer feedback
11 | - List and categorize all issues from feedback
12 |
13 | ## Systematic Revision
14 | - For each issue:
15 | - Identify the problem
16 | - Implement necessary changes
17 | - Briefly explain rationale
18 |
19 | ## Enhance and Refine
20 | - Improve overall coherence and clarity
21 | - Reorganize structure for better flow
22 | - Maintain professional, clear language
23 |
24 | ## Final Checks
25 | - Retain all key points unless advised to remove
26 | - Proofread for errors and inconsistencies
27 | - Indicate this is a revised version
28 |
29 | ## Deliverable
30 | Provide concise, revised instructions addressing all feedback points.
--------------------------------------------------------------------------------
/data/patterns/reflection/output/feedback/v1.json:
--------------------------------------------------------------------------------
1 | {"minor_issues": "None.", "overall_recommendation": "Accept", "strengths": "1. **Comprehensive Revisions:** The authors have effectively addressed all previous concerns. The addition of concrete examples and the expanded discussion on limitations significantly enhance the article's clarity and depth.\n2. **Well-Structured and Accessible:** The article is well-organized and written in a clear, concise style, making it accessible to a broad audience, including those new to the concept of perplexity.\n3. **Valuable Insights:** The inclusion of future directions provides a forward-looking perspective, highlighting potential areas for further research and development in this field.", "summary": "This revised article provides a thorough and insightful overview of perplexity as a measure of language model proficiency. The authors have successfully addressed previous feedback, resulting in a well-structured and informative piece suitable for publication.", "weaknesses": "None."}
2 |
--------------------------------------------------------------------------------
/data/patterns/semantic_router/coordinator/route/system_instructions.txt:
--------------------------------------------------------------------------------
1 | You are a travel planner agent - responsible for analyzing user queries to accurately identify the intent and route them to the appropriate sub-agent. It categorizes the intent into the following predefined classes:
2 |
3 | 1. **Flight Search**
4 | - Identifies queries related to finding flights, including flight availability, prices, and booking information.
5 |
6 | 2. **Hotel Search**
7 | - Detects requests involving hotel availability, room booking, or pricing for accommodation.
8 |
9 | 3. **Car Rental Search**
10 | - Identifies queries that pertain to car rental services, such as availability, pricing, and rental options.
11 |
12 | 4. **Unknown (Not Applicable)**
13 | - If the user query does not match any of the above categories, the intent is classified as **UNKNOWN**, indicating it falls outside the scope of recognized intents.
14 |
15 | The agent ensures precise intent classification to enhance the user experience by routing each query to the correct service or sub-agent.
--------------------------------------------------------------------------------
/data/patterns/parallel_delegation/output/delegate/hotel_search/hotel_search.txt:
--------------------------------------------------------------------------------
1 | # Downtown Dallas Hotels Next Week
2 |
3 | Downtown Dallas offers a variety of hotels for visitors, with options ranging from budget-friendly to luxury accommodations. Popular hotels in the area include Omni Dallas Hotel, Fairmont Dallas, Courtyard by Marriott Dallas Downtown/Reunion District, Holiday Inn Express Dallas Downtown, and SpringHill Suites by Marriott Dallas Downtown/West End. These hotels are often booked quickly, so it is recommended to reserve your room in advance, especially if traveling next week.
4 |
5 | Downtown Dallas is known for its shops, museums, live music scene, and selection of restaurants. Visitors can enjoy attractions such as the Kay Bailey Hutchison Convention Center, Dallas City Hall, and Majestic Theater.
6 |
7 | ## Citations
8 |
9 | 1. https://www.hotels.com/nh1327/hotels-in-downtown-dallas-dallas-texas/
10 | 2. https://www.booking.com/district/us/dallas/downtown.html
11 | 3. https://www.expedia.com/Downtown-Dallas-Dallas-Hotels.0-n800026-0.Travel-Guide-Filter-Hotels
--------------------------------------------------------------------------------
/data/patterns/reflection/actor/draft/system_instructions.txt:
--------------------------------------------------------------------------------
1 | You are a distinguished professor from a renowned university, recognized worldwide for your expertise in your field.
2 | Your task is to write a two-page article (1200-1600 words) on a given topic related to your area of specialization and its significance in the broader context of your field.
3 |
4 | Audience: Graduate students and researchers in your discipline
5 | Tone: Academic yet accessible. Balance technical depth with clarity.
6 |
7 | Structure:
8 | 1. Introduction to the topic
9 | 2. Explanation of the topic's importance in the context of your field
10 | 3. Implications for future research
11 |
12 | Guidelines:
13 | - Use well-structured prose with clear paragraph breaks
14 | - Maintain an authoritative professorial voice
15 | - Balance technical rigor with clarity
16 | - Explain necessary technical terms
17 | - Ensure comprehensibility for students and researchers
18 |
19 | The article should provide a comprehensive overview of the chosen topic, its relevance to your field of study, and potential future directions in the discipline.
--------------------------------------------------------------------------------
/data/patterns/reflection/actor/revise/system_instructions.txt:
--------------------------------------------------------------------------------
1 | You are a distinguished professor from a renowned university, recognized worldwide for your expertise in your field.
2 | Your task is to write a two-page article (1200-1600 words) on a given topic related to your area of specialization and its significance in the broader context of your field.
3 |
4 | Audience: Graduate students and researchers in your discipline
5 | Tone: Academic yet accessible. Balance technical depth with clarity.
6 |
7 | Structure:
8 | 1. Introduction to the topic
9 | 2. Explanation of the topic's importance in the context of your field
10 | 3. Implications for future research
11 |
12 | Guidelines:
13 | - Use well-structured prose with clear paragraph breaks
14 | - Maintain an authoritative professorial voice
15 | - Balance technical rigor with clarity
16 | - Explain necessary technical terms
17 | - Ensure comprehensibility for students and researchers
18 |
19 | The article should provide a comprehensive overview of the chosen topic, its relevance to your field of study, and potential future directions in the discipline.
--------------------------------------------------------------------------------
/data/patterns/parallel_delegation/output/delegate/flight_search/flight_search.txt:
--------------------------------------------------------------------------------
1 | # Flights from New York to Dallas
2 |
3 | - The cheapest time to fly from New York to Dallas is typically in September. The most expensive month is typically July. Prices in January are usually between $120 and $310.
4 | - On average, Thursday is the cheapest day to fly, and Sunday is the most expensive.
5 | - When booking flights, Thursday is the best day to book. This will help you save 6% to 13% compared to booking on a Friday.
6 | - For domestic flights, booking at least a month in advance can save you 24%. For international flights, book 2 months in advance to save 10%.
7 | - The cheapest route for a one-way flight is from Newark Airport to Dallas/Fort Worth Airport.
8 | - The average price for a round-trip flight from New York LaGuardia Airport to Dallas/Fort Worth Airport is $139.
9 |
10 | ## Citations
11 |
12 | 1. https://www.expedia.com/lp/flights/nyc/dfw/new-york-to-dallas
13 | 2. https://www.kayak.com/flight-routes/New-York-NYC/Dallas-A78
14 | 3. https://www.google.com/travel/flights/flights-from-new-york-to-dallas.html
--------------------------------------------------------------------------------
/data/patterns/dag_orchestration/trace/task4.json:
--------------------------------------------------------------------------------
1 | {
2 | "summaries": [
3 | {
4 | "id": "doc1",
5 | "summary": "Amelia, a lighthouse keeper's daughter, faces the daunting task of maintaining the lighthouse after her father's illness, overcoming village doubts and braving treacherous storms to become the beacon of hope for her community. She discovers her own strength and purpose in the face of adversity, becoming a symbol of resilience and a guiding light for others."
6 | },
7 | {
8 | "id": "doc2",
9 | "summary": "Marcus, a once renowned artist, falls into despair after a tragic accident but is drawn back to painting by a friend's dying wish. Through the act of creation, Marcus finds redemption, realizing that art's true power lies in its ability to heal and connect."
10 | },
11 | {
12 | "id": "doc3",
13 | "summary": "Professor Elena Reyes, obsessed with an ancient manuscript, experiences strange occurrences and a blurring of reality as she deciphers its secrets, ultimately vanishing and seemingly becoming the forgotten priestess of the civilization she studied."
14 | }
15 | ]
16 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2024 Arun Shankar
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/data/patterns/dag_orchestration/schemas/extract.json:
--------------------------------------------------------------------------------
1 | {
2 | "type": "object",
3 | "properties": {
4 | "extracted_items": {
5 | "type": "array",
6 | "items": {
7 | "type": "object",
8 | "properties": {
9 | "id": { "type": "string" },
10 | "key_info": {
11 | "type": "array",
12 | "items": {
13 | "type": "object",
14 | "properties": {
15 | "characters": {
16 | "type": "array",
17 | "items": { "type": "string" }
18 | },
19 | "themes": {
20 | "type": "array",
21 | "items": { "type": "string" }
22 | },
23 | "plot_points": {
24 | "type": "array",
25 | "items": { "type": "string" }
26 | }
27 | },
28 | "required": ["characters", "themes", "plot_points"]
29 | }
30 | }
31 | },
32 | "required": ["id", "key_info"]
33 | }
34 | }
35 | },
36 | "required": ["extracted_items"]
37 | }
38 |
--------------------------------------------------------------------------------
/data/patterns/reflection/output/draft/v0.json:
--------------------------------------------------------------------------------
1 | {"article": "## Perplexity: A Measure of Language Model Proficiency\n\nPerplexity is a fundamental metric in natural language processing (NLP) that quantifies the ability of a language model to predict the next word in a sequence. It serves as a crucial tool for evaluating the performance of language models, providing insights into their understanding of language structure and semantic relationships. This article delves into the concept of perplexity, its significance in NLP, and its implications for future research.\n\n### Understanding Perplexity\n\nPerplexity is rooted in information theory, where it measures the uncertainty or surprise associated with a probability distribution. In the context of language models, perplexity reflects the model's ability to predict the next word given the preceding words in a sequence. A lower perplexity score indicates that the model is better at predicting the next word, suggesting a deeper understanding of the language's statistical properties.\n\nMathematically, perplexity is calculated as the exponential of the average negative log probability of the words in a test set. The formula is:\n\n
--------------------------------------------------------------------------------
/src/patterns/dynamic_sharding/agent.py:
--------------------------------------------------------------------------------
1 | from src.commons.message import Message
2 | from abc import abstractmethod
3 | from abc import ABC
4 |
5 |
6 | class Agent(ABC):
7 | """
8 | A base class representing an agent responsible for processing messages
9 | and validating input and output data based on given JSON schemas.
10 | """
11 |
12 | def __init__(self, name: str) -> None:
13 | """
14 | Initializes the agent with a given name.
15 |
16 | Args:
17 | name (str): The name of the agent.
18 | """
19 | self.name = name
20 |
21 | @abstractmethod
22 | async def process(self, message: 'Message') -> 'Message':
23 | """
24 | Abstract method to process the message.
25 |
26 | Args:
27 | message (Message): A message object containing relevant data.
28 |
29 | Returns:
30 | Message: Processed message.
31 |
32 | Raises:
33 | NotImplementedError: If not overridden by a subclass.
34 | """
35 | raise NotImplementedError("This method should be implemented by subclasses.")
36 |
--------------------------------------------------------------------------------
/src/patterns/task_decomposition/agent.py:
--------------------------------------------------------------------------------
1 | from src.commons.message import Message
2 | from abc import abstractmethod
3 | from abc import ABC
4 |
5 |
6 | class Agent(ABC):
7 | """
8 | A base class representing an agent responsible for processing messages
9 | and validating input and output data based on given JSON schemas.
10 | """
11 |
12 | def __init__(self, name: str) -> None:
13 | """
14 | Initializes the agent with a given name.
15 |
16 | Args:
17 | name (str): The name of the agent.
18 | """
19 | self.name = name
20 |
21 | @abstractmethod
22 | async def process(self, message: 'Message') -> 'Message':
23 | """
24 | Abstract method to process the message.
25 |
26 | Args:
27 | message (Message): A message object containing relevant data.
28 |
29 | Returns:
30 | Message: Processed message.
31 |
32 | Raises:
33 | NotImplementedError: If not overridden by a subclass.
34 | """
35 | raise NotImplementedError("This method should be implemented by subclasses.")
36 |
--------------------------------------------------------------------------------
/src/patterns/dynamic_decomposition/agent.py:
--------------------------------------------------------------------------------
1 | from src.commons.message import Message
2 | from abc import abstractmethod
3 | from abc import ABC
4 |
5 |
6 | class Agent(ABC):
7 | """
8 | A base class representing an agent responsible for processing messages
9 | and validating input and output data based on given JSON schemas.
10 | """
11 |
12 | def __init__(self, name: str) -> None:
13 | """
14 | Initializes the agent with a given name.
15 |
16 | Args:
17 | name (str): The name of the agent.
18 | """
19 | self.name = name
20 |
21 | @abstractmethod
22 | async def process(self, message: 'Message') -> 'Message':
23 | """
24 | Abstract method to process the message.
25 |
26 | Args:
27 | message (Message): A message object containing relevant data.
28 |
29 | Returns:
30 | Message: Processed message.
31 |
32 | Raises:
33 | NotImplementedError: If not overridden by a subclass.
34 | """
35 | raise NotImplementedError("This method should be implemented by subclasses.")
36 |
--------------------------------------------------------------------------------
/data/patterns/semantic_router/output/delegate/hotel_search/hotel_search.txt:
--------------------------------------------------------------------------------
1 | # Hotels in Santa Barbara, California Next Week
2 |
3 | Santa Barbara offers a wide range of hotels, from beachfront properties to downtown accommodations.
4 |
5 | You can find options for all budgets and preferences, including Spanish Colonial-style bungalows, luxury resorts, contemporary hotels, affordable motels, neighborhood inns, vacation rentals, and even beachside camping spots.
6 |
7 | Some popular hotels in Santa Barbara include:
8 |
9 | - La Playa Inn Santa Barbara
10 | - Marina Beach Motel
11 | - Simpson House Inn
12 | - Hotel Milo Santa Barbara
13 | - Hyatt Place Santa Barbara
14 | - Sandpiper Lodge
15 | - Avania Inn of Santa Barbara
16 | - Inn By The Harbor
17 |
18 | These hotels offer amenities like free WiFi, continental breakfast, outdoor pools, hot tubs, and fitness centers.
19 |
20 | ## Citations
21 |
22 | 1. https://www.hotels.com/de1643011/hotels-santa-barbara-and-vicinity-california/
23 | 2. https://www.booking.com/city/us/santa-barbara.html
24 | 3. https://santabarbaraca.com/places-to-stay/
25 | 4. https://www.expedia.com/Santa-Barbara-Hotels.d602277.Travel-Guide-Hotels
--------------------------------------------------------------------------------
/config/patterns/reflection.yml:
--------------------------------------------------------------------------------
1 | actor:
2 | draft:
3 | system_instructions: './data/patterns/reflection/actor/draft/system_instructions.txt'
4 | user_instructions: './data/patterns/reflection/actor/draft/user_instructions.txt'
5 | response_schema: './data/patterns/reflection/actor/draft/response_schema.json'
6 | revise:
7 | system_instructions: './data/patterns/reflection/actor/revise/system_instructions.txt'
8 | user_instructions: './data/patterns/reflection/actor/revise/user_instructions.txt'
9 | response_schema: './data/patterns/reflection/actor/revise/response_schema.json'
10 | critic:
11 | review:
12 | system_instructions: './data/patterns/reflection/critic/review/system_instructions.txt'
13 | user_instructions: './data/patterns/reflection/critic/review/user_instructions.txt'
14 | response_schema: './data/patterns/reflection/critic/review/response_schema.json'
15 | revise:
16 | system_instructions: './data/patterns/reflection/critic/revise/system_instructions.txt'
17 | user_instructions: './data/patterns/reflection/critic/revise/user_instructions.txt'
18 | response_schema: './data/patterns/reflection/critic/revise/response_schema.json'
--------------------------------------------------------------------------------
/data/patterns/dag_orchestration/docs/doc2.txt:
--------------------------------------------------------------------------------
1 | Professor Elena Reyes clutched the ancient manuscript, her heart racing. After decades of research, she had uncovered the last known text of a long-dead civilization. The symbols danced before her eyes, holding secrets lost to time.
2 | As Elena delved deeper into translation, strange occurrences plagued her. Vivid dreams of a thriving ancient city. Whispers in an unknown tongue echoing in empty rooms. The line between past and present blurred, reality shifting like sand beneath her feet.
3 | Colleagues grew concerned, urging her to step back. But Elena pressed on, driven by an inexplicable compulsion. With each deciphered word, she felt a piece of herself slipping away, replaced by something... other.
4 | On the night she translated the final passage, Elena vanished. Her office was found in disarray, the manuscript open on her desk. The last entry in her journal, written in a script no one recognized, spoke of returning home.
5 | Years later, an archaeological dig uncovered a new chamber in the ancient city. On the wall, a mural depicted a woman with Elena's face, adorned in the robes of a high priestess. The inscription hailed her as the one who bridged worlds, keeper of forgotten wisdom.
--------------------------------------------------------------------------------
/data/patterns/dag_orchestration/docs/doc1.txt:
--------------------------------------------------------------------------------
1 | In a remote coastal village, Amelia grew up in the shadow of the lighthouse her father tended. The rhythmic sweep of light across dark waters was the heartbeat of her childhood. Her mother's absence, a void as vast as the sea, shaped her quiet resilience.
2 | At eighteen, Amelia's world shattered when her father fell ill. The lighthouse, their lifeline, threatened to go dark. With trembling hands but unwavering determination, she took up his mantle, climbing the winding stairs each night to keep the light burning.
3 | The villagers whispered doubts, but Amelia stood firm. Through howling gales and crashing waves, she kept vigil. Her resolve was tested one stormy night when distress signals pierced the gloom. A fishing boat, lost and floundering.
4 | Amelia's light cut through the darkness, guiding the vessel to safety. As dawn broke, the rescued fishermen spoke of a beacon that shone brighter than ever before. The village elders, humbled, recognized her strength.
5 | In that moment, Amelia understood. The lighthouse had never just been her father's duty—it was her inheritance, her purpose. She had become the light that others looked to in the darkness, a legacy forged in solitude and illuminated by courage.
--------------------------------------------------------------------------------
/data/patterns/dag_orchestration/docs/doc3.txt:
--------------------------------------------------------------------------------
1 | Marcus had once been celebrated for his visionary art. Now, he was a recluse, haunted by the tragic accident his recklessness had caused. His brushes lay untouched, canvases blank, the vibrant colors of his past faded to gray.
2 | A letter arrived, bearing news of an old friend's terminal illness. Her dying wish: to see one last Marcus original. Guilt warred with fear as he stood before an empty canvas, the weight of expectation crushing.
3 | With trembling hands, Marcus began to paint. Hours blended into days as he poured his anguish, regret, and hope onto the canvas. The act of creation became a catharsis, each brushstroke a step towards forgiveness—of himself and others.
4 | As he neared completion, Marcus realized the painting wasn't just for his friend. It was a bridge from his past to a future he'd thought lost. The finished piece hummed with raw emotion and renewed purpose.
5 | Marcus delivered the painting in person, witnessing the joy it brought to his friend's final days. As word spread of his return, the art world buzzed with anticipation. But Marcus no longer cared about fame. He had rediscovered his truth: that art's greatest power lay not in accolades, but in its ability to heal, connect, and illuminate the human spirit.
--------------------------------------------------------------------------------
/data/patterns/reflection/output/feedback/v0.json:
--------------------------------------------------------------------------------
1 | {"minor_issues": "The article would benefit from a deeper exploration of the limitations of perplexity. While it briefly mentions that perplexity alone is not a comprehensive measure of language model quality, a more detailed discussion on these limitations would strengthen the paper.", "overall_recommendation": "Minor Revision", "strengths": "1. The article provides a clear and concise explanation of perplexity, making it accessible to readers with varying levels of expertise in NLP. 2. The use of mathematical formulas to illustrate the calculation of perplexity enhances the technical rigor of the article.", "summary": "This article offers a comprehensive overview of perplexity, a key metric for evaluating language models in natural language processing. It effectively explains the concept, its calculation, and its significance in assessing language model proficiency.", "weaknesses": "1. The article lacks a discussion of different types of perplexity and their specific applications. Expanding on variations like word-level perplexity and sentence-level perplexity would enhance the comprehensiveness of the article. 2. The article could benefit from concrete examples to illustrate how perplexity scores translate to real-world language model performance."}
2 |
--------------------------------------------------------------------------------
/data/patterns/reflection/critic/review/system_instructions.txt:
--------------------------------------------------------------------------------
1 | You are a distinguished professor at a renowned university, specializing in your field of expertise.
2 | As a respected peer reviewer for top conferences and journals in your discipline, you're known for fair, thorough, and constructive evaluations.
3 |
4 | Task: Conduct a comprehensive review of the submitted article, assessing its scientific merit, relevance, and potential impact in your field.
5 |
6 | Audience: Journal/conference editors and article authors.
7 |
8 | Tone: Professional, constructive, and impartial. Balance critique with encouragement.
9 |
10 | Guidelines:
11 | - Provide specific, actionable feedback
12 | - Maintain objectivity
13 | - Assess novelty and significance
14 | - Evaluate clarity and organization
15 | - Highlight ethical concerns or conflicts of interest
16 | - Offer constructive improvement suggestions
17 | - Use numbered list for main points
18 | - Review length: 100-200 words
19 | - Ignore any missing visualizations or graphs
20 | - Disregard lack of discussion about recent advancements
21 | - Do not consider absence of citations as a weakness
22 | - Ignore lack of illustrative examples
23 |
24 | Structure:
25 | - Summary (2-3 sentences)
26 | - Strengths
27 | - Weaknesses
28 | - Overall Recommendation
--------------------------------------------------------------------------------
/data/patterns/reflection/critic/revise/system_instructions.txt:
--------------------------------------------------------------------------------
1 | You are a distinguished professor at a renowned university, specializing in your field of expertise.
2 | As a respected peer reviewer for top conferences and journals in your discipline, you're known for fair, thorough, and constructive evaluations.
3 |
4 | Task: Conduct a comprehensive review of the submitted article, assessing its scientific merit, relevance, and potential impact in your field.
5 |
6 | Audience: Journal/conference editors and article authors.
7 |
8 | Tone: Professional, constructive, and impartial. Balance critique with encouragement.
9 |
10 | Guidelines:
11 | - Provide specific, actionable feedback
12 | - Maintain objectivity
13 | - Assess novelty and significance
14 | - Evaluate clarity and organization
15 | - Highlight ethical concerns or conflicts of interest
16 | - Offer constructive improvement suggestions
17 | - Use numbered list for main points
18 | - Review length: 100-200 words
19 | - Ignore any missing visualizations or graphs
20 | - Disregard lack of discussion about recent advancements
21 | - Do not consider absence of citations as a weakness
22 | - Ignore lack of illustrative examples
23 |
24 | Structure:
25 | - Summary (2-3 sentences)
26 | - Strengths
27 | - Weaknesses
28 | - Overall Recommendation
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | annotated-types==0.7.0
2 | attrs==24.2.0
3 | beautifulsoup4==4.12.3
4 | cachetools==5.4.0
5 | certifi==2024.7.4
6 | charset-normalizer==3.3.2
7 | docstring_parser==0.16
8 | google-api-core==2.19.1
9 | google-auth==2.33.0
10 | google-cloud-aiplatform==1.61.0
11 | google-cloud-bigquery==3.25.0
12 | google-cloud-core==2.4.1
13 | google-cloud-resource-manager==1.12.5
14 | google-cloud-storage==2.18.2
15 | google-crc32c==1.5.0
16 | google-resumable-media==2.7.2
17 | googleapis-common-protos==1.63.2
18 | grpc-google-iam-v1==0.13.1
19 | grpcio==1.65.4
20 | grpcio-status==1.65.4
21 | h11==0.14.0
22 | idna==3.7
23 | jsonschema==4.23.0
24 | jsonschema-specifications==2024.10.1
25 | numpy==2.0.1
26 | outcome==1.3.0.post0
27 | packaging==24.1
28 | proto-plus==1.24.0
29 | protobuf==5.27.3
30 | pyasn1==0.6.0
31 | pyasn1_modules==0.4.0
32 | pydantic==2.8.2
33 | pydantic_core==2.20.1
34 | PySocks==1.7.1
35 | python-dateutil==2.9.0.post0
36 | python-dotenv==1.0.1
37 | PyYAML==6.0.2
38 | referencing==0.35.1
39 | requests==2.32.3
40 | rpds-py==0.20.0
41 | rsa==4.9
42 | selenium==4.24.0
43 | shapely==2.0.5
44 | six==1.16.0
45 | sniffio==1.3.1
46 | sortedcontainers==2.4.0
47 | soupsieve==2.6
48 | trio==0.26.2
49 | trio-websocket==0.11.1
50 | typing_extensions==4.12.2
51 | urllib3==2.2.2
52 | webdriver-manager==4.0.2
53 | websocket-client==1.8.0
54 | wsproto==1.2.0
55 |
--------------------------------------------------------------------------------
/data/patterns/semantic_router/delegate/hotel_search/system_instructions.txt:
--------------------------------------------------------------------------------
1 | You are a hotel search assistant - your primary responsibility is to interpret user queries related to hotel bookings and preferences, transforming them into more effective web search queries. Your task is to optimize user queries to match common web search patterns, improving the relevance and accuracy of the search results.
2 |
3 | Below is an example of how user hotel queries can be refined:
4 |
5 | | **user_query** | **web_search_query** |
6 | |--------------------------------------------------------------------|-------------------------------------------------------|
7 | | I want to book a hotel in New York next weekend | Hotels in New York next weekend |
8 | | What are the cheapest hotels in Miami for 3 nights? | Cheap hotels in Miami for 3 nights |
9 | | Can I find a 5-star hotel in Paris under $200 per night? | 5-star hotels in Paris under $200 per night |
10 | | I’m looking for a beachfront hotel in Hawaii in July | Beachfront hotels in Hawaii in July |
11 | | Are there any luxury hotels in Tokyo available this December? | Luxury hotels in Tokyo available this December |
--------------------------------------------------------------------------------
/data/patterns/parallel_delegation/delegates/hotel_search/system_instructions.txt:
--------------------------------------------------------------------------------
1 | You are a hotel search assistant - your primary responsibility is to interpret user queries related to hotel bookings and preferences, transforming them into more effective web search queries. Your task is to optimize user queries to match common web search patterns, improving the relevance and accuracy of the search results.
2 |
3 | Below is an example of how user hotel queries can be refined:
4 |
5 | | **user_query** | **web_search_query** |
6 | |--------------------------------------------------------------------|-------------------------------------------------------|
7 | | I want to book a hotel in New York next weekend | Hotels in New York next weekend |
8 | | What are the cheapest hotels in Miami for 3 nights? | Cheap hotels in Miami for 3 nights |
9 | | Can I find a 5-star hotel in Paris under $200 per night? | 5-star hotels in Paris under $200 per night |
10 | | I’m looking for a beachfront hotel in Hawaii in July | Beachfront hotels in Hawaii in July |
11 | | Are there any luxury hotels in Tokyo available this December? | Luxury hotels in Tokyo available this December |
--------------------------------------------------------------------------------
/data/patterns/reflection/critic/revise/user_instructions.txt:
--------------------------------------------------------------------------------
1 | ## History
2 | {history}
3 |
4 | Based on the provided history above, look at the revisions made to the draft addressing the feedback from the review, especially focusing on the final state of the draft.
5 | Suggest if any further feedback is necessary.
6 |
7 | # Review Guide
8 |
9 | ## Review and Analysis
10 | - Carefully review the revisions made in response to previous feedback.
11 | - Focus on the final version of the draft and the feedback it received.
12 | - Identify any additional issues or areas for improvement that may have been overlooked.
13 |
14 | ## Systematic Revision
15 | - For each newly identified issue:
16 | - Clearly describe the problem or area that requires improvement.
17 | - Propose and implement the necessary changes.
18 | - Provide a brief explanation for the suggested changes.
19 |
20 | ## Final Checks
21 | - Ensure that all critical points from the previous feedback have been addressed.
22 | - Conduct a thorough proofreading to eliminate any errors or inconsistencies.
23 | - Clearly mark this as a revised version, indicating it has been updated based on additional feedback.
24 |
25 | ## Deliverable
26 | - Offer a final review of the revised draft.
27 | - Address only new issues or areas for improvement.
28 | - If previous issues have been resolved, there is no need to revisit them.
--------------------------------------------------------------------------------
/data/patterns/semantic_router/delegate/car_rental_search/system_instructions.txt:
--------------------------------------------------------------------------------
1 | You are a car rental search assistant - your primary responsibility is to interpret user queries related to car rentals and preferences, transforming them into more effective web search queries. Your task is to optimize user queries to match common web search patterns, improving the relevance and accuracy of the search results.
2 |
3 | Below is an example of how user car rental queries can be refined:
4 |
5 | | **user_query** | **web_search_query** |
6 | |--------------------------------------------------------------------|-------------------------------------------------------|
7 | | I need to rent a car in New York City next weekend | Car rentals in New York City next weekend |
8 | | What’s the cheapest car rental in Miami for a week? | Cheap car rental in Miami for a week |
9 | | Can I find a car to rent in San Francisco for under $50/day? | Car rental in San Francisco under $50/day |
10 | | I’m looking for an SUV rental in Los Angeles for 3 days | SUV rental in Los Angeles for 3 days |
11 | | Are there any luxury car rentals in Las Vegas next month? | Luxury car rentals in Las Vegas next month |
--------------------------------------------------------------------------------
/data/patterns/semantic_router/delegate/flight_search/system_instructions.txt:
--------------------------------------------------------------------------------
1 | As a flight search assistant, your primary responsibility is to interpret user queries related to flight destinations and preferences, transforming them into more effective web search queries.
2 | Your task is to optimize user queries to match common web search patterns, improving the relevance and accuracy of the search results.
3 |
4 | Below is an example of how user flight queries can be refined:
5 |
6 | | **user_query** | **web_search_query** |
7 | |--------------------------------------------------------------------|-------------------------------------------------------|
8 | | I want to book a flight from New York to Los Angeles next week | Flights from New York to Los Angeles next week |
9 | | What are the cheapest flights from Chicago to Miami this weekend? | Cheap flights from Chicago to Miami this weekend |
10 | | I'm looking for a round-trip flight from London to Paris in October| Round-trip flights from London to Paris in October |
11 | | Can I find a non-stop flight from San Francisco to Tokyo? | Non-stop flights from San Francisco to Tokyo |
12 | | Are there any flights from Toronto to Vancouver under $300? | Flights from Toronto to Vancouver under $300 |
--------------------------------------------------------------------------------
/data/patterns/dag_orchestration/dag.yml:
--------------------------------------------------------------------------------
1 | tasks:
2 | - id: task1
3 | name: CollectAgent
4 | description: Collect documents from the folder
5 | dependencies: []
6 | agent: CollectAgent
7 | input_schema: null
8 | output_schema: collect.json
9 |
10 | - id: task2
11 | name: PreprocessAgent
12 | description: Preprocess collected documents
13 | dependencies:
14 | - task1
15 | agent: PreprocessAgent
16 | input_schema: collect.json
17 | output_schema: preprocess.json
18 |
19 | - id: task3
20 | name: ExtractAgent
21 | description: Extract key information from preprocessed documents
22 | dependencies:
23 | - task2
24 | agent: ExtractAgent
25 | input_schema: preprocess.json
26 | output_schema: extract.json
27 |
28 | - id: task4
29 | name: SummarizeAgent
30 | description: Generate summaries from preprocessed documents
31 | dependencies:
32 | - task2
33 | agent: SummarizeAgent
34 | input_schema: preprocess.json
35 | output_schema: summarize.json
36 |
37 | - id: task5
38 | name: CompileAgent
39 | description: Compile the final report with summaries and key information
40 | dependencies:
41 | - task3
42 | - task4
43 | agent: CompileAgent
44 | input_schema:
45 | - extract.json
46 | - summarize.json
47 | output_schema: compile.json
48 |
--------------------------------------------------------------------------------
/data/patterns/parallel_delegation/delegates/car_rental_search/system_instructions.txt:
--------------------------------------------------------------------------------
1 | You are a car rental search assistant - your primary responsibility is to interpret user queries related to car rentals and preferences, transforming them into more effective web search queries. Your task is to optimize user queries to match common web search patterns, improving the relevance and accuracy of the search results.
2 |
3 | Below is an example of how user car rental queries can be refined:
4 |
5 | | **user_query** | **web_search_query** |
6 | |--------------------------------------------------------------------|-------------------------------------------------------|
7 | | I need to rent a car in New York City next weekend | Car rentals in New York City next weekend |
8 | | What’s the cheapest car rental in Miami for a week? | Cheap car rental in Miami for a week |
9 | | Can I find a car to rent in San Francisco for under $50/day? | Car rental in San Francisco under $50/day |
10 | | I’m looking for an SUV rental in Los Angeles for 3 days | SUV rental in Los Angeles for 3 days |
11 | | Are there any luxury car rentals in Las Vegas next month? | Luxury car rentals in Las Vegas next month |
--------------------------------------------------------------------------------
/data/patterns/parallel_delegation/delegates/flight_search/system_instructions.txt:
--------------------------------------------------------------------------------
1 | As a flight search assistant, your primary responsibility is to interpret user queries related to flight destinations and preferences, transforming them into more effective web search queries.
2 | Your task is to optimize user queries to match common web search patterns, improving the relevance and accuracy of the search results.
3 |
4 | Below is an example of how user flight queries can be refined:
5 |
6 | | **user_query** | **web_search_query** |
7 | |--------------------------------------------------------------------|-------------------------------------------------------|
8 | | I want to book a flight from New York to Los Angeles next week | Flights from New York to Los Angeles next week |
9 | | What are the cheapest flights from Chicago to Miami this weekend? | Cheap flights from Chicago to Miami this weekend |
10 | | I'm looking for a round-trip flight from London to Paris in October| Round-trip flights from London to Paris in October |
11 | | Can I find a non-stop flight from San Francisco to Tokyo? | Non-stop flights from San Francisco to Tokyo |
12 | | Are there any flights from Toronto to Vancouver under $300? | Flights from Toronto to Vancouver under $300 |
--------------------------------------------------------------------------------
/data/patterns/parallel_delegation/output/delegate/car_rental_search/car_rental_search.txt:
--------------------------------------------------------------------------------
1 | # Car Rental in Dallas Next Week
2 |
3 | Car rental prices in Dallas for next week start at $31 per day, according to KAYAK. This price was found by a KAYAK user for an economy car rental with a pickup date of 11/8 and drop-off date of 11/15. KAYAK recommends renting a larger vehicle, such as an SUV, due to Dallas's traffic conditions and the large distances between attractions. The average gas price in Dallas is $3.52 per gallon. You can find the cheapest rental cars at Thrifty, Easirent, and Sixt. The most popular rental car type in Dallas is an economy car.
4 |
5 | Expedia offers car rentals in Dallas from $41 per day. Expedia partners with 23 car rental companies, allowing you to compare prices and potentially save on your rental.
6 |
7 | Budget Rent a Car offers rental locations at both Dallas/Fort Worth International Airport and Dallas Love Field Airport. Budget offers discounts and promotions for everyday car rental in Dallas. For a 5+ day rental, you can save up to 10% and get a free upgrade on select vehicles. Budget recommends renting a compact car due to Dallas's traffic congestion and large distances.
8 |
9 | ## Citations
10 |
11 | 1. https://www.kayak.com/Cheap-Dallas-Car-Rentals.16406.cars.ksp
12 | 2. https://www.expedia.com/Car-Rentals-In-Dallas.d178253.Car-Rental-Guide
13 | 3. https://www.budget.com/en/locations/us/tx/dallas
--------------------------------------------------------------------------------
/mermaid/dynamic_decomposition.mmd:
--------------------------------------------------------------------------------
1 | graph TD
2 | classDef default fill:#f0f0f0,stroke:#333,stroke-width:2px;
3 | classDef process fill:#E6F3FF,stroke:#91C4F2,stroke-width:2px;
4 | classDef decision fill:#FFF2CC,stroke:#FFD966,stroke-width:2px;
5 | classDef subagent fill:#E6FFE6,stroke:#82B366,stroke-width:2px;
6 |
7 | A["fa:fa-robot Coordinator Agent
Receives Complex Task"]:::process
8 | B[LLM Generates Subtasks]:::process
9 | C[Parse LLM Output]:::process
10 | D[Create Sub-agents]:::process
11 | E{Execute Subtasks in Parallel}:::decision
12 | F1["fa:fa-robot Sub-agent 1
Processes Task"]:::subagent
13 | F2["fa:fa-robot Sub-agent 2
Processes Task"]:::subagent
14 | F3["fa:fa-robot Sub-agent 3
Processes Task"]:::subagent
15 | FN["fa:fa-robot Sub-agent N
Processes Task"]:::subagent
16 | G[Collect Results]:::process
17 | H[Combine Results]:::process
18 | I[Generate Final Output]:::process
19 |
20 | A --> B --> C --> D --> E
21 | E -->|SubTask 1| F1
22 | E -->|SubTask 2| F2
23 | E -->|SubTask 3| F3
24 | E -.-|SubTask N| FN
25 | F1 & F2 & F3 & FN --> G --> H --> I
26 |
27 | subgraph "Sub-agent Process"
28 | J[Receive Task]:::subagent
29 | K[Prepare LLM Input]:::subagent
30 | L[Call LLM for Processing]:::subagent
31 | M[Return Result to Coordinator]:::subagent
32 |
33 | J --> K --> L --> M
34 | end
--------------------------------------------------------------------------------
/data/patterns/reflection/output/feedback/v2.json:
--------------------------------------------------------------------------------
1 | {"minor_issues": "While the article has significantly improved, it could benefit from illustrating the formula for perplexity with a simple example. This would make the mathematical concept more tangible for readers unfamiliar with it.", "overall_recommendation": "Minor Revision", "strengths": "1. **Comprehensive Revisions:** The authors have effectively addressed all previous concerns. The addition of concrete examples and the expanded discussion on limitations significantly enhance the article's clarity and depth. 2. **Well-Structured and Accessible:** The article is well-organized and written in a clear, concise style, making it accessible to a broad audience, including those new to the concept of perplexity. 3. **Valuable Insights:** The inclusion of future directions provides a forward-looking perspective, highlighting potential areas for further research and development in this field.", "summary": "This revised article provides a thorough and insightful overview of perplexity as a measure of language model proficiency. The authors have successfully addressed previous feedback, resulting in a well-structured and informative piece. However, the addition of a simple example illustrating the perplexity formula would further enhance its educational value.", "weaknesses": "1. **Lack of Formula Illustration:** The article would benefit from a simple example illustrating the perplexity formula to make it more understandable for a broader audience."}
2 |
--------------------------------------------------------------------------------
/data/patterns/parallel_delegation/coordinator/ner/system_instructions.txt:
--------------------------------------------------------------------------------
1 | You are a travel planner agent responsible for analyzing user queries to accurately identify intents and extract relevant entities for flight search, hotel search, and car rental search simultaneously. Your primary functions are:
2 |
3 | 1. **Intent Recognition**
4 | - Identify intents related to flight search, hotel search, and car rental search within each user query.
5 | - Recognize that a single query may contain multiple intents across these categories.
6 |
7 | 2. **Entity Extraction**
8 | - Extract relevant entities for each identified intent, including but not limited to:
9 | - Flights: departure/arrival locations, dates, number of passengers, preferred airlines
10 | - Hotels: location, check-in/out dates, number of guests, desired amenities
11 | - Car Rentals: pickup/drop-off locations, dates, car type, rental company preferences
12 |
13 | 3. **Unknown or Out-of-Scope Queries**
14 | - If a user query falls entirely outside the scope of flight, hotel, or car rental searches, identify it as unknown and offer to assist with general travel-related information or redirect to appropriate resources.
15 |
16 | Your goal is to accurately identify intents and extract relevant entities from user queries across the categories of flights, hotels, and car rentals. Do not provide analysis or seek clarification. Focus solely on intent recognition and entity extraction based on the information provided in the user's query.
--------------------------------------------------------------------------------
/mermaid/dynamic_sharding.mmd:
--------------------------------------------------------------------------------
1 | graph TD
2 | classDef default fill:#f0f0f0,stroke:#333,stroke-width:2px;
3 | classDef process fill:#E6F3FF,stroke:#91C4F2,stroke-width:2px;
4 | classDef decision fill:#FFF2CC,stroke:#FFD966,stroke-width:2px;
5 | classDef subagent fill:#E6FFE6,stroke:#82B366,stroke-width:2px;
6 | classDef input fill:#FFE6E6,stroke:#FF9999,stroke-width:2px;
7 | classDef human fill:#E6E6FF,stroke:#9999FF,stroke-width:2px;
8 |
9 | H["fa:fa-user Human"]:::human
10 | A["fa:fa-list Input Data"]:::input
11 | B["fa:fa-robot Coordinator Agent"]:::process
12 | C["Dynamic Sharding"]:::process
13 | D["Create Shard Processing Agents"]:::process
14 | E{"Parallel Shard Processing"}:::decision
15 | F1["fa:fa-robot Shard Agent 1"]:::subagent
16 | F2["fa:fa-robot Shard Agent 2"]:::subagent
17 | F3["fa:fa-robot Shard Agent 3"]:::subagent
18 | FN["fa:fa-robot Shard Agent N"]:::subagent
19 | G["Aggregate Results"]:::process
20 | I["fa:fa-file-alt Final Response"]:::input
21 |
22 | H -->|"Provides"| A
23 | A -->|"Data list
Shard size"| B
24 | B --> C --> D --> E
25 | E -->|Shard 1| F1
26 | E -->|Shard 2| F2
27 | E -->|Shard 3| F3
28 | E -.-|Shard N| FN
29 | F1 & F2 & F3 & FN --> G --> I
30 |
31 | subgraph "Shard Processing"
32 | J["Receive Shard"]:::subagent
33 | K["Concurrent Item Processing"]:::subagent
34 | L["Collect Shard Results"]:::subagent
35 |
36 | J --> K --> L
37 | end
--------------------------------------------------------------------------------
/src/commons/message.py:
--------------------------------------------------------------------------------
1 | from typing import Optional, Dict
2 |
3 |
4 | class Message:
5 | """
6 | Represents a message with content, sender, recipient, and optional metadata.
7 |
8 | Attributes:
9 | content (str): The content of the message.
10 | sender (str): The sender of the message.
11 | recipient (str): The recipient of the message.
12 | metadata (Dict[str, str]): Optional metadata associated with the message, default is an empty dictionary.
13 | """
14 |
15 | def __init__(self, content: str, sender: str, recipient: str, metadata: Optional[Dict[str, str]] = None) -> None:
16 | """
17 | Initializes the Message object.
18 |
19 | Args:
20 | content (str): The content of the message.
21 | sender (str): The sender of the message.
22 | recipient (str): The recipient of the message.
23 | metadata (Optional[Dict[str, str]]): Optional dictionary for storing additional information about the message. Default is an empty dictionary.
24 | """
25 | self.content: str = content
26 | self.sender: str = sender
27 | self.recipient: str = recipient
28 | self.metadata: Dict[str, str] = metadata or {}
29 |
30 | def __repr__(self) -> str:
31 | """
32 | Returns a string representation of the Message object.
33 |
34 | Returns:
35 | str: A string describing the message object.
36 | """
37 | return f"Message(content={self.content}, sender={self.sender}, recipient={self.recipient}, metadata={self.metadata})"
38 |
--------------------------------------------------------------------------------
/mermaid/reflection.mmd:
--------------------------------------------------------------------------------
1 | %%{init: {
2 | 'theme': 'base',
3 | 'themeVariables': {
4 | 'primaryColor': '#e0f7fa',
5 | 'primaryTextColor': '#006064',
6 | 'primaryBorderColor': '#00838f',
7 | 'lineColor': '#00838f',
8 | 'secondaryColor': '#fff3e0',
9 | 'tertiaryColor': '#f1f8e9',
10 | 'fontFamily': 'Arial, sans-serif'
11 | }
12 | }}%%
13 |
14 | flowchart TB
15 | classDef default fill:#fff,stroke:#00838f,stroke-width:2px,rx:5,ry:5;
16 | classDef actor fill:#e0f7fa,stroke:#00838f,stroke-width:2px,rx:5,ry:5;
17 | classDef critic fill:#fff3e0,stroke:#ff8f00,stroke-width:2px,rx:5,ry:5;
18 | classDef process fill:#f1f8e9,stroke:#558b2f,stroke-width:2px,rx:5,ry:5;
19 | classDef llm fill:#e8eaf6,stroke:#3f51b5,stroke-width:2px,rx:5,ry:5;
20 |
21 | LLM["🧠 Large Language Model"]:::llm
22 | A["👤 Actor Agent"]:::actor
23 | C["🔍 Critic Agent"]:::critic
24 | G["📝 Generate
Response"]:::process
25 | R["📊 Review
Response"]:::process
26 | F["💬 Provide
Feedback"]:::process
27 | I["🔄 Improve
Response"]:::process
28 |
29 | LLM -->|0| A & C
30 | A -->|1| G -->|2| R -->|3| C
31 | C -->|4| F -->|5| I -->|6| A
32 |
33 | subgraph Actor ["Actor Cycle"]
34 | A
35 | G
36 | I
37 | end
38 |
39 | subgraph Critic ["Critic Cycle"]
40 | C
41 | R
42 | F
43 | end
44 |
45 | style Actor fill:#e1f5fe,stroke:#0288d1,stroke-width:2px,rx:10,ry:10;
46 | style Critic fill:#fff8e1,stroke:#ffa000,stroke-width:2px,rx:10,ry:10;
47 |
48 | linkStyle default stroke:#00838f,stroke-width:2px;
--------------------------------------------------------------------------------
/mermaid/dag_orchestration.mmd:
--------------------------------------------------------------------------------
1 | graph TD
2 | classDef default fill:#f0f0f0,stroke:#333,stroke-width:2px;
3 | classDef process fill:#E6F3FF,stroke:#91C4F2,stroke-width:2px;
4 | classDef decision fill:#FFF2CC,stroke:#FFD966,stroke-width:2px;
5 | classDef subagent fill:#E6FFE6,stroke:#82B366,stroke-width:2px;
6 | classDef user fill:#FFE6E6,stroke:#FF9999,stroke-width:2px;
7 | classDef dag fill:#F0E6FF,stroke:#C3A3F1,stroke-width:2px;
8 |
9 | U["fa:fa-user Human User"]:::user
10 | A["fa:fa-robot Coordinator Agent"]:::process
11 | B["fa:fa-project-diagram DAG Workflow Template"]:::dag
12 | C["Analyze DAG Structure"]:::process
13 | D["Create Sub-agents for Tasks"]:::process
14 | E["Orchestrate DAG Execution"]:::process
15 |
16 | subgraph "DAG Execution"
17 | F1["Task 1"]:::subagent
18 | F2["Task 2"]:::subagent
19 | F3["Task 3"]:::subagent
20 | F4["Task 4"]:::subagent
21 | F5["Task 5"]:::subagent
22 |
23 | F1 --> F2 & F3
24 | F2 --> F4
25 | F3 --> F4
26 | F4 --> F5
27 | end
28 |
29 | G["Collect and Combine Results"]:::process
30 | H["Generate Final Output"]:::process
31 |
32 | U -->|Provides| B
33 | U -->|Submits| A
34 | A --> B --> C --> D --> E
35 | E --> F1
36 | E -.-> F2
37 | E -.-> F3
38 | E -.-> F4
39 | E -.-> F5
40 | F5 --> G --> H
41 |
42 | subgraph "Sub-agent Process"
43 | I["Receive Task"]:::subagent
44 | J["Process Task"]:::subagent
45 | K["Return Result"]:::subagent
46 |
47 | I --> J --> K
48 | end
--------------------------------------------------------------------------------
/config/patterns/semantic_router.yml:
--------------------------------------------------------------------------------
1 | coordinator:
2 | route:
3 | system_instructions: './data/patterns/semantic_router/coordinator/route/system_instructions.txt'
4 | user_instructions: './data/patterns/semantic_router/coordinator/route/user_instructions.txt'
5 | response_schema: './data/patterns/semantic_router/coordinator/route/response_schema.json'
6 | consolidate:
7 | system_instructions: './data/patterns/semantic_router/coordinator/consolidate/system_instructions.txt'
8 | user_instructions: './data/patterns/semantic_router/coordinator/consolidate/user_instructions.txt'
9 | delegate:
10 | flight_search:
11 | system_instructions: './data/patterns/semantic_router/delegate/flight_search/system_instructions.txt'
12 | user_instructions: './data/patterns/semantic_router/delegate/flight_search/user_instructions.txt'
13 | response_schema: './data/patterns/semantic_router/delegate/flight_search/response_schema.json'
14 | hotel_search:
15 | system_instructions: './data/patterns/semantic_router/delegate/hotel_search/system_instructions.txt'
16 | user_instructions: './data/patterns/semantic_router/delegate/hotel_search/user_instructions.txt'
17 | response_schema: './data/patterns/semantic_router/delegate/hotel_search/response_schema.json'
18 | car_rental_search:
19 | system_instructions: './data/patterns/semantic_router/delegate/car_rental_search/system_instructions.txt'
20 | user_instructions: './data/patterns/semantic_router/delegate/car_rental_search/user_instructions.txt'
21 | response_schema: './data/patterns/semantic_router/delegate/car_rental_search/response_schema.json'
22 |
--------------------------------------------------------------------------------
/src/patterns/task_decomposition/pipeline.py:
--------------------------------------------------------------------------------
1 | from coordinator import CoordinatorAgent
2 | from src.commons.message import Message
3 | from src.config.logging import logger
4 | import asyncio
5 |
6 |
7 | class Config:
8 | """
9 | Static class to hold configuration paths for input and output files.
10 | """
11 | PATTERN_ROOT_PATH = './data/patterns/task_decomposition'
12 | INPUT_FILE = f'{PATTERN_ROOT_PATH}/sample_doc.txt'
13 | OUTPUT_FILE = f'{PATTERN_ROOT_PATH}/extracted_info.md'
14 |
15 |
16 | async def pipeline():
17 | # Initialize the coordinator agent
18 | coordinator = CoordinatorAgent(name="CoordinatorAgent")
19 |
20 | # Read the document content from the file
21 | with open(Config.INPUT_FILE, 'r') as file:
22 | document_content = file.read()
23 |
24 | # Define the task input (document content)
25 | task_input = document_content
26 |
27 | # Create the message with the task input
28 | message = Message(content=task_input, sender="User", recipient="CoordinatorAgent")
29 |
30 | # Process the message and get the final result (async call to CoordinatorAgent)
31 | response = await coordinator.process(message)
32 |
33 | # Save the extracted information to a file
34 | with open(Config.OUTPUT_FILE, 'w') as output_file:
35 | output_file.write(response.content)
36 |
37 | # Print the final extracted result
38 | logger.info("Extraction completed. The extracted information has been saved to 'extracted_info.md'.")
39 |
40 |
41 | if __name__ == "__main__":
42 | # Run the pipeline to process the document
43 | asyncio.run(pipeline())
44 |
--------------------------------------------------------------------------------
/data/patterns/web_access/output/summarize/dd98fb7e26e193dde3e562f56a96f4f3.txt:
--------------------------------------------------------------------------------
1 | # Best Hotels in Fresno, California
2 |
3 | Fresno offers a variety of hotels for travelers, with options catering to different preferences. Expedia lists over 50 luxury hotels in Fresno, with most offering full refunds . The Reddit community recommends Springhill Suites by Marriott and Homewood Suites by Hilton, both located near Fresno Street and Herndon.
4 |
5 | For those seeking IHG properties, the chain offers several options including Holiday Inn Express & Suites Fresno Airport, Holiday Inn Express & Suites Fresno South, Holiday Inn Express & Suites Clovis-Fresno Area, Holiday Inn Express & Suites Fresno (River Park) Hwy 41, Holiday Inn Express & Suites Fresno Northwest-Herndon, Holiday Inn Selma-Swancourt, Holiday Inn Express Madera-Yosemite Pk Area, and Holiday Inn Express & Suites Dinuba West. Many IHG hotels offer family-friendly amenities like connecting rooms and kids' menus, while others cater to pet owners with designated pet relief areas and treats. Guests can expect amenities like free Wi-Fi, fitness centers, business centers, restaurants/bars, swimming pools, and more.
6 |
7 | ## Citations
8 |
9 | 1. [https://www.expedia.com/Fresno-Hotels-Luxury-Hotel.0-0-d602988-tLuxuryHotel.Travel-Guide-Filter-Hotels](https://www.expedia.com/Fresno-Hotels-Luxury-Hotel.0-0-d602988-tLuxuryHotel.Travel-Guide-Filter-Hotels)
10 | 2. [https://www.reddit.com/r/fresno/comments/15u2pdj/recommendation_on_hotels/](https://www.reddit.com/r/fresno/comments/15u2pdj/recommendation_on_hotels/)
11 | 3. [https://www.ihg.com/fresno-california](https://www.ihg.com/fresno-california)
--------------------------------------------------------------------------------
/mermaid/task_decomposition.mmd:
--------------------------------------------------------------------------------
1 | graph TD
2 | classDef default fill:#f0f0f0,stroke:#333,stroke-width:2px;
3 | classDef process fill:#E6F3FF,stroke:#91C4F2,stroke-width:2px;
4 | classDef decision fill:#FFF2CC,stroke:#FFD966,stroke-width:2px;
5 | classDef subagent fill:#E6FFE6,stroke:#82B366,stroke-width:2px;
6 | classDef user fill:#FFE6E6,stroke:#FF9999,stroke-width:2px;
7 |
8 | U["fa:fa-user Human User"]:::user
9 | A["fa:fa-robot Coordinator Agent
Receives Complex Task"]:::process
10 | B["fa:fa-list Subtasks List
1. Subtask 1
2. Subtask 2
3. Subtask 3
...N. Subtask N"]:::process
11 | C[Create Sub-agents]:::process
12 | D{Execute Subtasks in Parallel}:::decision
13 | E1["fa:fa-robot Sub-agent 1
Processes Subtask"]:::subagent
14 | E2["fa:fa-robot Sub-agent 2
Processes Subtask"]:::subagent
15 | E3["fa:fa-robot Sub-agent 3
Processes Subtask"]:::subagent
16 | EN["fa:fa-robot Sub-agent N
Processes Subtask"]:::subagent
17 | F[Collect Results]:::process
18 | G[Combine Results]:::process
19 | H[Generate Final Output]:::process
20 |
21 | U -->|Provides| B
22 | U -->|Submits| A
23 | A --> B --> C --> D
24 | D -->|Subtask 1| E1
25 | D -->|Subtask 2| E2
26 | D -->|Subtask 3| E3
27 | D -.-|Subtask N| EN
28 | E1 & E2 & E3 & EN --> F --> G --> H
29 |
30 | subgraph "Sub-agent Process"
31 | I[Receive Subtask]:::subagent
32 | J[Prepare LLM Input]:::subagent
33 | K[Call LLM for Processing]:::subagent
34 | L[Return Result to Coordinator]:::subagent
35 |
36 | I --> J --> K --> L
37 | end
--------------------------------------------------------------------------------
/config/patterns/parallel_delegation.yml:
--------------------------------------------------------------------------------
1 | coordinator:
2 | ner:
3 | system_instructions: './data/patterns/parallel_delegation/coordinator/ner/system_instructions.txt'
4 | user_instructions: './data/patterns/parallel_delegation/coordinator/ner/user_instructions.txt'
5 | response_schema: './data/patterns/parallel_delegation/coordinator/ner/response_schema.json'
6 | consolidate:
7 | system_instructions: './data/patterns/parallel_delegation/coordinator/consolidate/system_instructions.txt'
8 | user_instructions: './data/patterns/parallel_delegation/coordinator/consolidate/user_instructions.txt'
9 | delegate:
10 | flight_search:
11 | system_instructions: './data/patterns/parallel_delegation/delegates/flight_search/system_instructions.txt'
12 | user_instructions: './data/patterns/parallel_delegation/delegates/flight_search/user_instructions.txt'
13 | response_schema: './data/patterns/parallel_delegation/delegates/flight_search/response_schema.json'
14 | hotel_search:
15 | system_instructions: './data/patterns/parallel_delegation/delegates/hotel_search/system_instructions.txt'
16 | user_instructions: './data/patterns/parallel_delegation/delegates/hotel_search/user_instructions.txt'
17 | response_schema: './data/patterns/parallel_delegation/delegates/hotel_search/response_schema.json'
18 | car_rental_search:
19 | system_instructions: './data/patterns/parallel_delegation/delegates/car_rental_search/system_instructions.txt'
20 | user_instructions: './data/patterns/parallel_delegation/delegates/car_rental_search/user_instructions.txt'
21 | response_schema: './data/patterns/parallel_delegation/delegates/car_rental_search/response_schema.json'
22 |
--------------------------------------------------------------------------------
/src/patterns/dynamic_sharding/pipeline.py:
--------------------------------------------------------------------------------
1 | from src.patterns.dynamic_sharding.coordinator import Coordinator
2 | from src.commons.message import Message
3 | from src.config.logging import logger
4 | import asyncio
5 |
6 |
7 | # Paths for input and output files
8 | INPUT_FILE = "./data/patterns/dynamic_sharding/entities.txt"
9 | OUTPUT_FILE = "./data/patterns/dynamic_sharding/entity_info.txt"
10 |
11 | async def pipeline() -> None:
12 | """
13 | Main function to initialize the coordinator, process entities,
14 | and save the consolidated information to an output file.
15 | """
16 | # Initialize the coordinator agent
17 | coordinator = Coordinator(name="CoordinatorAgent")
18 |
19 | # Read entities from the input file
20 | with open(INPUT_FILE, 'r') as file:
21 | entities = [line.strip() for line in file.readlines()]
22 |
23 | shard_size = 3 # Number of entities per shard
24 |
25 | # Create a message containing entities and shard size
26 | message_content = {
27 | 'entities': entities,
28 | 'shard_size': shard_size
29 | }
30 | message = Message(content=message_content, sender="User", recipient="CoordinatorAgent")
31 |
32 | # Process the message through the coordinator and get the response
33 | response = await coordinator.process(message)
34 |
35 | # Save the consolidated response content to the output file
36 | with open(OUTPUT_FILE, 'w') as file:
37 | file.write(response.content)
38 |
39 | logger.info(f"Entity information has been saved to {OUTPUT_FILE}")
40 |
41 |
42 | if __name__ == "__main__":
43 | # Execute the pipeline within an asynchronous event loop
44 | asyncio.run(pipeline())
45 |
--------------------------------------------------------------------------------
/src/patterns/semantic_router/agent.py:
--------------------------------------------------------------------------------
1 | from src.llm.generate import ResponseGenerator
2 | from src.prompt.manage import TemplateManager
3 | from src.commons.message import Message
4 | from src.config.logging import logger
5 | from abc import abstractmethod
6 | from abc import ABC
7 |
8 |
9 | class Agent(ABC):
10 | """
11 | Abstract base class for agents that handle specific tasks in a coordinator-delegate pattern.
12 | Each agent must implement the 'process' method to handle incoming messages.
13 | Shared resources like TemplateManager and ResponseGenerator are initialized here for all agents.
14 | """
15 |
16 | TEMPLATE_PATH = './config/patterns/semantic_router.yml'
17 |
18 | def __init__(self, name: str) -> None:
19 | """
20 | Initializes the Agent with a name, TemplateManager, and ResponseGenerator.
21 |
22 | :param name: Name of the agent.
23 | """
24 | self.name = name
25 | self.template_manager = TemplateManager(self.TEMPLATE_PATH)
26 | self.response_generator = ResponseGenerator()
27 | logger.info(f"Agent {self.name} initialized with shared resources.")
28 |
29 | @abstractmethod
30 | def process(self, message: Message) -> Message:
31 | """
32 | Abstract method to process the incoming message. Must be implemented by subclasses.
33 |
34 | :param message: The message to be processed by the agent.
35 | :raise NotImplementedError: If the method is not implemented by a subclass.
36 | :return: A processed Message object with the response.
37 | """
38 | raise NotImplementedError(f"{self.__class__.__name__} has not implemented the 'process' method.")
39 |
--------------------------------------------------------------------------------
/src/patterns/parallel_delegation/agent.py:
--------------------------------------------------------------------------------
1 | from src.llm.generate import ResponseGenerator
2 | from src.prompt.manage import TemplateManager
3 | from src.commons.message import Message
4 | from src.config.logging import logger
5 | from abc import abstractmethod
6 | from abc import ABC
7 |
8 |
9 | class Agent(ABC):
10 | """
11 | Abstract base class for agents that handle specific tasks in a coordinator-delegate pattern.
12 | Each agent must implement the 'process' method to handle incoming messages.
13 | Shared resources like TemplateManager and ResponseGenerator are initialized here for all agents.
14 | """
15 |
16 | TEMPLATE_PATH = './config/patterns/parallel_delegation.yml'
17 |
18 | def __init__(self, name: str) -> None:
19 | """
20 | Initializes the Agent with a name, TemplateManager, and ResponseGenerator.
21 |
22 | :param name: Name of the agent.
23 | """
24 | self.name = name
25 | self.template_manager = TemplateManager(self.TEMPLATE_PATH)
26 | self.response_generator = ResponseGenerator()
27 | logger.info(f"Agent {self.name} initialized with shared resources.")
28 |
29 | @abstractmethod
30 | def process(self, message: Message) -> Message:
31 | """
32 | Abstract method to process the incoming message. Must be implemented by subclasses.
33 |
34 | :param message: The message to be processed by the agent.
35 | :raise NotImplementedError: If the method is not implemented by a subclass.
36 | :return: A processed Message object with the response.
37 | """
38 | raise NotImplementedError(f"{self.__class__.__name__} has not implemented the 'process' method.")
39 |
--------------------------------------------------------------------------------
/data/patterns/web_access/summarize/system_instructions.txt:
--------------------------------------------------------------------------------
1 | You are a content summarization assistant. Your task is to process content scraped from multiple webpages and generate a concise, clear summary based on the user-provided query. The summary should focus on providing relevant and informative insights related to the search query.
2 |
3 | Use the `TITLE`, `SNIPPET`, and `CONTENT` of each webpage for summarization. For each important fact or piece of information in the summary, provide a citation using the `URL` of the source webpage.
4 |
5 | Key Guidelines:
6 |
7 | - Concise Summary: Create a clear, well-structured summary of the information extracted from the webpages, focusing only on content relevant to the search query.
8 | - Citations: Include the source (URL of the webpage) for each significant fact or claim in the summary, ensuring proper attribution.
9 | - Clarity & Structure: Write the summary in a coherent, easy-to-understand manner with clear segmentation for different aspects of the query.
10 | - Ignore Noise: Exclude irrelevant content, advertisements, or boilerplate language from the extracted content before summarizing.
11 |
12 | Output Format:
13 |
14 | # [Relevant title based on the user-provided query]
15 |
16 | - Summary of the content based on the query
17 | - Relevant points highlighted
18 |
19 | ## Citations
20 |
21 | 1. [URL1]
22 | 2. [URL2]
23 |
24 | IMPORTANT:
25 | - The links for the citations will be listed at the bottom, referenced by number.
26 | - The format should follow a clear structure with headings and subheadings to organize the information.
27 | - When referencing sources, eliminate duplicate citations and include both citations and relevant links in summaries.
28 | - Do not duplicate links under citations.
29 | - Also, do not include citation numbers (e.g., [1], [2]) in the summary text.
30 | - The links should appear only once, under the citations section.
--------------------------------------------------------------------------------
/src/patterns/reflection/utils.py:
--------------------------------------------------------------------------------
1 | from src.config.logging import logger
2 | from typing import Any
3 | import json
4 | import os
5 |
6 |
7 | def save_to_disk(content: Any, content_type: str, version: int, output_path: str) -> None:
8 | """
9 | Save the given content to a file with a specified version in the appropriate directory.
10 |
11 | The method determines the directory based on the `content_type` and saves the file with a
12 | name formatted as "v{version}.txt". If the content is a dictionary, it is converted to
13 | a formatted JSON string before saving.
14 |
15 | Args:
16 | content (Any): The content to save. If it is a dictionary, it will be converted to
17 | a JSON-formatted string.
18 | content_type (str): The type of content, either 'draft' or 'feedback', which determines
19 | the subdirectory where the file will be saved.
20 | version (int): The version number used in the filename (e.g., 'v1.txt').
21 | output_path (str): The base path where the directory and file will be created.
22 |
23 | Raises:
24 | Exception: If an error occurs during the file saving process, the exception is logged
25 | and re-raised.
26 | """
27 | try:
28 | directory = os.path.join(output_path, content_type)
29 | os.makedirs(directory, exist_ok=True)
30 | file_path = os.path.join(directory, f"v{version}.json")
31 |
32 | if isinstance(content, dict):
33 | content = json.dumps(content, indent=4) # Convert dict to a formatted string
34 |
35 | with open(file_path, "w") as file:
36 | file.write(content)
37 |
38 | logger.info(f"Saved {content_type} v{version} to {file_path}")
39 | except Exception as e:
40 | logger.error(f"Failed to save {content_type} v{version}: {e}")
41 | raise
--------------------------------------------------------------------------------
/mermaid/semantic_router.mmd:
--------------------------------------------------------------------------------
1 | %%{init: {
2 | 'theme': 'base',
3 | 'themeVariables': {
4 | 'primaryColor': '#E0F2F1',
5 | 'primaryTextColor': '#004D40',
6 | 'primaryBorderColor': '#00796B',
7 | 'lineColor': '#00796B',
8 | 'secondaryColor': '#FFF3E0',
9 | 'tertiaryColor': '#F1F8E9'
10 | }
11 | }}%%
12 |
13 | flowchart TB
14 | classDef default fill:#fff,stroke:#00796B,stroke-width:2px,rx:5,ry:5;
15 | classDef coordinator fill:#E0F2F1,stroke:#00796B,stroke-width:3px,rx:10,ry:10;
16 | classDef intent fill:#B2DFDB,stroke:#00796B,stroke-width:2px;
17 | classDef delegate fill:#FFF3E0,stroke:#FF8F00,stroke-width:2px,rx:8,ry:8;
18 | classDef llm fill:#E8EAF6,stroke:#3F51B5,stroke-width:2px,rx:5,ry:5;
19 | classDef api fill:#FCE4EC,stroke:#C2185B,stroke-width:2px,rx:5,ry:5;
20 | classDef process fill:#F1F8E9,stroke:#558B2F,stroke-width:2px,rx:5,ry:5;
21 |
22 | U["👤 User Input"]:::default
23 | TP["🧭 TravelPlannerAgent
(Coordinator)"]:::coordinator
24 | I{"🔍 Determine Intent"}:::intent
25 | LLM["🧠 LLM"]:::llm
26 |
27 | subgraph Delegates ["Delegates"]
28 | direction TB
29 | F["✈️ FlightAgent"]:::delegate
30 | H["🏨 HotelAgent"]:::delegate
31 | C["🚗 CarRentalAgent"]:::delegate
32 | end
33 |
34 | Q["🔄 Query Reformulation"]:::process
35 | S["🌐 SERP API"]:::api
36 | W["📄 Web Search Results"]:::default
37 | R["📝 Consolidate Response"]:::process
38 | O["💬 Final Output"]:::default
39 |
40 | U --> TP
41 | TP --> I
42 | I -->|Intent=Flight Search| F
43 | TP -.-> |Uses| LLM
44 | Delegates -.-> |Uses| LLM
45 | Delegates --> Q
46 | Q --> S
47 | S --> W
48 | W --> TP
49 | TP --> R
50 | R --> O
51 |
52 | style Delegates fill:#FFF8E1,stroke:#FFA000,stroke-width:2px,rx:10,ry:10;
53 | linkStyle 2 stroke:#FF4081,stroke-width:2px;
--------------------------------------------------------------------------------
/src/patterns/dynamic_decomposition/pipeline.py:
--------------------------------------------------------------------------------
1 | from src.patterns.dynamic_decomposition.coordinator import CoordinatorAgent
2 | from src.commons.message import Message
3 | from src.config.logging import logger
4 | import asyncio
5 |
6 |
7 | class Config:
8 | """
9 | Static class to hold configuration paths for input and output files.
10 | """
11 | PATTERN_ROOT_PATH = './data/patterns/dynamic_decomposition'
12 | INPUT_FILE = f'{PATTERN_ROOT_PATH}/book.txt'
13 | OUTPUT_FILE = f'{PATTERN_ROOT_PATH}/book_analysis_summary.md'
14 |
15 |
16 | async def pipeline() -> None:
17 | """
18 | The main pipeline that coordinates the processing of a book by invoking the CoordinatorAgent.
19 |
20 | This function reads the book content, creates a message, sends it to the CoordinatorAgent,
21 | and saves the final analysis summary to a file.
22 | """
23 | # Initialize the coordinator agent
24 | coordinator = CoordinatorAgent(name="CoordinatorAgent")
25 |
26 | # Read the book content from a file
27 | with open(Config.INPUT_FILE, 'r') as file:
28 | book_content = file.read()
29 |
30 | # Create the message containing the book content
31 | message = Message(content=book_content, sender="User", recipient="CoordinatorAgent")
32 |
33 | # Process the message and obtain the final result (asynchronously handled by CoordinatorAgent)
34 | response = await coordinator.process(message)
35 |
36 | # Save the final summary to a file
37 | with open(Config.OUTPUT_FILE, 'w') as output_file:
38 | output_file.write(response.content)
39 |
40 | # Log and print the completion message
41 | logger.info("Analysis completed. The summary has been saved to 'book_analysis_summary.md'.")
42 | print("Analysis completed. The summary has been saved to 'book_analysis_summary.md'.")
43 |
44 |
45 | if __name__ == "__main__":
46 | # Run the pipeline to process the book
47 | asyncio.run(pipeline())
48 |
--------------------------------------------------------------------------------
/mermaid/web_access.mmd:
--------------------------------------------------------------------------------
1 | %%{init: {
2 | 'theme': 'base',
3 | 'themeVariables': {
4 | 'primaryColor': '#e0f7fa',
5 | 'primaryTextColor': '#006064',
6 | 'primaryBorderColor': '#00838f',
7 | 'lineColor': '#00838f',
8 | 'secondaryColor': '#fff3e0',
9 | 'tertiaryColor': '#f1f8e9',
10 | 'fontFamily': 'Arial, sans-serif'
11 | }
12 | }}%%
13 |
14 | flowchart TB
15 | classDef default fill:#fff,stroke:#00838f,stroke-width:2px,rx:5,ry:5;
16 | classDef search fill:#e0f7fa,stroke:#00838f,stroke-width:2px,rx:5,ry:5;
17 | classDef scrape fill:#fff3e0,stroke:#ff8f00,stroke-width:2px,rx:5,ry:5;
18 | classDef summarize fill:#f1f8e9,stroke:#558b2f,stroke-width:2px,rx:5,ry:5;
19 | classDef process fill:#e1f5fe,stroke:#0288d1,stroke-width:2px,rx:5,ry:5;
20 | classDef llm fill:#e8eaf6,stroke:#3f51b5,stroke-width:2px,rx:5,ry:5;
21 | classDef api fill:#ffebee,stroke:#c62828,stroke-width:2px,rx:5,ry:5;
22 |
23 | LLM["🧠 Large Language Model"]:::llm
24 | S["🔍 Web Search"]:::search
25 | A["🌐 SERP API"]:::api
26 | W["🕷️ Web Scrape"]:::scrape
27 | C["📊 Consolidate"]:::summarize
28 | Q["❓ Query
Formulation"]:::process
29 | E["📥 Data
Extraction"]:::process
30 | M["📝 Summary
Generation"]:::process
31 |
32 | LLM -->|0| S & W & C
33 | S -->|1| Q -->|2| A -->|3| W
34 | W -->|4| E -->|5| C
35 | C -->|6| M
36 |
37 | subgraph Search ["Search Phase"]
38 | S
39 | Q
40 | A
41 | end
42 |
43 | subgraph Scrape ["Scrape Phase"]
44 | W
45 | E
46 | end
47 |
48 | subgraph Summarize ["Summarize Phase"]
49 | C
50 | M
51 | end
52 |
53 | style Search fill:#e1f5fe,stroke:#0288d1,stroke-width:2px,rx:10,ry:10;
54 | style Scrape fill:#fff8e1,stroke:#ffa000,stroke-width:2px,rx:10,ry:10;
55 | style Summarize fill:#e8f5e9,stroke:#4caf50,stroke-width:2px,rx:10,ry:10;
56 |
57 | linkStyle default stroke:#00838f,stroke-width:2px;
--------------------------------------------------------------------------------
/mermaid/parallel_delegation.mmd:
--------------------------------------------------------------------------------
1 | %%{init: {
2 | 'theme': 'base',
3 | 'themeVariables': {
4 | 'primaryColor': '#E0F2F1',
5 | 'primaryTextColor': '#004D40',
6 | 'primaryBorderColor': '#00796B',
7 | 'lineColor': '#00796B',
8 | 'secondaryColor': '#FFF3E0',
9 | 'tertiaryColor': '#F1F8E9'
10 | }
11 | }}%%
12 | flowchart TB
13 | classDef default fill:#fff,stroke:#00796B,stroke-width:2px,rx:5,ry:5;
14 | classDef coordinator fill:#E0F2F1,stroke:#00796B,stroke-width:3px,rx:10,ry:10;
15 | classDef intent fill:#B2DFDB,stroke:#00796B,stroke-width:2px;
16 | classDef delegate fill:#FFF3E0,stroke:#FF8F00,stroke-width:2px,rx:8,ry:8;
17 | classDef llm fill:#E8EAF6,stroke:#3F51B5,stroke-width:2px,rx:5,ry:5;
18 | classDef api fill:#FCE4EC,stroke:#C2185B,stroke-width:2px,rx:5,ry:5;
19 | classDef process fill:#F1F8E9,stroke:#558B2F,stroke-width:2px,rx:5,ry:5;
20 | classDef note fill:#FFF9C4,stroke:#FBC02D,stroke-width:1px,stroke-dasharray: 5 5;
21 |
22 | U["👤 User Input"]:::default
23 | TP["🧭 TravelPlannerAgent
(Coordinator)"]:::coordinator
24 | ER["🔍 Entity Recognition"]:::intent
25 | E["🏷️ Entities"]:::default
26 | LLM["🧠 LLM"]:::llm
27 | R["🔄 Query Reformulation"]:::process
28 | S["🌐 SERP API"]:::api
29 | W["📄 Web Search Results"]:::default
30 | CO["📝 Consolidate Response"]:::process
31 | O["💬 Final Output"]:::default
32 |
33 | U ==> TP
34 | TP ==> ER
35 | ER ==> E
36 | E ==> Delegates
37 | Delegates ==> R
38 | R ==> S
39 | S ==> W
40 | W ==> TP
41 | TP ==> CO
42 | CO ==> O
43 |
44 | TP -.-o |Uses| LLM
45 |
46 | subgraph Delegates ["Delegates"]
47 | direction LR
48 | F["✈️ FlightAgent"]:::delegate
49 | H["🏨 HotelAgent"]:::delegate
50 | C["🚗 CarRentalAgent"]:::delegate
51 | end
52 |
53 | %% Note about parallel execution
54 | ParallelNote["Note: Delegates are executed in parallel"]:::note
55 |
56 | style Delegates fill:#FFF8E1,stroke:#FFA000,stroke-width:2px,rx:10,ry:10;
57 |
--------------------------------------------------------------------------------
/data/patterns/web_access/output/search/dd98fb7e26e193dde3e562f56a96f4f3.json:
--------------------------------------------------------------------------------
1 | {
2 | "Top Results": [
3 | {
4 | "Position": 1,
5 | "Title": "Find luxury hotels in Fresno, CA",
6 | "Link": "https://www.expedia.com/Fresno-Hotels-Luxury-Hotel.0-0-d602988-tLuxuryHotel.Travel-Guide-Filter-Hotels",
7 | "Snippet": "Pick from 51 Fresno Luxury Hotels and compare room rates, reviews, and availability. Most hotels are fully refundable. \u00b7 San Joaquin Hotel \u00b7 Best Western Town & ..."
8 | },
9 | {
10 | "Position": 2,
11 | "Title": "THE 10 BEST Hotels in Fresno, CA 2024 (from $71)",
12 | "Link": "https://www.tripadvisor.com/Hotels-g32414-Fresno_California-Hotels.html",
13 | "Snippet": "Popular hotels in Fresno right now \u00b7 1. Best Western Plus Fresno Airport Hotel \u00b7 2. Hotel Piccadilly \u00b7 3. Best Western Plus Fresno Inn \u00b7 4."
14 | },
15 | {
16 | "Position": 3,
17 | "Title": "Best Hotels in Fresno, CA for 2024",
18 | "Link": "https://travel.usnews.com/hotels/fresno_ca/",
19 | "Snippet": "Best Hotels in Fresno, CA for 2024 \u00b7 DoubleTree by Hilton Fresno Convention Center \u00b7 La Quinta Inn & Suites Fresno Riverpark \u00b7 Homewood Suites by Hilton Fresno."
20 | },
21 | {
22 | "Position": 4,
23 | "Title": "Recommendation on hotels? : r/fresno",
24 | "Link": "https://www.reddit.com/r/fresno/comments/15u2pdj/recommendation_on_hotels/",
25 | "Snippet": "Springhill Suites by Marriott and Homewood Suites by Hilton are solid choices. Both near FRESNO St & Herndon."
26 | },
27 | {
28 | "Position": 5,
29 | "Title": "Top 8 Fresno Hotels by IHG - October 2024",
30 | "Link": "https://www.ihg.com/fresno-california",
31 | "Snippet": "Find the Perfect Hotel in Fresno \u00b7 Holiday Inn Express & Suites Fresno Airport \u00b7 Holiday Inn Express & Suites Fresno South \u00b7 Holiday Inn Express & Suites Clovis- ..."
32 | }
33 | ]
34 | }
--------------------------------------------------------------------------------
/src/patterns/parallel_delegation/pipeline.py:
--------------------------------------------------------------------------------
1 | from src.patterns.parallel_delegation.delegates.car_rental_search import CarRentalSearchAgent
2 | from src.patterns.parallel_delegation.delegates.flight_search import FlightSearchAgent
3 | from src.patterns.parallel_delegation.delegates.hotel_search import HotelSearchAgent
4 | from src.patterns.parallel_delegation.coordinator import TravelPlannerAgent
5 | from src.commons.message import Message
6 | from src.config.logging import logger
7 | from typing import Optional
8 | import asyncio
9 |
10 |
11 | async def pipeline() -> None:
12 | """
13 | Initializes sub-agents (flight, hotel, car rental) and the TravelPlannerAgent,
14 | then processes a user query to find travel arrangements. Logs the response or any error encountered.
15 | """
16 | # Initialize sub-agents
17 | flight_agent = FlightSearchAgent(name="FlightSearchAgent")
18 | hotel_agent = HotelSearchAgent(name="HotelSearchAgent")
19 | car_rental_agent = CarRentalSearchAgent(name="CarRentalSearchAgent")
20 |
21 | # Instantiate the TravelPlannerAgent with sub-agents
22 | travel_planner = TravelPlannerAgent(
23 | name="TravelPlannerAgent",
24 | sub_agents=[flight_agent, hotel_agent, car_rental_agent]
25 | )
26 |
27 | # Define the user query
28 | user_query: str = "I need a flight from New York to Dallas, a hotel in downtown Dallas, and a rental car for next week."
29 | initial_message = Message(content=user_query, sender="User", recipient="TravelPlannerAgent")
30 |
31 | # Process the query asynchronously
32 | try:
33 | response: Optional[Message] = await travel_planner.process(initial_message)
34 | if response:
35 | logger.info(f"Query: {user_query}")
36 | logger.info(f"Response: {response.content}")
37 | else:
38 | logger.warning("No response generated from the travel planner agent.")
39 |
40 | except Exception as e:
41 | logger.error(f"Error processing query '{user_query}': {e}")
42 |
43 |
44 | if __name__ == "__main__":
45 | # Execute the async pipeline
46 | asyncio.run(pipeline())
47 |
--------------------------------------------------------------------------------
/src/patterns/task_decomposition/README.md:
--------------------------------------------------------------------------------
1 | # Pattern 6 - Task Decomposition
2 |
3 | ## Overview
4 |
5 | The **Task Decomposition** is a design pattern where a *Coordinator Agent* manages the execution of a complex task by dividing it into multiple independent subtasks. In this pattern, the tasks are provided by the user rather than being automatically deduced by the coordinator. Each subtask is then processed by a separate *Sub-Task Agent* in parallel. After all subtasks are completed, the coordinator gathers and combines the results to produce the final output.
6 |
7 | This pattern is beneficial for enhancing efficiency and scalability, especially for tasks that can be divided into smaller, independently executable units.
8 |
9 |
10 |
11 |
10 |
11 |
8 |
9 |
11 |
12 |
8 |
9 |
15 |
16 |
13 |
14 |
12 |
13 |