Showing preview only (1,811K chars total). Download the full file or copy to clipboard to get everything.
Repository: awslabs/agent-squad
Branch: main
Commit: 8048bcf308fc
Files: 347
Total size: 1.7 MB
Directory structure:
gitextract_g9hwz37y/
├── .gitattributes
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ ├── bug_report.yml
│ │ └── feature_request.yml
│ ├── PULL_REQUEST_TEMPLATE.md
│ └── workflows/
│ ├── npm-publish.yml
│ ├── on-docs-update.yml
│ ├── on-issue-opened.yml
│ ├── on-push.yml
│ ├── pr-issue-link-checker.yml
│ ├── py-run-tests.yml
│ ├── pypi-publish.yml
│ ├── ts-run-lint.yml
│ ├── ts-run-security-checks.yml
│ └── ts-run-tests.yml
├── .gitignore
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── docs/
│ ├── .gitignore
│ ├── README.md
│ ├── astro.config.mjs
│ ├── package.json
│ ├── src/
│ │ ├── components/
│ │ │ └── code.astro
│ │ ├── content/
│ │ │ ├── config.ts
│ │ │ └── docs/
│ │ │ ├── agents/
│ │ │ │ ├── built-in/
│ │ │ │ │ ├── amazon-bedrock-agent.mdx
│ │ │ │ │ ├── anthropic-agent.mdx
│ │ │ │ │ ├── bedrock-flows-agent.mdx
│ │ │ │ │ ├── bedrock-inline-agent.mdx
│ │ │ │ │ ├── bedrock-llm-agent.mdx
│ │ │ │ │ ├── bedrock-translator-agent.mdx
│ │ │ │ │ ├── chain-agent.mdx
│ │ │ │ │ ├── comprehend-filter-agent.mdx
│ │ │ │ │ ├── lambda-agent.mdx
│ │ │ │ │ ├── lex-bot-agent.mdx
│ │ │ │ │ ├── openai-agent.mdx
│ │ │ │ │ └── supervisor-agent.mdx
│ │ │ │ ├── custom-agents.mdx
│ │ │ │ ├── overview.mdx
│ │ │ │ └── tools.mdx
│ │ │ ├── classifiers/
│ │ │ │ ├── built-in/
│ │ │ │ │ ├── anthropic-classifier.mdx
│ │ │ │ │ ├── bedrock-classifier.mdx
│ │ │ │ │ └── openai-classifier.mdx
│ │ │ │ ├── custom-classifier.mdx
│ │ │ │ └── overview.mdx
│ │ │ ├── cookbook/
│ │ │ │ ├── examples/
│ │ │ │ │ ├── api-agent.mdx
│ │ │ │ │ ├── chat-chainlit-app.md
│ │ │ │ │ ├── chat-demo-app.md
│ │ │ │ │ ├── ecommerce-support-simulator.md
│ │ │ │ │ ├── fast-api-streaming.md
│ │ │ │ │ ├── ollama-agent.mdx
│ │ │ │ │ ├── ollama-classifier.mdx
│ │ │ │ │ ├── python-local-demo.md
│ │ │ │ │ └── typescript-local-demo.md
│ │ │ │ ├── lambda/
│ │ │ │ │ ├── aws-lambda-nodejs.md
│ │ │ │ │ └── aws-lambda-python.md
│ │ │ │ ├── monitoring/
│ │ │ │ │ ├── agent-overlap.md
│ │ │ │ │ ├── logging.mdx
│ │ │ │ │ └── observability.mdx
│ │ │ │ ├── patterns/
│ │ │ │ │ ├── cost-efficient.md
│ │ │ │ │ └── multi-lingual.md
│ │ │ │ └── tools/
│ │ │ │ ├── math-operations.md
│ │ │ │ └── weather-api.mdx
│ │ │ ├── general/
│ │ │ │ ├── faq.md
│ │ │ │ ├── how-it-works.md
│ │ │ │ ├── introduction.md
│ │ │ │ └── quickstart.mdx
│ │ │ ├── index.mdx
│ │ │ ├── orchestrator/
│ │ │ │ └── overview.mdx
│ │ │ ├── retrievers/
│ │ │ │ ├── built-in/
│ │ │ │ │ └── bedrock-kb-retriever.mdx
│ │ │ │ ├── custom-retriever.mdx
│ │ │ │ └── overview.md
│ │ │ └── storage/
│ │ │ ├── custom.mdx
│ │ │ ├── dynamodb.mdx
│ │ │ ├── in-memory.mdx
│ │ │ ├── overview.md
│ │ │ └── sql.mdx
│ │ ├── env.d.ts
│ │ └── styles/
│ │ ├── custom.css
│ │ ├── font.css
│ │ ├── landing.css
│ │ └── terminal.css
│ └── tsconfig.json
├── examples/
│ ├── bedrock-flows/
│ │ ├── python/
│ │ │ └── main.py
│ │ ├── readme.md
│ │ └── typescript/
│ │ └── main.ts
│ ├── bedrock-inline-agents/
│ │ ├── python/
│ │ │ └── main.py
│ │ └── typescript/
│ │ └── main.ts
│ ├── bedrock-prompt-routing/
│ │ ├── main.py
│ │ └── readme.md
│ ├── chat-chainlit-app/
│ │ ├── .gitignore
│ │ ├── README.md
│ │ ├── agents.py
│ │ ├── app.py
│ │ ├── chainlit.md
│ │ ├── ollamaAgent.py
│ │ └── requirements.txt
│ ├── chat-demo-app/
│ │ ├── .gitignore
│ │ ├── .npmignore
│ │ ├── README.md
│ │ ├── bin/
│ │ │ └── chat-demo-app.ts
│ │ ├── cdk.json
│ │ ├── jest.config.js
│ │ ├── lambda/
│ │ │ ├── auth/
│ │ │ │ ├── index.mjs
│ │ │ │ └── package.json
│ │ │ ├── find-my-name/
│ │ │ │ └── lambda.py
│ │ │ ├── multi-agent/
│ │ │ │ ├── index.ts
│ │ │ │ ├── math_tool.ts
│ │ │ │ ├── prompts.ts
│ │ │ │ └── weather_tool.ts
│ │ │ └── sync_bedrock_knowledgebase/
│ │ │ └── lambda.py
│ │ ├── lib/
│ │ │ ├── CustomResourcesLambda/
│ │ │ │ ├── aoss-index-create.ts
│ │ │ │ ├── data-source-sync.ts
│ │ │ │ └── permission-validation.ts
│ │ │ ├── airlines.yaml
│ │ │ ├── bedrock-agent-construct.ts
│ │ │ ├── chat-demo-app-stack.ts
│ │ │ ├── constants.ts
│ │ │ ├── knowledge-base-construct.ts
│ │ │ ├── lex-agent-construct.ts
│ │ │ ├── user-interface-stack.ts
│ │ │ └── utils/
│ │ │ ├── OpensearchServerlessHelper.ts
│ │ │ └── utils.ts
│ │ ├── package.json
│ │ ├── scripts/
│ │ │ └── download.js
│ │ ├── test/
│ │ │ └── chat-demo-app.ts
│ │ ├── tsconfig.json
│ │ └── ui/
│ │ ├── .babelrc
│ │ ├── .gitignore
│ │ ├── .vscode/
│ │ │ ├── extensions.json
│ │ │ └── launch.json
│ │ ├── README.md
│ │ ├── astro.config.mjs
│ │ ├── package.json
│ │ ├── src/
│ │ │ ├── components/
│ │ │ │ ├── ChatWindow.tsx
│ │ │ │ ├── emojiHelper.ts
│ │ │ │ └── loadingScreen.tsx
│ │ │ ├── pages/
│ │ │ │ └── index.astro
│ │ │ └── utils/
│ │ │ ├── ApiClient.ts
│ │ │ └── amplifyConfig.ts
│ │ ├── tailwind.config.cjs
│ │ └── tsconfig.json
│ ├── ecommerce-support-simulator/
│ │ ├── .gitignore
│ │ ├── .npmignore
│ │ ├── README.md
│ │ ├── bin/
│ │ │ └── ai-ecommerce-support-simulator.ts
│ │ ├── cdk.json
│ │ ├── graphql/
│ │ │ ├── Query.sendMessage.js
│ │ │ ├── schema.graphql
│ │ │ ├── sendResponse.js
│ │ │ └── sendResponsePipeline.js
│ │ ├── jest.config.js
│ │ ├── lambda/
│ │ │ ├── customerMessage/
│ │ │ │ ├── agents.ts
│ │ │ │ ├── index.ts
│ │ │ │ └── sqsLogger.ts
│ │ │ ├── sendResponse/
│ │ │ │ └── index.ts
│ │ │ └── supportMessage/
│ │ │ └── index.ts
│ │ ├── lib/
│ │ │ ├── ai-ecommerce-support-simulator-stack.ts
│ │ │ └── utils/
│ │ │ └── utils.ts
│ │ ├── package.json
│ │ ├── resources/
│ │ │ └── ui/
│ │ │ ├── .gitignore
│ │ │ ├── .vscode/
│ │ │ │ ├── extensions.json
│ │ │ │ └── launch.json
│ │ │ ├── README.md
│ │ │ ├── astro.config.mjs
│ │ │ ├── package.json
│ │ │ ├── public/
│ │ │ │ └── mock_data.json
│ │ │ ├── src/
│ │ │ │ ├── components/
│ │ │ │ │ ├── ChatMode.tsx
│ │ │ │ │ ├── EmailMode.tsx
│ │ │ │ │ ├── SupportSimulator.tsx
│ │ │ │ │ └── email-templates.json
│ │ │ │ ├── consts.ts
│ │ │ │ ├── content/
│ │ │ │ │ └── config.ts
│ │ │ │ ├── layouts/
│ │ │ │ │ └── Layout.astro
│ │ │ │ ├── pages/
│ │ │ │ │ └── index.astro
│ │ │ │ ├── styles/
│ │ │ │ │ └── global.css
│ │ │ │ ├── types.ts
│ │ │ │ └── utils/
│ │ │ │ └── amplifyConfig.ts
│ │ │ ├── tailwind.config.js
│ │ │ └── tsconfig.json
│ │ ├── test/
│ │ │ └── ai-ecommerce-support-simulator.test.ts
│ │ └── tsconfig.json
│ ├── fast-api-streaming/
│ │ ├── README.MD
│ │ ├── main.py
│ │ └── requirements.txt
│ ├── langfuse-demo/
│ │ ├── main.py
│ │ ├── readme.md
│ │ ├── requirements.txt
│ │ └── tools/
│ │ └── weather_tool.py
│ ├── local-demo/
│ │ ├── local-orchestrator.ts
│ │ ├── package.json
│ │ └── tools/
│ │ ├── math_tool.ts
│ │ └── weather_tool.ts
│ ├── python/
│ │ ├── imports.py
│ │ ├── main-app.py
│ │ ├── movie-production/
│ │ │ ├── movie-production-demo.py
│ │ │ ├── readme.md
│ │ │ ├── requirements.txt
│ │ │ └── search_web.py
│ │ ├── pages/
│ │ │ └── home.py
│ │ ├── readme.md
│ │ ├── requirements.txt
│ │ └── travel-planner/
│ │ ├── readme.md
│ │ ├── requirements.txt
│ │ ├── search_web.py
│ │ └── travel-planner-demo.py
│ ├── python-demo/
│ │ ├── main-stream.py
│ │ ├── main.py
│ │ └── tools/
│ │ └── weather_tool.py
│ ├── strands-agents-demo/
│ │ ├── main.py
│ │ └── requirements.txt
│ ├── supervisor-mode/
│ │ ├── main.py
│ │ └── weather_tool.py
│ ├── text-2-structured-output/
│ │ ├── README.md
│ │ ├── multi_agent_query_analyzer.py
│ │ ├── product_search_agent.py
│ │ ├── prompts.py
│ │ └── requirements.txt
│ └── tools/
│ └── python/
│ └── weather_tool_example.py
├── python/
│ ├── .gitignore
│ ├── CONTRIBUTING.md
│ ├── Makefile
│ ├── README.md
│ ├── pyproject.toml
│ ├── ruff.toml
│ ├── setup.cfg
│ ├── setup.py
│ ├── src/
│ │ ├── agent_squad/
│ │ │ ├── __init__.py
│ │ │ ├── agents/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── agent.py
│ │ │ │ ├── amazon_bedrock_agent.py
│ │ │ │ ├── anthropic_agent.py
│ │ │ │ ├── bedrock_flows_agent.py
│ │ │ │ ├── bedrock_inline_agent.py
│ │ │ │ ├── bedrock_llm_agent.py
│ │ │ │ ├── bedrock_translator_agent.py
│ │ │ │ ├── chain_agent.py
│ │ │ │ ├── comprehend_filter_agent.py
│ │ │ │ ├── lambda_agent.py
│ │ │ │ ├── lex_bot_agent.py
│ │ │ │ ├── openai_agent.py
│ │ │ │ ├── strands_agent.py
│ │ │ │ └── supervisor_agent.py
│ │ │ ├── classifiers/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── anthropic_classifier.py
│ │ │ │ ├── bedrock_classifier.py
│ │ │ │ ├── classifier.py
│ │ │ │ └── openai_classifier.py
│ │ │ ├── orchestrator.py
│ │ │ ├── retrievers/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── amazon_kb_retriever.py
│ │ │ │ └── retriever.py
│ │ │ ├── shared/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── user_agent.py
│ │ │ │ └── version.py
│ │ │ ├── storage/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── chat_storage.py
│ │ │ │ ├── dynamodb_chat_storage.py
│ │ │ │ ├── in_memory_chat_storage.py
│ │ │ │ └── sql_chat_storage.py
│ │ │ ├── types/
│ │ │ │ ├── __init__.py
│ │ │ │ └── types.py
│ │ │ └── utils/
│ │ │ ├── __init__.py
│ │ │ ├── helpers.py
│ │ │ ├── logger.py
│ │ │ └── tool.py
│ │ └── tests/
│ │ ├── __init__.py
│ │ ├── agents/
│ │ │ ├── __init__.py
│ │ │ ├── test_agent.py
│ │ │ ├── test_amazon_bedrock_agent.py
│ │ │ ├── test_anthropic_agent.py
│ │ │ ├── test_bedrock_flows_agent.py
│ │ │ ├── test_bedrock_inline_agent.py
│ │ │ ├── test_bedrock_llm_agent.py
│ │ │ ├── test_comprehend_agent.py
│ │ │ ├── test_lambda_agent.py
│ │ │ ├── test_lex_bot_agent.py
│ │ │ ├── test_openai_agent.py
│ │ │ ├── test_strands_agent.py
│ │ │ └── test_supervisor_agent.py
│ │ ├── classifiers/
│ │ │ ├── __init__.py
│ │ │ ├── test_anthropic_classifier.py
│ │ │ └── test_classifier.py
│ │ ├── pytest.ini
│ │ ├── retrievers/
│ │ │ └── test_retriever.py
│ │ ├── storage/
│ │ │ ├── __init__.py
│ │ │ ├── test_chat_storage.py
│ │ │ ├── test_dynamodb_chat_storage.py
│ │ │ ├── test_in_memory_chat_storage.py
│ │ │ └── test_sql_chat_storage.py
│ │ ├── test_orchestrator.py
│ │ └── utils/
│ │ ├── test_helpers.py
│ │ ├── test_logger.py
│ │ └── test_tool.py
│ └── test_requirements.txt
└── typescript/
├── .eslintrc.js
├── .npmignore
├── README.md
├── jest.config.js
├── package.json
├── src/
│ ├── agentOverlapAnalyzer.ts
│ ├── agents/
│ │ ├── agent.ts
│ │ ├── amazonBedrockAgent.ts
│ │ ├── anthropicAgent.ts
│ │ ├── bedrockFlowsAgent.ts
│ │ ├── bedrockInlineAgent.ts
│ │ ├── bedrockLLMAgent.ts
│ │ ├── bedrockTranslatorAgent.ts
│ │ ├── chainAgent.ts
│ │ ├── comprehendFilterAgent.ts
│ │ ├── lambdaAgent.ts
│ │ ├── lexBotAgent.ts
│ │ ├── openAIAgent.ts
│ │ └── supervisorAgent.ts
│ ├── classifiers/
│ │ ├── anthropicClassifier.ts
│ │ ├── bedrockClassifier.ts
│ │ ├── classifier.ts
│ │ └── openAIClassifier.ts
│ ├── common/
│ │ └── src/
│ │ ├── awsSdkUtils.ts
│ │ ├── types/
│ │ │ └── awsSdk.ts
│ │ └── version.ts
│ ├── index.ts
│ ├── orchestrator.ts
│ ├── retrievers/
│ │ ├── AmazonKBRetriever.ts
│ │ └── retriever.ts
│ ├── storage/
│ │ ├── chatStorage.ts
│ │ ├── dynamoDbChatStorage.ts
│ │ ├── memoryChatStorage.ts
│ │ └── sqlChatStorage.ts
│ ├── types/
│ │ └── index.ts
│ └── utils/
│ ├── chatUtils.ts
│ ├── helpers.ts
│ ├── logger.ts
│ └── tool.ts
├── tests/
│ ├── Orchestrator.test.ts
│ ├── agents/
│ │ ├── Agents.test.ts
│ │ ├── LambdaAgent.test.ts
│ │ └── OpenAi.test.ts
│ ├── classifiers/
│ │ ├── AnthropicClassifier.test.ts
│ │ ├── BedrockClassifier.test.ts
│ │ ├── Classifier.test.ts
│ │ └── OpenAIClassifier.test.ts
│ ├── mock/
│ │ └── mockAgent.ts
│ ├── retrievers/
│ │ └── Retriever.test.ts
│ ├── storage/
│ │ └── ChatStorage.test.ts
│ └── utils/
│ └── Utils.test.ts
└── tsconfig.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitattributes
================================================
# Include TypeScript and Python as detectable languages
*.py linguist-detectable=true
*.ts linguist-detectable=true
*.js linguist-detectable=false
================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.yml
================================================
name: Bug report
description: Report a reproducible bug to help us improve
title: "Bug: TITLE"
labels: ["bug"]
body:
- type: markdown
attributes:
value: |
Thank you for submitting a bug report. Please add as much information as possible to help us reproduce, and remove any potential sensitive data.
- type: textarea
id: expected_behaviour
attributes:
label: Expected Behaviour
description: Please share details on the behaviour you expected
validations:
required: true
- type: textarea
id: current_behaviour
attributes:
label: Current Behaviour
description: Please share details on the current issue
validations:
required: true
- type: textarea
id: code_snippet
attributes:
label: Code snippet
description: Please share a code snippet to help us reproduce the issue
render: python
validations:
required: true
- type: textarea
id: solution
attributes:
label: Possible Solution
description: If known, please suggest a potential resolution
validations:
required: false
- type: textarea
id: steps
attributes:
label: Steps to Reproduce
description: Please share how we might be able to reproduce this issue
validations:
required: true
- type: markdown
attributes:
value: |
---
================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.yml
================================================
name: Feature request
description: Suggest an idea for Agent Squad
title: "Feature request: TITLE"
labels: ["feature-request", "triage"]
body:
- type: markdown
attributes:
value: |
Thank you for taking the time to suggest an idea to the Agent Squad project.
*Future readers*: Please react with 👍 and your use case to help us understand customer demand.
- type: textarea
id: problem
attributes:
label: Use case
description: Please help us understand your use case or problem you're facing
validations:
required: true
- type: textarea
id: suggestion
attributes:
label: Solution/User Experience
description: Please share what a good solution would look like to this use case
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternative solutions
description: Please describe what alternative solutions to this use case, if any
render: markdown
validations:
required: false
================================================
FILE: .github/PULL_REQUEST_TEMPLATE.md
================================================
<!-- markdownlint-disable MD041 MD043 -->
## Issue Link (REQUIRED)
<!-- This PR must be linked to an issue. PRs without a linked issue will not be merged. -->
Fixes #<!-- Add issue number here (e.g., Fixes #123) -->
## Summary
### Changes
<!-- Please provide a summary of what's being changed -->
### User experience
<!-- Please share what the user experience looks like before and after this change -->
## Checklist
If your change doesn't seem to apply, please leave them unchecked.
* [ ] I have performed a self-review of this change
* [ ] Changes have been tested
* [ ] Changes are documented
* [ ] I have linked this PR to an existing issue (required)
<details>
<summary>Is this a breaking change?</summary>
**RFC issue number**:
Checklist:
* [ ] Migration process documented
* [ ] Implement warnings (if it can live side by side)
</details>
## Acknowledgment
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.
**Disclaimer**: We value your time and bandwidth. As such, any pull requests created on non-triaged issues might not be successful.
================================================
FILE: .github/workflows/npm-publish.yml
================================================
# This workflow will run tests using node and then publish a package to GitHub Packages when a release is created
# For more information see: https://docs.github.com/en/actions/publishing-packages/publishing-nodejs-packages
name: Publish Typescript Package to NPM
on:
workflow_dispatch:
jobs:
build-and-publish:
runs-on: ubuntu-latest
defaults:
run:
working-directory: typescript
steps:
- uses: actions/checkout@9a9194f87191a7e9055e3e9b95b8cfb13023bb08
- uses: actions/setup-node@60edb5dd545a775178f52524783378180af0d1f8
with:
node-version: 20
registry-url: https://registry.npmjs.org/
- run: cp ../LICENSE .
- run: npm install
- run: npm run build
- run: npm pack
- run: npm publish --access=public
env:
NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
================================================
FILE: .github/workflows/on-docs-update.yml
================================================
name: Build and Deploy Documentation
on:
push:
branches:
- main
paths:
- 'docs/**'
workflow_dispatch:
permissions:
contents: read
pages: write
id-token: write
jobs:
# Build the documentation.
build:
concurrency: ci-${{ github.ref }}
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install, build, and upload documentation
uses: withastro/action@v2
with:
path: ./docs
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
path: ./docs/dist
# Deploy the documentation to GitHub Pages.
deploy:
needs: build
runs-on: ubuntu-latest
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@7a9bd943aa5e5175aeb8502edcc6c1c02d398e10
================================================
FILE: .github/workflows/on-issue-opened.yml
================================================
name: Label issues
on:
issues:
types:
- reopened
- opened
permissions:
issues: write
jobs:
label_issues:
runs-on: ubuntu-latest
steps:
- uses: actions/github-script@1f16022c7518aad314c43abcd029895291be0f52
with:
script: |
github.rest.issues.addLabels({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
labels: ["triage"]
})
================================================
FILE: .github/workflows/on-push.yml
================================================
name: Push Workflow
on:
push:
branches:
- main
pull_request:
types:
- opened
- edited
permissions:
contents: read
jobs:
security-checks:
uses: ./.github/workflows/ts-run-security-checks.yml
secrets: inherit
================================================
FILE: .github/workflows/pr-issue-link-checker.yml
================================================
name: PR Issue Link Checker
on:
pull_request:
types: [opened, edited, reopened, synchronize]
jobs:
check-issue-link:
runs-on: ubuntu-latest
steps:
- name: Check for Linked Issue
uses: actions/github-script@v6
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const { owner, repo, number } = context.issue;
// Get the PR details
const pr = await github.rest.pulls.get({
owner,
repo,
pull_number: number
});
// Check PR body for issue links
const body = pr.data.body || '';
// Regular expressions to match different formats of issue links
const issueRegexes = [
/#(\d+)/, // #123
/[Cc]loses #(\d+)/, // Closes #123
/[Ff]ixes #(\d+)/, // Fixes #123
/[Rr]esolves #(\d+)/, // Resolves #123
/[Cc]lose #(\d+)/, // Close #123
/[Ff]ix #(\d+)/, // Fix #123
/[Rr]esolve #(\d+)/, // Resolve #123
/[Cc]loses: #(\d+)/, // Closes: #123
/[Ff]ixes: #(\d+)/, // Fixes: #123
/[Rr]esolves: #(\d+)/, // Resolves: #123
/[Cc]lose: #(\d+)/, // Close: #123
/[Ff]ix: #(\d+)/, // Fix: #123
/[Rr]esolve: #(\d+)/, // Resolve: #123
/(?:issues?|closes?|fixes?|resolves?)[ ]*?(?:\/|#)(\d+)/i // Various other formats
];
let hasIssueLink = false;
// Also check if the PR is linked to issues through GitHub's UI
const linkedIssues = await github.rest.issues.listEventsForTimeline({
owner,
repo,
issue_number: number
});
const crossReferences = linkedIssues.data.filter(event =>
event.event === 'cross-referenced' &&
event.source?.issue?.html_url.includes(`/${owner}/${repo}/issues/`)
);
if (crossReferences.length > 0) {
hasIssueLink = true;
}
// Check for issue links in PR body
if (!hasIssueLink) {
for (const regex of issueRegexes) {
if (regex.test(body)) {
hasIssueLink = true;
break;
}
}
}
if (!hasIssueLink) {
core.setFailed('Pull request must be linked to an issue. Please add a reference to an issue in your PR description (e.g., "Fixes #123") or link an issue through the GitHub UI.');
}
================================================
FILE: .github/workflows/py-run-tests.yml
================================================
name: Run Python tests
on:
push:
branches:
- main
paths:
- "python/**"
pull_request:
paths:
- "python/**"
workflow_dispatch:
permissions:
contents: read
jobs:
test_and_quality_check:
runs-on: ubuntu-latest
strategy:
max-parallel: 4
matrix:
python-version: ["3.11","3.12","3.13"]
env:
PYTHON: "${{ matrix.python-version }}"
permissions:
contents: read # checkout code only
defaults:
run:
working-directory: python
steps:
- name: Checkout repository
uses: actions/checkout@9a9194f87191a7e9055e3e9b95b8cfb13023bb08
- name: Set up Python
uses: actions/setup-python@2bd53f9a4d1dd1cd21eaffcc01a7b91a8e73ea4c
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
pip install --upgrade pip
pip install -r test_requirements.txt
- name: Code format and linter with Ruff
run: make code-quality
- name: Run tests
run: make test
================================================
FILE: .github/workflows/pypi-publish.yml
================================================
name: Publish Python Package to PyPI
on:
workflow_dispatch:
jobs:
build-and-publish:
runs-on: ubuntu-latest
defaults:
run:
working-directory: python
steps:
- uses: actions/checkout@9a9194f87191a7e9055e3e9b95b8cfb13023bb08
- name: Copy files
run: |
cp ../LICENSE .
- name: Set up Python
uses: actions/setup-python@2bd53f9a4d1dd1cd21eaffcc01a7b91a8e73ea4c
with:
python-version: '3.12'
- name: Install build dependencies
run: |
python -m pip install --upgrade pip
python -m pip install --upgrade build twine
- name: Build package
run: python -m build
- name: Check distribution
run: twine check dist/*
- name: Publish to PyPI
env:
TWINE_USERNAME: __token__
TWINE_PASSWORD: ${{secrets.PYPI_API_TOKEN}}
run: python -m twine upload dist/* --verbose
================================================
FILE: .github/workflows/ts-run-lint.yml
================================================
name: Run lint checks on the project
on:
push:
paths:
- 'typescript/**'
pull_request:
types:
- opened
- reopened
- synchronize
workflow_dispatch: # Allows manual triggering on any branch
permissions:
contents: read
jobs:
lint:
runs-on: ubuntu-latest
defaults:
run:
working-directory: typescript
steps:
- name: Checkout repository
uses: actions/checkout@9a9194f87191a7e9055e3e9b95b8cfb13023bb08
- name: Link Checker
uses: lycheeverse/lychee-action@c053181aa0c3d17606addfe97a9075a32723548a
with:
fail: true
args: --scheme=https . --exclude-all-private --accept '999, 429' --max-concurrency 1 --retry-wait-time 5 --user-agent "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" --exclude https://docs.anthropic.com/en/api/getting-started
- name: Install dependencies
run: npm install
- name: Run linting
run: npm run lint
================================================
FILE: .github/workflows/ts-run-security-checks.yml
================================================
name: Run security checks on the project
on:
workflow_call:
workflow_dispatch:
permissions:
contents: read
jobs:
scan:
runs-on: ubuntu-latest
defaults:
run:
working-directory: typescript
env:
ACTIONS_STEP_DEBUG: true
steps:
# Checkout and setup.
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install dependencies
run: npm install
# NPM audit.
- name: Run audit
run: npm audit
continue-on-error: true
# GitLeaks.
- name: Run Gitleaks
uses: gitleaks/gitleaks-action@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE }}
================================================
FILE: .github/workflows/ts-run-tests.yml
================================================
name: Run Typescript tests
on:
push:
branches:
- main
paths:
- "typescript/**"
pull_request:
paths:
- "typescript/**"
workflow_dispatch:
permissions:
contents: read
jobs:
lint:
runs-on: ubuntu-latest
defaults:
run:
working-directory: typescript
steps:
- name: Checkout repository
uses: actions/checkout@9a9194f87191a7e9055e3e9b95b8cfb13023bb08
- name: Link Checker
uses: lycheeverse/lychee-action@c053181aa0c3d17606addfe97a9075a32723548a
with:
fail: true
args: --scheme=https . --exclude-all-private --accept 999 --user-agent "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
- name: Install dependencies
run: npm install
- name: Run tests
run: npm run coverage
================================================
FILE: .gitignore
================================================
!typescript/jest.config.js
typescript/*.d.ts
node_modules
typescript/.package-lock.json
examples/chat-demo-app/cdk.out
examples/chat-demo-app/lib/**/*.js
examples/chat-demo-app/bin/*.js
!examples/lambda/url_rewrite/*.js
examples/resources/ui/public/aws-exports.json
examples/resources/ui/dist
examples/text-2-structured-output/venv
.DS_Store
typescript/dist/**/*
typescript/*.tgz
*aws-exports.json
!download.js
examples/local-demo/.env
typescript/coverage/**/*
.venv
examples/chat-chainlit-app/venv
*.env
*__pycache__
git-release-notes.genai.mjs
================================================
FILE: CODE_OF_CONDUCT.md
================================================
# Code of Conduct
This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).
For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact
[opensource-codeofconduct@amazon.com](opensource-codeofconduct@amazon.com) with any additional questions or comments.
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing Guidelines
Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional
documentation, we greatly value feedback and contributions from our community.
Please read through this document before submitting any issues or pull requests to ensure we have all the necessary
information to effectively respond to your bug report or contribution.
## Reporting Bugs/Feature Requests
We welcome you to use the GitHub issue tracker to report bugs or suggest features.
When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already reported the issue. Please try to include as much information as you can. Details like these are incredibly useful:
* A reproducible test case or series of steps
* The version of our code being used
* Any modifications you've made relevant to the bug
* Anything unusual about your environment or deployment
## Contributing via Pull Requests
Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that:
1. You are working against the latest source on the *main* branch.
2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already.
3. You open an issue to discuss any significant work - we would hate for your time to be wasted.
To send us a pull request, please:
1. Fork the repository.
2. Create a new branch to focus on the specific change you are contributing e.g. improv/lambda-agent
3. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change.
4. Ensure local tests pass.
5. Commit to your fork using clear commit messages.
6. Send us a pull request, answering any default questions in the pull request interface.
7. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation.
GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and
[creating a pull request](https://help.github.com/articles/creating-a-pull-request/).
## Finding contributions to work on
Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start.
## Code of Conduct
This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).
For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact
opensource-codeofconduct@amazon.com with any additional questions or comments.
## Security issue notifications
If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue.
## Licensing
See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution.
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
<h2 align="center">Agent Squad</h2>
<p align="center">Flexible, lightweight open-source framework for orchestrating multiple AI agents to handle complex conversations.</p>
---
<p align="center">
<strong>📢 New Name Alert:</strong> Multi-Agent Orchestrator is now <strong>Agent Squad!</strong> 🎉<br>
Same powerful functionalities, new catchy name. Embrace the squad!
</p>
---
<p align="center">
<a href="https://github.com/awslabs/agent-squad"><img alt="GitHub Repo" src="https://img.shields.io/badge/GitHub-Repo-green.svg" /></a>
<a href="https://www.npmjs.com/package/agent-squad"><img alt="npm" src="https://img.shields.io/npm/v/agent-squad.svg?style=flat-square"></a>
<a href="https://pypi.org/project/agent-squad/"><img alt="PyPI" src="https://img.shields.io/pypi/v/agent-squad.svg?style=flat-square"></a>
</p>
<p align="center">
<!-- GitHub Stats -->
<img src="https://img.shields.io/github/stars/awslabs/agent-squad?style=social" alt="GitHub stars">
<img src="https://img.shields.io/github/forks/awslabs/agent-squad?style=social" alt="GitHub forks">
<img src="https://img.shields.io/github/watchers/awslabs/agent-squad?style=social" alt="GitHub watchers">
</p>
<p align="center">
<!-- Repository Info -->
<img src="https://img.shields.io/github/last-commit/awslabs/agent-squad" alt="Last Commit">
<img src="https://img.shields.io/github/issues/awslabs/agent-squad" alt="Issues">
<img src="https://img.shields.io/github/issues-pr/awslabs/agent-squad" alt="Pull Requests">
</p>
<p align="center">
<a href="https://awslabs.github.io/agent-squad/" style="display: inline-block; background-color: #0066cc; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; font-weight: bold; font-size: 15px; transition: background-color 0.3s;">
📚 Explore Full Documentation
</a>
</p>
## 🔖 Features
- 🧠 **Intelligent intent classification** — Dynamically route queries to the most suitable agent based on context and content.
- 🔤 **Dual language support** — Fully implemented in both **Python** and **TypeScript**.
- 🌊 **Flexible agent responses** — Support for both streaming and non-streaming responses from different agents.
- 📚 **Context management** — Maintain and utilize conversation context across multiple agents for coherent interactions.
- 🔧 **Extensible architecture** — Easily integrate new agents or customize existing ones to fit your specific needs.
- 🌐 **Universal deployment** — Run anywhere - from AWS Lambda to your local environment or any cloud platform.
- 📦 **Pre-built agents and classifiers** — A variety of ready-to-use agents and multiple classifier implementations available.
## What's the Agent Squad ❓
The Agent Squad is a flexible framework for managing multiple AI agents and handling complex conversations. It intelligently routes queries and maintains context across interactions.
The system offers pre-built components for quick deployment, while also allowing easy integration of custom agents and conversation messages storage solutions.
This adaptability makes it suitable for a wide range of applications, from simple chatbots to sophisticated AI systems, accommodating diverse requirements and scaling efficiently.
<hr/>
## 🏗️ High-level architecture flow diagram
<br /><br />

<br /><br />
1. The process begins with user input, which is analyzed by a Classifier.
2. The Classifier leverages both Agents' Characteristics and Agents' Conversation history to select the most appropriate agent for the task.
3. Once an agent is selected, it processes the user input.
4. The orchestrator then saves the conversation, updating the Agents' Conversation history, before delivering the response back to the user.
##  Introducing SupervisorAgent: Agents Coordination
The Agent Squad now includes a powerful new SupervisorAgent that enables sophisticated team coordination between multiple specialized agents. This new component implements a "agent-as-tools" architecture, allowing a lead agent to coordinate a team of specialized agents in parallel, maintaining context and delivering coherent responses.

Key capabilities:
- 🤝 **Team Coordination** - Coordinate multiple specialized agents working together on complex tasks
- ⚡ **Parallel Processing** - Execute multiple agent queries simultaneously
- 🧠 **Smart Context Management** - Maintain conversation history across all team members
- 🔄 **Dynamic Delegation** - Intelligently distribute subtasks to appropriate team members
- 🤖 **Agent Compatibility** - Works with all agent types (Bedrock, Anthropic, Lex, etc.)
The SupervisorAgent can be used in two powerful ways:
1. **Direct Usage** - Call it directly when you need dedicated team coordination for specific tasks
2. **Classifier Integration** - Add it as an agent within the classifier to build complex hierarchical systems with multiple specialized teams
Here are just a few examples where this agent can be used:
- Customer Support Teams with specialized sub-teams
- AI Movie Production Studios
- Travel Planning Services
- Product Development Teams
- Healthcare Coordination Systems
[Learn more about SupervisorAgent →](https://awslabs.github.io/agent-squad/agents/built-in/supervisor-agent)
## 💬 Demo App
In the screen recording below, we demonstrate an extended version of the demo app that uses 6 specialized agents:
- **Travel Agent**: Powered by an Amazon Lex Bot
- **Weather Agent**: Utilizes a Bedrock LLM Agent with a tool to query the open-meteo API
- **Restaurant Agent**: Implemented as an Amazon Bedrock Agent
- **Math Agent**: Utilizes a Bedrock LLM Agent with two tools for executing mathematical operations
- **Tech Agent**: A Bedrock LLM Agent designed to answer questions on technical topics
- **Health Agent**: A Bedrock LLM Agent focused on addressing health-related queries
Watch as the system seamlessly switches context between diverse topics, from booking flights to checking weather, solving math problems, and providing health information.
Notice how the appropriate agent is selected for each query, maintaining coherence even with brief follow-up inputs.
The demo highlights the system's ability to handle complex, multi-turn conversations while preserving context and leveraging specialized agents across various domains.

## 🎯 Examples & Quick Start
Get hands-on experience with the Agent Squad through our diverse set of examples:
- **Demo Applications**:
- [Streamlit Global Demo](https://github.com/awslabs/agent-squad/tree/main/examples/python): A single Streamlit application showcasing multiple demos, including:
- AI Movie Production Studio
- AI Travel Planner
- [Chat Demo App](https://awslabs.github.io/agent-squad/cookbook/examples/chat-demo-app/):
- Explore multiple specialized agents handling various domains like travel, weather, math, and health
- [E-commerce Support Simulator](https://awslabs.github.io/agent-squad/cookbook/examples/ecommerce-support-simulator/): Experience AI-powered customer support with:
- Automated response generation for common queries
- Intelligent routing of complex issues to human support
- Real-time chat and email-style communication
- Human-in-the-loop interactions for complex cases
- **Sample Projects**: Explore our example implementations in the `examples` folder:
- [`chat-demo-app`](https://github.com/awslabs/agent-squad/tree/main/examples/chat-demo-app): Web-based chat interface with multiple specialized agents
- [`ecommerce-support-simulator`](https://github.com/awslabs/agent-squad/tree/main/examples/ecommerce-support-simulator): AI-powered customer support system
- [`chat-chainlit-app`](https://github.com/awslabs/agent-squad/tree/main/examples/chat-chainlit-app): Chat application built with Chainlit
- [`fast-api-streaming`](https://github.com/awslabs/agent-squad/tree/main/examples/fast-api-streaming): FastAPI implementation with streaming support
- [`text-2-structured-output`](https://github.com/awslabs/agent-squad/tree/main/examples/text-2-structured-output): Natural Language to Structured Data
- [`bedrock-inline-agents`](https://github.com/awslabs/agent-squad/tree/main/examples/bedrock-inline-agents): Bedrock Inline Agents sample
- [`bedrock-prompt-routing`](https://github.com/awslabs/agent-squad/tree/main/examples/bedrock-prompt-routing): Bedrock Prompt Routing sample code
Examples are available in both Python and TypeScript. Check out our [documentation](https://awslabs.github.io/agent-squad/) for comprehensive guides on setting up and using the Agent Squad framework!
## 📚 Deep Dives: Stories, Blogs & Podcasts
Discover creative implementations and diverse applications of the Agent Squad:
- **[From 'Bonjour' to 'Boarding Pass': Multilingual AI Chatbot for Flight Reservations](https://community.aws/content/2lCi8jEKydhDm8eE8QFIQ5K23pF/from-bonjour-to-boarding-pass-multilingual-ai-chatbot-for-flight-reservations)**
This article demonstrates how to build a multilingual chatbot using the Agent Squad framework. The article explains how to use an **Amazon Lex** bot as an agent, along with 2 other new agents to make it work in many languages with just a few lines of code.
- **[Beyond Auto-Replies: Building an AI-Powered E-commerce Support system](https://community.aws/content/2lq6cYYwTYGc7S3Zmz28xZoQNQj/beyond-auto-replies-building-an-ai-powered-e-commerce-support-system)**
This article demonstrates how to build an AI-driven multi-agent system for automated e-commerce customer email support. It covers the architecture and setup of specialized AI agents using the Agent Squad framework, integrating automated processing with human-in-the-loop oversight. The guide explores email ingestion, intelligent routing, automated response generation, and human verification, providing a comprehensive approach to balancing AI efficiency with human expertise in customer support.
- **[Speak Up, AI: Voicing Your Agents with Amazon Connect, Lex, and Bedrock](https://community.aws/content/2mt7CFG7xg4yw6GRHwH9akhg0oD/speak-up-ai-voicing-your-agents-with-amazon-connect-lex-and-bedrock)**
This article demonstrates how to build an AI customer call center. It covers the architecture and setup of specialized AI agents using the Agent Squad framework interacting with voice via **Amazon Connect** and **Amazon Lex**.
- **[Unlock Bedrock InvokeInlineAgent API's Hidden Potential](https://community.aws/content/2pTsHrYPqvAbJBl9ht1XxPOSPjR/unlock-bedrock-invokeinlineagent-api-s-hidden-potential-with-agent-squad)**
Learn how to scale **Amazon Bedrock Agents** beyond knowledge base limitations using the Agent Squad framework and **InvokeInlineAgent API**. This article demonstrates dynamic agent creation and knowledge base selection for enterprise-scale AI applications.
- **[Supercharging Amazon Bedrock Flows](https://community.aws/content/2phMjQ0bqWMg4PBwejBs1uf4YQE/supercharging-amazon-bedrock-flows-with-aws-agent-squad)**
Learn how to enhance **Amazon Bedrock Flows** with conversation memory and multi-flow orchestration using the Agent Squad framework. This guide shows how to overcome Bedrock Flows' limitations to build more sophisticated AI workflows with persistent memory and intelligent routing between flows.
### 🎙️ Podcast Discussions
- **🇫🇷 Podcast (French)**: L'orchestrateur multi-agents : Un orchestrateur open source pour vos agents IA
- **Platforms**:
- [Apple Podcasts](https://podcasts.apple.com/be/podcast/lorchestrateur-multi-agents/id1452118442?i=1000684332612)
- [Spotify](https://open.spotify.com/episode/4RdMazSRhZUyW2pniG91Vf)
- **🇬🇧 Podcast (English)**: An Orchestrator for Your AI Agents
- **Platforms**:
- [Apple Podcasts](https://podcasts.apple.com/us/podcast/an-orchestrator-for-your-ai-agents/id1574162669?i=1000677039579)
- [Spotify](https://open.spotify.com/episode/2a9DBGZn2lVqVMBLWGipHU)
### TypeScript Version
#### Installation
> 🔄 `multi-agent-orchestrator` becomes `agent-squad`
```bash
npm install agent-squad
```
#### Usage
The following example demonstrates how to use the Agent Squad with two different types of agents: a Bedrock LLM Agent with Converse API support and a Lex Bot Agent. This showcases the flexibility of the system in integrating various AI services.
```typescript
import { AgentSquad, BedrockLLMAgent, LexBotAgent } from "agent-squad";
const orchestrator = new AgentSquad();
// Add a Bedrock LLM Agent with Converse API support
orchestrator.addAgent(
new BedrockLLMAgent({
name: "Tech Agent",
description:
"Specializes in technology areas including software development, hardware, AI, cybersecurity, blockchain, cloud computing, emerging tech innovations, and pricing/costs related to technology products and services.",
streaming: true
})
);
// Add a Lex Bot Agent for handling travel-related queries
orchestrator.addAgent(
new LexBotAgent({
name: "Travel Agent",
description: "Helps users book and manage their flight reservations",
botId: process.env.LEX_BOT_ID,
botAliasId: process.env.LEX_BOT_ALIAS_ID,
localeId: "en_US",
})
);
// Example usage
const response = await orchestrator.routeRequest(
"I want to book a flight",
'user123',
'session456'
);
// Handle the response (streaming or non-streaming)
if (response.streaming == true) {
console.log("\n** RESPONSE STREAMING ** \n");
// Send metadata immediately
console.log(`> Agent ID: ${response.metadata.agentId}`);
console.log(`> Agent Name: ${response.metadata.agentName}`);
console.log(`> User Input: ${response.metadata.userInput}`);
console.log(`> User ID: ${response.metadata.userId}`);
console.log(`> Session ID: ${response.metadata.sessionId}`);
console.log(
`> Additional Parameters:`,
response.metadata.additionalParams
);
console.log(`\n> Response: `);
// Stream the content
for await (const chunk of response.output) {
if (typeof chunk === "string") {
process.stdout.write(chunk);
} else {
console.error("Received unexpected chunk type:", typeof chunk);
}
}
} else {
// Handle non-streaming response (AgentProcessingResult)
console.log("\n** RESPONSE ** \n");
console.log(`> Agent ID: ${response.metadata.agentId}`);
console.log(`> Agent Name: ${response.metadata.agentName}`);
console.log(`> User Input: ${response.metadata.userInput}`);
console.log(`> User ID: ${response.metadata.userId}`);
console.log(`> Session ID: ${response.metadata.sessionId}`);
console.log(
`> Additional Parameters:`,
response.metadata.additionalParams
);
console.log(`\n> Response: ${response.output}`);
}
```
### Python Version
> 🔄 `multi-agent-orchestrator` becomes `agent-squad`
```bash
# Optional: Set up a virtual environment
python -m venv venv
source venv/bin/activate # On Windows use `venv\Scripts\activate`
pip install agent-squad[aws]
```
#### Default Usage
Here's an equivalent Python example demonstrating the use of the Agent Squad with a Bedrock LLM Agent and a Lex Bot Agent:
```python
import sys
import asyncio
from agent_squad.orchestrator import AgentSquad
from agent_squad.agents import BedrockLLMAgent, BedrockLLMAgentOptions, AgentStreamResponse
orchestrator = AgentSquad()
tech_agent = BedrockLLMAgent(BedrockLLMAgentOptions(
name="Tech Agent",
streaming=True,
description="Specializes in technology areas including software development, hardware, AI, \
cybersecurity, blockchain, cloud computing, emerging tech innovations, and pricing/costs \
related to technology products and services.",
model_id="anthropic.claude-3-sonnet-20240229-v1:0",
))
orchestrator.add_agent(tech_agent)
health_agent = BedrockLLMAgent(BedrockLLMAgentOptions(
name="Health Agent",
streaming=True,
description="Specializes in health and well being",
))
orchestrator.add_agent(health_agent)
async def main():
# Example usage
response = await orchestrator.route_request(
"What is AWS Lambda?",
'user123',
'session456',
{},
True
)
# Handle the response (streaming or non-streaming)
if response.streaming:
print("\n** RESPONSE STREAMING ** \n")
# Send metadata immediately
print(f"> Agent ID: {response.metadata.agent_id}")
print(f"> Agent Name: {response.metadata.agent_name}")
print(f"> User Input: {response.metadata.user_input}")
print(f"> User ID: {response.metadata.user_id}")
print(f"> Session ID: {response.metadata.session_id}")
print(f"> Additional Parameters: {response.metadata.additional_params}")
print("\n> Response: ")
# Stream the content
async for chunk in response.output:
async for chunk in response.output:
if isinstance(chunk, AgentStreamResponse):
print(chunk.text, end='', flush=True)
else:
print(f"Received unexpected chunk type: {type(chunk)}", file=sys.stderr)
else:
# Handle non-streaming response (AgentProcessingResult)
print("\n** RESPONSE ** \n")
print(f"> Agent ID: {response.metadata.agent_id}")
print(f"> Agent Name: {response.metadata.agent_name}")
print(f"> User Input: {response.metadata.user_input}")
print(f"> User ID: {response.metadata.user_id}")
print(f"> Session ID: {response.metadata.session_id}")
print(f"> Additional Parameters: {response.metadata.additional_params}")
print(f"\n> Response: {response.output.content}")
if __name__ == "__main__":
asyncio.run(main())
```
These examples showcase:
1. The use of a Bedrock LLM Agent with Converse API support, allowing for multi-turn conversations.
2. Integration of a Lex Bot Agent for specialized tasks (in this case, travel-related queries).
3. The orchestrator's ability to route requests to the most appropriate agent based on the input.
4. Handling of both streaming and non-streaming responses from different types of agents.
### Modular Installation Options
The Agent Squad is designed with a modular architecture, allowing you to install only the components you need while ensuring you always get the core functionality.
#### Installation Options
**1. AWS Integration**:
```bash
pip install "agent-squad[aws]"
```
Includes core orchestration functionality with comprehensive AWS service integrations (`BedrockLLMAgent`, `AmazonBedrockAgent`, `LambdaAgent`, etc.)
**2. Anthropic Integration**:
```bash
pip install "agent-squad[anthropic]"
```
**3. OpenAI Integration**:
```bash
pip install "agent-squad[openai]"
```
Adds OpenAI's GPT models for agents and classification, along with core packages.
**4. Full Installation**:
```bash
pip install "agent-squad[all]"
```
Includes all optional dependencies for maximum flexibility.
### 🙌 **We Want to Hear From You!**
Have something to share, discuss, or brainstorm? We’d love to connect with you and hear about your journey with the **Agent Squad framework**. Here’s how you can get involved:
- **🙌 Show & Tell**: Got a success story, cool project, or creative implementation? Share it with us in the [**Show and Tell**](https://github.com/awslabs/agent-squad/discussions/categories/show-and-tell) section. Your work might inspire the entire community! 🎉
- **💬 General Discussion**: Have questions, feedback, or suggestions? Join the conversation in our [**General Discussions**](https://github.com/awslabs/agent-squad/discussions/categories/general) section. It’s the perfect place to connect with other users and contributors.
- **💡 Ideas**: Thinking of a new feature or improvement? Share your thoughts in the [**Ideas**](https://github.com/awslabs/agent-squad/discussions/categories/ideas) section. We’re always open to exploring innovative ways to make the orchestrator even better!
Let’s collaborate, learn from each other, and build something incredible together! 🚀
## 📝 Pull Request Guidelines
### Issue-First Policy
This repository follows an **Issue-First** policy:
- **Every pull request must be linked to an existing issue**
- If there isn't an issue for the changes you want to make, please create one first
- Use the issue to discuss proposed changes before investing time in implementation
### How to Link Pull Requests to Issues
When creating a pull request, you must link it to an issue using one of these methods:
1. Include a reference in the PR description using keywords:
- `Fixes #123`
- `Resolves #123`
- `Closes #123`
2. Manually link the PR to an issue through GitHub's UI:
- On the right sidebar of your PR, click "Development" and then "Link an issue"
### Automated Enforcement
We use GitHub Actions to automatically verify that each PR is linked to an issue. PRs without linked issues will not pass required checks and cannot be merged.
This policy helps us:
- Maintain clear documentation of changes and their purposes
- Ensure community discussion before implementation
- Keep a structured development process
- Make project history more traceable and understandable
## 🤝 Contributing
⚠️ Note: Our project has been renamed from **Multi-Agent Orchestrator** to **Agent Squad**. Please use the new name in your contributions and discussions.
⚠️ We value your contributions! Before submitting changes, please start a discussion by opening an issue to share your proposal.
Once your proposal is approved, here are the next steps:
1. 📚 Review our [Contributing Guide](CONTRIBUTING.md)
2. 💡 Create a [GitHub Issue](https://github.com/awslabs/agent-squad/issues)
3. 🔨 Submit a pull request
✅ Follow existing project structure and include documentation for new features.
🌟 **Stay Updated**: Star the repository to be notified about new features, improvements, and exciting developments in the Agent Squad framework!
# Authors
- [Corneliu Croitoru](https://www.linkedin.com/in/corneliucroitoru/)
- [Anthony Bernabeu](https://www.linkedin.com/in/anthonybernabeu/)
# 👥 Contributors
Big shout out to our awesome contributors! Thank you for making this project better! 🌟 ⭐ 🚀
[](https://github.com/awslabs/agent-squad/graphs/contributors)
Please see our [contributing guide](./CONTRIBUTING.md) for guidelines on how to propose bugfixes and improvements.
## 📄 LICENSE
This project is licensed under the Apache 2.0 licence - see the [LICENSE](https://raw.githubusercontent.com/awslabs/agent-squad/main/LICENSE) file for details.
## 📄 Font License
This project uses the JetBrainsMono NF font, licensed under the SIL Open Font License 1.1.
For full license details, see [FONT-LICENSE.md](https://github.com/JetBrains/JetBrainsMono/blob/master/OFL.txt).
================================================
FILE: docs/.gitignore
================================================
# build output
dist/
# generated types
.astro/
# dependencies
node_modules/
# logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# environment variables
.env
.env.production
# macOS-specific files
.DS_Store
================================================
FILE: docs/README.md
================================================
<br>
<p align="center">
<p align="center">
<img src="https://astro.badg.es/v2/built-with-starlight/tiny.svg">
</p>
</p>
<br>
## 🚀 Run
To run the documentation locally, clone the repository and run:
```bash
npm run dev
```
## 🧞 Commands
All commands are run from the root of the project, from a terminal:
| Command | Action |
| :------------------------ | :----------------------------------------------- |
| `npm install` | Installs dependencies |
| `npm run dev` | Starts local dev server at `localhost:4321` |
| `npm run build` | Build your production site to `./dist/` |
| `npm run preview` | Preview your build locally, before deploying |
| `npm run astro ...` | Run CLI commands like `astro add`, `astro check` |
| `npm run astro -- --help` | Get help using the Astro CLI |
## 👀 Want to learn more?
Check out [Starlight’s docs](https://starlight.astro.build/), read [the Astro documentation](https://docs.astro.build), or jump into the [Astro Discord server](https://astro.build/chat).
================================================
FILE: docs/astro.config.mjs
================================================
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';
// https://astro.build/config
export default defineConfig({
site: process.env.ASTRO_SITE,
base: '/agent-squad',
markdown: {
gfm: true
},
integrations: [
starlight({
title: 'Agent Squad',
description: 'Flexible and powerful framework for managing multiple AI agents and handling complex conversations 🤖🚀',
defaultLocale: 'en',
favicon: '/src/assets/favicon.ico',
customCss: [
'./src/styles/landing.css',
'./src/styles/font.css',
'./src/styles/custom.css',
'./src/styles/terminal.css'
],
social: {
github: 'https://github.com/awslabs/agent-squad'
},
sidebar: [
{
label: 'Introduction',
items: [
{ label: 'Introduction', link: '/general/introduction' },
{ label: 'How it works', link: '/general/how-it-works' },
{ label: 'Quickstart', link: '/general/quickstart' },
{ label: 'FAQ', link: '/general/faq' }
]
},
{
label: 'Orchestrator',
items: [
{ label: 'Overview', link: '/orchestrator/overview' },
]
},{
label: 'Classifier',
items: [
{ label: 'Overview', link: '/classifiers/overview' },
{
label: 'Built-in classifiers',
items: [
{ label: 'Bedrock Classifier', link: '/classifiers/built-in/bedrock-classifier'},
{ label: 'Anthropic Classifier', link: '/classifiers/built-in/anthropic-classifier' },
{ label: 'OpenAI Classifier', link: '/classifiers/built-in/openai-classifier' },
]
},
{ label: 'Custom Classifier', link: '/classifiers/custom-classifier' },
]
},
{
label: 'Agents',
items: [
{ label: 'Overview', link: '/agents/overview' },
{
label: 'Built-in Agents',
items: [
{ label: 'Supervisor Agent', link: '/agents/built-in/supervisor-agent' },
{ label: 'Bedrock LLM Agent', link: '/agents/built-in/bedrock-llm-agent'},
{ label: 'Amazon Bedrock Agent', link: '/agents/built-in/amazon-bedrock-agent' },
{ label: 'Amazon Lex Bot Agent', link: '/agents/built-in/lex-bot-agent' },
{ label: 'AWS Lambda Agent', link: '/agents/built-in/lambda-agent' },
{ label: 'OpenAI Agent', link: '/agents/built-in/openai-agent' },
{ label: 'Anthropic Agent', link: '/agents/built-in/anthropic-agent'},
{ label: 'Chain Agent', link: '/agents/built-in/chain-agent' },
{ label: 'Comprehend Filter Agent', link: '/agents/built-in/comprehend-filter-agent' },
{ label: 'Amazon Bedrock Translator Agent', link: '/agents/built-in/bedrock-translator-agent' },
{ label: 'Amazon Bedrock Inline Agent', link: '/agents/built-in/bedrock-inline-agent' },
{ label: 'Bedrock Flows Agent', link: '/agents/built-in/bedrock-flows-agent' },
]
},
{ label: 'Custom Agents', link: '/agents/custom-agents' },
{ label: 'Tools for Agents', link: '/agents/tools' },
]
},
{
label: 'Conversation Storage',
items: [
{ label: 'Overview', link: '/storage/overview' },
{
label: 'Built-in storage',
items: [
{ label: 'In-Memory', link: '/storage/in-memory' },
{ label: 'DynamoDB', link: '/storage/dynamodb' },
{ label: 'SQL Storage', link: '/storage/sql' },
]
},
{ label: 'Custom Storage', link: '/storage/custom' }
]
},
{
label: 'Retrievers',
items: [
{ label: 'Overview', link: '/retrievers/overview' },
{
label: 'Built-in retrievers',
items: [
{ label: 'Bedrock Knowledge Base', link: '/retrievers/built-in/bedrock-kb-retriever' },
]
},
{ label: 'Custom Retriever', link: '/retrievers/custom-retriever' },
]
},
{
label: 'Cookbook',
items: [
{
label: 'Examples',
items: [
{ label: 'Chat Chainlit App', link: '/cookbook/examples/chat-chainlit-app' },
{ label: 'Chat Demo App', link: '/cookbook/examples/chat-demo-app' },
{ label: 'E-commerce Support Simulator', link: '/cookbook/examples/ecommerce-support-simulator' },
{ label: 'Fast API Streaming', link: '/cookbook/examples/fast-api-streaming' },
{ label: 'Typescript Local Demo', link: '/cookbook/examples/typescript-local-demo' },
{ label: 'Python Local Demo', link: '/cookbook/examples/python-local-demo' },
{ label: 'Api Agent', link: '/cookbook/examples/api-agent' },
{ label: 'Ollama Agent', link: '/cookbook/examples/ollama-agent' },
{ label: 'Ollama Classifier', link: '/cookbook/examples/ollama-classifier' }
]
},
{
label: 'Lambda Implementations',
items: [
{ label: 'Python Lambda', link: '/cookbook/lambda/aws-lambda-python' },
{ label: 'NodeJs Lambda', link: '/cookbook/lambda/aws-lambda-nodejs' }
]
},
{
label: 'Tool Integration',
items: [
{ label: 'Weather API Integration', link: '/cookbook/tools/weather-api' },
{ label: 'Math Operations', link: '/cookbook/tools/math-operations' }
]
},
{
label: 'Routing Patterns',
items: [
{ label: 'Cost-Efficient Routing', link: '/cookbook/patterns/cost-efficient' },
{ label: 'Multi-lingual Routing', link: '/cookbook/patterns/multi-lingual' }
]
},
{
label: 'Optimization, Logging & Observability',
items: [
{ label: 'Agent Overlap Analysis', link: '/cookbook/monitoring/agent-overlap' },
{ label: 'Logging', link: '/cookbook/monitoring/logging' },
{ label: 'Observability', link: '/cookbook/monitoring/observability' }
]
}
]
}
]
})
]
});
================================================
FILE: docs/package.json
================================================
{
"name": "@agent-squad/docs",
"description": "The official documentation for Agent Squad",
"type": "module",
"version": "0.7.0",
"private": true,
"scripts": {
"dev": "npx astro dev",
"start": "npx astro dev",
"build": "npx astro build",
"preview": "npx astro preview",
"astro": "npx astro",
"audit": "npm audit",
"clean": "npx rimraf .astro/ node_modules/ dist/"
},
"author": {
"name": "Amazon Web Services",
"url": "https://aws.amazon.com"
},
"repository": {
"type": "git",
"url": "git://github.com/awslabs/agent-squad"
},
"license": "Apache-2.0",
"dependencies": {
"@astrojs/starlight": "^0.30.3",
"astro": "^5.1.1",
"sharp": "^0.33.4",
"shiki": "^1.10.3"
},
"devDependencies": {
"rimraf": "^5.0.7"
}
}
================================================
FILE: docs/src/components/code.astro
================================================
---
import { ExpressiveCode, ExpressiveCodeConfig } from 'expressive-code';
import { toHtml } from 'hast-util-to-html';
import { pluginCollapsibleSections } from '@expressive-code/plugin-collapsible-sections';
import fs from 'node:fs/promises';
interface Props {
file: string;
language?: string;
meta?: string;
}
const { file, language, meta } = Astro.props;
const fileNamePath = '../' + file;
const fileEtension = file.split('.').pop() ?? 'js';
const code = await fs.readFile(fileNamePath, 'utf-8');
const ec = new ExpressiveCode({
plugins: [pluginCollapsibleSections()],
});
// Get base styles that should be included on the page
// (they are independent of the rendered code blocks)
const baseStyles = await ec.getBaseStyles();
// Render some example code to AST
const { renderedGroupAst, styles } = await ec.render({
code: code,
language: language ?? fileEtension,
meta: `title="${file}"` + (meta ? ` ${meta}` : ''),
});
// Convert the rendered AST to HTML
let htmlContent = toHtml(renderedGroupAst);
// Collect styles and add them before the HTML content
const stylesToPrepend: string[] = [];
stylesToPrepend.push(baseStyles);
stylesToPrepend.push(...styles);
if (stylesToPrepend.length) {
htmlContent = `<style>${[...stylesToPrepend].join('')}</style>${htmlContent}`;
}
---
<div set:html={htmlContent} />
================================================
FILE: docs/src/content/config.ts
================================================
/*
* Copyright (C) 2023 Amazon.com, Inc. or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { defineCollection } from 'astro:content';
import { docsSchema, i18nSchema } from '@astrojs/starlight/schema';
export const collections = {
docs: defineCollection({ schema: docsSchema() }),
i18n: defineCollection({ type: 'data', schema: i18nSchema() }),
};
================================================
FILE: docs/src/content/docs/agents/built-in/amazon-bedrock-agent.mdx
================================================
---
title: AmazonBedrockAgent
description: Documentation for the AmazonBedrockAgent in the Agent Squad
---
The `AmazonBedrockAgent` is a specialized agent class in the Agent Squad that integrates directly with [Amazon Bedrock agents](https://aws.amazon.com/bedrock/agents/?nc1=h_ls).
## Creating an AmazonBedrockAgent
Here are various examples showing different ways to create and configure an AmazonBedrockAgent:
### Python Package
If you haven't already installed the AWS-related dependencies, make sure to install them:
```bash
pip install "agent-squad[aws]"
```
### Basic Examples
**1. Minimal Configuration**
import { Tabs, TabItem } from '@astrojs/starlight/components';
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const agent = new AmazonBedrockAgent({
name: 'My Bank Agent',
description: 'A helpful and friendly agent that answers questions about loan-related inquiries',
agentId: 'your-agent-id',
agentAliasId: 'your-agent-alias-id'
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
agent = AmazonBedrockAgent(AmazonBedrockAgentOptions(
name='My Bank Agent',
description='A helpful and friendly agent that answers questions about loan-related inquiries',
agent_id='your-agent-id',
agent_alias_id='your-agent-alias-id'
))
```
</TabItem>
</Tabs>
<hr/>
**2. Using Custom Client**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { BedrockAgentRuntimeClient } from "@aws-sdk/client-bedrock-agent-runtime";
const customClient = new BedrockAgentRuntimeClient({ region: 'us-east-1' });
const agent = new AmazonBedrockAgent({
name: 'My Bank Agent',
description: 'A helpful and friendly agent for banking inquiries',
agentId: 'your-agent-id',
agentAliasId: 'your-agent-alias-id',
client: customClient
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
import boto3
custom_client = boto3.client('bedrock-agent-runtime', region_name='us-east-1')
agent = AmazonBedrockAgent(AmazonBedrockAgentOptions(
name='My Bank Agent',
description='A helpful and friendly agent for banking inquiries',
agent_id='your-agent-id',
agent_alias_id='your-agent-alias-id',
client=custom_client
))
```
</TabItem>
</Tabs>
<hr/>
**3. With Tracing Enabled**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const agent = new AmazonBedrockAgent({
name: 'My Bank Agent',
description: 'A banking agent with tracing enabled',
agentId: 'your-agent-id',
agentAliasId: 'your-agent-alias-id',
enableTrace: true
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
agent = AmazonBedrockAgent(AmazonBedrockAgentOptions(
name='My Bank Agent',
description='A banking agent with tracing enabled',
agent_id='your-agent-id',
agent_alias_id='your-agent-alias-id',
enable_trace=True
))
```
</TabItem>
</Tabs>
<hr/>
**4. With Streaming Enabled**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const agent = new AmazonBedrockAgent({
name: 'My Bank Agent',
description: 'A streaming-enabled banking agent',
agentId: 'your-agent-id',
agentAliasId: 'your-agent-alias-id',
streaming: true
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
agent = AmazonBedrockAgent(AmazonBedrockAgentOptions(
name='My Bank Agent',
description='A streaming-enabled banking agent',
agent_id='your-agent-id',
agent_alias_id='your-agent-alias-id',
streaming=True
))
```
</TabItem>
</Tabs>
<hr/>
**5. Complete Example with All Options**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { AmazonBedrockAgent } from "agent-squad";
import { BedrockAgentRuntimeClient } from "@aws-sdk/client-bedrock-agent-runtime";
const agent = new AmazonBedrockAgent({
// Required fields
name: "Advanced Bank Agent",
description: "A fully configured banking agent with all features enabled",
agentId: "your-agent-id",
agentAliasId: "your-agent-alias-id",
// Optional fields
region: "us-west-2",
streaming: true,
enableTrace: true,
client: new BedrockAgentRuntimeClient({ region: "us-west-2" }),
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
import boto3
from agent_squad.agents import AmazonBedrockAgent, AmazonBedrockAgentOptions
custom_client = boto3.client('bedrock-agent-runtime', region_name='us-west-2')
agent = AmazonBedrockAgent(AmazonBedrockAgentOptions(
# Required fields
name='Advanced Bank Agent',
description='A fully configured banking agent with all features enabled',
agent_id='your-agent-id',
agent_alias_id='your-agent-alias-id',
# Optional fields
region='us-west-2',
streaming=True,
enable_trace=True,
client=custom_client
))
```
</TabItem>
</Tabs>
### Option Explanations
- `name`: (Required) Identifies the agent within your system.
- `description`: (Required) Describes the agent's purpose or capabilities.
- `agentId/agent_id`: (Required) The ID of the Amazon Bedrock agent you want to use.
- `agentAliasId/agent_alias_id`: (Required) The alias ID of the Amazon Bedrock agent.
- `region`: (Optional) AWS region for the Bedrock service. If not provided, uses the default AWS region.
- `client`: (Optional) Custom BedrockAgentRuntimeClient for specialized configurations.
- `enableTrace/enable_trace`: (Optional) When set to true, enables tracing of the agent's steps and reasoning process.
- `streaming`: (Optional) Enables streaming for the final response. Defaults to false.
## Adding the Agent to the Orchestrator
To integrate the AmazonBedrockAgent into your Agent Squad, follow these steps:
1. First, ensure you have created an instance of the orchestrator:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { AgentSquad } from "agent-squad";
const orchestrator = new AgentSquad();
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
from agent_squad.orchestrator import AgentSquad
orchestrator = AgentSquad()
```
</TabItem>
</Tabs>
2. Then, add the agent to the orchestrator:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
orchestrator.addAgent(agent);
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
orchestrator.add_agent(agent)
```
</TabItem>
</Tabs>
3. Now you can use the orchestrator to route requests to the appropriate agent, including your Amazon Bedrock agent:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const response = await orchestrator.routeRequest(
"What is the base rate interest for 30 years?",
"user123",
"session456"
);
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
response = await orchestrator.route_request(
"What is the base rate interest for 30 years?",
"user123",
"session456"
)
```
</TabItem>
</Tabs>
---
By leveraging the `AmazonBedrockAgent`, you can easily integrate **pre-built Amazon Bedrock agents** into your Agent Squad.
================================================
FILE: docs/src/content/docs/agents/built-in/anthropic-agent.mdx
================================================
---
title: Anthropic Agent
description: Documentation for the AnthropicAgent in the Agent Squad
---
## Overview
The `AnthropicAgent` is a powerful and flexible agent class in the Agent Squad System.
It leverages the [Anthropic API](https://docs.anthropic.com/en/api/getting-started) to interact with various Large Language Models (LLMs) provided by Anthropic, such as Claude.
This agent can handle a wide range of processing tasks, making it suitable for diverse applications such as conversational AI, question-answering systems, and more.
## Key Features
- Integration with Anthropic's API
- Support for multiple LLM models available on Anthropic's platform
- Streaming and non-streaming response options
- Customizable inference configuration
- Ability to set and update custom system prompts
- Optional integration with retrieval systems for enhanced context
- Support for Tool use within the conversation flow
## Creating an AnthropicAgent
Here are various examples showing different ways to create and configure an AnthropicAgent:
### Python Package
If you haven't already installed the Anthropic-related dependencies, make sure to install them:
```bash
pip install "agent-squad[anthropic]"
```
### Basic Examples
**1. Minimal Configuration**
import { Tabs, TabItem } from '@astrojs/starlight/components';
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const agent = new AnthropicAgent({
name: 'Anthropic Assistant',
description: 'A versatile AI assistant',
apiKey: 'your-anthropic-api-key'
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
agent = AnthropicAgent(AnthropicAgentOptions(
name='Anthropic Assistant',
description='A versatile AI assistant',
api_key='your-anthropic-api-key'
))
```
</TabItem>
</Tabs>
<hr/>
**2. Using Custom Client**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { Anthropic } from '@anthropic-ai/sdk';
const customClient = new Anthropic({ apiKey: 'your-anthropic-api-key' });
const agent = new AnthropicAgent({
name: 'Anthropic Assistant',
description: 'A versatile AI assistant',
client: customClient
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
from anthropic import Anthropic
custom_client = Anthropic(api_key='your-anthropic-api-key')
agent = AnthropicAgent(AnthropicAgentOptions(
name='Anthropic Assistant',
description='A versatile AI assistant',
client=custom_client
))
```
</TabItem>
</Tabs>
<hr/>
**3. Custom Model and Streaming**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const agent = new AnthropicAgent({
name: 'Anthropic Assistant',
description: 'A streaming-enabled assistant',
apiKey: 'your-anthropic-api-key',
modelId: 'claude-3-opus-20240229',
streaming: true
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
agent = AnthropicAgent(AnthropicAgentOptions(
name='Anthropic Assistant',
description='A streaming-enabled assistant',
api_key='your-anthropic-api-key',
model_id='claude-3-opus-20240229',
streaming=True
))
```
</TabItem>
</Tabs>
<hr/>
**4. With Inference Configuration**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const agent = new AnthropicAgent({
name: 'Anthropic Assistant',
description: 'An assistant with custom inference settings',
apiKey: 'your-anthropic-api-key',
inferenceConfig: {
maxTokens: 500,
temperature: 0.7,
topP: 0.9,
stopSequences: ['Human:', 'AI:']
}
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
agent = AnthropicAgent(AnthropicAgentOptions(
name='Anthropic Assistant',
description='An assistant with custom inference settings',
api_key='your-anthropic-api-key',
inference_config={
'maxTokens': 500,
'temperature': 0.7,
'topP': 0.9,
'stopSequences': ['Human:', 'AI:']
}
))
```
</TabItem>
</Tabs>
<hr/>
**5. With Simple System Prompt**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const agent = new AnthropicAgent({
name: 'Anthropic Assistant',
description: 'An assistant with custom prompt',
apiKey: 'your-anthropic-api-key',
customSystemPrompt: {
template: 'You are a helpful AI assistant focused on technical support.'
}
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
agent = AnthropicAgent(AnthropicAgentOptions(
name='Anthropic Assistant',
description='An assistant with custom prompt',
api_key='your-anthropic-api-key',
custom_system_prompt={
'template': 'You are a helpful AI assistant focused on technical support.'
}
))
```
</TabItem>
</Tabs>
<hr/>
**6. With System Prompt Variables**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const agent = new AnthropicAgent({
name: 'Anthropic Assistant',
description: 'An assistant with variable prompt',
apiKey: 'your-anthropic-api-key',
customSystemPrompt: {
template: 'You are an AI assistant specialized in {{DOMAIN}}. Always use a {{TONE}} tone.',
variables: {
DOMAIN: 'customer support',
TONE: 'friendly and helpful'
}
}
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
agent = AnthropicAgent(AnthropicAgentOptions(
name='Anthropic Assistant',
description='An assistant with variable prompt',
api_key='your-anthropic-api-key',
custom_system_prompt={
'template': 'You are an AI assistant specialized in {{DOMAIN}}. Always use a {{TONE}} tone.',
'variables': {
'DOMAIN': 'customer support',
'TONE': 'friendly and helpful'
}
}
))
```
</TabItem>
</Tabs>
<hr/>
**7. With Custom Retriever**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const retriever = new CustomRetriever({
// Retriever configuration
});
const agent = new AnthropicAgent({
name: 'Anthropic Assistant',
description: 'An assistant with retriever',
apiKey: 'your-anthropic-api-key',
retriever: retriever
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
retriever = CustomRetriever(
# Retriever configuration
)
agent = AnthropicAgent(AnthropicAgentOptions(
name='Anthropic Assistant',
description='An assistant with retriever',
api_key='your-anthropic-api-key',
retriever=retriever
))
```
</TabItem>
</Tabs>
<hr/>
**8. With Tool Configuration**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const agent = new AnthropicAgent({
name: 'Anthropic Assistant',
description: 'An assistant with tool support',
apiKey: 'your-anthropic-api-key',
toolConfig: {
tool: [
{
name: "Weather_Tool",
description: "Get current weather data",
input_schema: {
type: "object",
properties: {
location: {
type: "string",
description: "City name",
}
},
required: ["location"]
}
}
],
useToolHandler: (response, conversation) => {
return {
role: ParticipantRole.USER,
content: {
"type": "tool_result",
"tool_use_id": "weather_tool",
"content": "Current weather data for the location"
}
}
}
}
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
agent = AnthropicAgent(AnthropicAgentOptions(
name='Anthropic Assistant',
description='An assistant with tool support',
api_key='your-anthropic-api-key',
tool_config={
'tool': [{
'name': 'Weather_Tool',
'description': 'Get current weather data',
'input_schema': {
'type': 'object',
'properties': {
'location': {
'type': 'string',
'description': 'City name'
}
},
'required': ['location']
}
}],
'useToolHandler': lambda response, conversation: {
'role': ParticipantRole.USER.value,
'content': {
'type': 'tool_result',
'tool_use_id': 'weather_tool',
'content': 'Current weather data for the location'
}
}
}
))
```
</TabItem>
</Tabs>
<hr/>
**9. With Reasoning enabled**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { AnthropicAgent } from 'agent-squad';
const agent = new AnthropicAgent({
name: "Tech Agent",
description: "Specializes in technology areas including software development, hardware, AI, cybersecurity, blockchain, cloud computing, emerging tech innovations, and pricing/costs related to technology products and services.",
inferenceConfig: {
maxTokens: 2500,
temperature: 1, // 1 for thinking
topP: 0.96 // 0.95 or above
},
modelId: "claude-3-7-sonnet-20250219", // Claude 3.7 or above
thinking: {type: "enabled", budget_tokens: 1024},
streaming: true,
apiKey: 'your-anthropic-api-key',
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
agent = AnthropicAgent(
AnthropicAgentOptions(
name="Tech Agent",
api_key='your-anthropic-api-key',
streaming=True,
description="Specializes in technology areas including software development, hardware, AI, \
cybersecurity, blockchain, cloud computing, emerging tech innovations, and pricing/costs \
related to technology products and services.",
model_id="claude-3-7-sonnet-20250219",
callbacks=LLMAgentCallbacks(),
inference_config={"maxTokens": 2500, "temperature": 1, "topP": 0.95}, # temperature set to 1 and topP 0.95 or above
thinking={"type": "enabled", "budget_tokens": 2000},
)
)
```
</TabItem>
</Tabs>
<hr/>
**10. Complete Example with All Options**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { AnthropicAgent } from 'agent-squad';
const agent = new AnthropicAgent({
// Required fields
name: 'Advanced Anthropic Assistant',
description: 'A fully configured AI assistant powered by Anthropic models',
apiKey: 'your-anthropic-api-key',
// Optional fields
modelId: 'claude-3-opus-20240229', // Choose Anthropic model
streaming: true, // Enable streaming responses
retriever: customRetriever, // Custom retriever for additional context
// Inference configuration
inferenceConfig: {
maxTokens: 500, // Maximum tokens to generate
temperature: 0.7, // Control randomness (0-1)
topP: 0.9, // Control diversity via nucleus sampling
stopSequences: ['Human:', 'AI:'] // Sequences that stop generation
},
// Tool configuration
toolConfig: {
tool: [{
name: "Weather_Tool",
description: "Get the current weather for a given location",
input_schema: {
type: "object",
properties: {
latitude: {
type: "string",
description: "Geographical WGS84 latitude"
},
longitude: {
type: "string",
description: "Geographical WGS84 longitude"
}
},
required: ["latitude", "longitude"]
}
}],
useToolHandler: (response, conversation) => ({
role: ParticipantRole.USER,
content: {
type: "tool_result",
tool_use_id: "tool_user_id",
content: "Response from the tool"
}
})
},
// Custom system prompt with variables
customSystemPrompt: {
template: `You are an AI assistant specialized in {{DOMAIN}}.
Your core competencies:
{{SKILLS}}
Communication style:
- Maintain a {{TONE}} tone
- Focus on {{FOCUS}}
- Prioritize {{PRIORITY}}`,
variables: {
DOMAIN: 'scientific research',
SKILLS: [
'- Advanced data analysis',
'- Statistical methodology',
'- Research design',
'- Technical writing'
],
TONE: 'professional and academic',
FOCUS: 'accuracy and clarity',
PRIORITY: 'evidence-based insights'
}
}
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
from agent_squad import AnthropicAgent, AnthropicAgentOptions
from agent_squad.types import ParticipantRole
agent = AnthropicAgent(AnthropicAgentOptions(
# Required fields
name='Advanced Anthropic Assistant',
description='A fully configured AI assistant powered by Anthropic models',
api_key='your-anthropic-api-key',
# Optional fields
model_id='claude-3-opus-20240229', # Choose Anthropic model
streaming=True, # Enable streaming responses
retriever=custom_retriever, # Custom retriever for additional context
# Inference configuration
inference_config={
'maxTokens': 500, # Maximum tokens to generate
'temperature': 0.7, # Control randomness (0-1)
'topP': 0.9, # Control diversity via nucleus sampling
'stopSequences': ['Human:', 'AI:'] # Sequences that stop generation
},
# Tool configuration
tool_config={
'tool': [{
'name': 'Weather_Tool',
'description': 'Get the current weather for a given location',
'input_schema': {
'type': 'object',
'properties': {
'latitude': {
'type': 'string',
'description': 'Geographical WGS84 latitude'
},
'longitude': {
'type': 'string',
'description': 'Geographical WGS84 longitude'
}
},
'required': ['latitude', 'longitude']
}
}],
'useToolHandler': lambda response, conversation: {
'role': ParticipantRole.USER.value,
'content': {
'type': 'tool_result',
'tool_use_id': 'tool_user_id',
'content': 'Response from the tool'
}
}
},
# Custom system prompt with variables
custom_system_prompt={
'template': """You are an AI assistant specialized in {{DOMAIN}}.
Your core competencies:
{{SKILLS}}
Communication style:
- Maintain a {{TONE}} tone
- Focus on {{FOCUS}}
- Prioritize {{PRIORITY}}""",
'variables': {
'DOMAIN': 'scientific research',
'SKILLS': [
'- Advanced data analysis',
'- Statistical methodology',
'- Research design',
'- Technical writing'
],
'TONE': 'professional and academic',
'FOCUS': 'accuracy and clarity',
'PRIORITY': 'evidence-based insights'
}
}
))
```
</TabItem>
</Tabs>
### Option Explanations
- `name` and `description`: Identify and describe the agent's purpose.
- `apiKey`: Your Anthropic API key for authentication.
- `modelId`: Specifies the LLM model to use (e.g., Claude 3 Sonnet).
- `streaming`: Enables streaming responses for real-time output.
- `inferenceConfig`: Fine-tunes the model's output characteristics.
- `retriever`: Integrates a retrieval system for enhanced context.
- `toolConfig`: Defines tools the agent can use and how to handle their responses ([See AgentTools for Agents for seamless tool definition](/agent-squad/agents/tools))
## Setting a New Prompt
You can dynamically set or update the system prompt for the agent:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
agent.setSystemPrompt(
`You are an AI assistant specialized in {{DOMAIN}}.
Your main goal is to {{GOAL}}.
Always maintain a {{TONE}} tone in your responses.`,
{
DOMAIN: "cybersecurity",
GOAL: "help users understand and mitigate potential security threats",
TONE: "professional and reassuring"
}
);
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
agent.set_system_prompt(
"""You are an AI assistant specialized in {{DOMAIN}}.
Your main goal is to {{GOAL}}.
Always maintain a {{TONE}} tone in your responses.""",
{
"DOMAIN": "cybersecurity",
"GOAL": "help users understand and mitigate potential security threats",
"TONE": "professional and reassuring"
}
)
```
</TabItem>
</Tabs>
This method allows you to dynamically change the agent's behavior and focus without creating a new instance.
## Adding the Agent to the Orchestrator
To integrate the **Anthropic Agent** into your orchestrator, follow these steps:
1. First, ensure you have created an instance of the orchestrator:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { AgentSquad } from "agent-squad";
const orchestrator = new AgentSquad();
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
from agent_squad.orchestrator import AgentSquad
orchestrator = AgentSquad()
```
</TabItem>
</Tabs>
2. Then, add the agent to the orchestrator:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
orchestrator.addAgent(agent);
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
orchestrator.add_agent(agent)
```
</TabItem>
</Tabs>
3. Now you can use the orchestrator to route requests to the appropriate agent, including your Anthropic agent:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const response = await orchestrator.routeRequest(
"What is the base rate interest for 30 years?",
"user123",
"session456"
);
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
response = await orchestrator.route_request(
"What is the base rate interest for 30 years?",
"user123",
"session456"
)
```
</TabItem>
</Tabs>
---
By leveraging the **AnthropicAgent**, you can create sophisticated, context-aware AI agents capable of handling a wide range of tasks and interactions, all powered by the latest LLM models available through Anthropic's platform.
================================================
FILE: docs/src/content/docs/agents/built-in/bedrock-flows-agent.mdx
================================================
---
title: Amazon Bedrock Flows Agent
description: Documentation for the BedrockFlowsAgent in the Agent Squad
---
## Overview
The **Bedrock Flows Agent** is a specialized agent class in the Agent Squad that integrates directly with [Amazon Bedrock Flows](https://aws.amazon.com/bedrock/flows/).
This integration enables you to orchestrate your Bedrock Flows alongside other agent types (Bedrock Agent, Lex, Bedrock API...), providing a unified and flexible approach to agents orchestration.
## Key Features
- Support for cross-region Bedrock Flows invocation
- Support for multiple flow input output type via flow input/output encoder/decoder callbacks
## Creating a BedrockFlowsAgent
### Python Package
If you haven't already installed the AWS-related dependencies, make sure to install them:
```bash
pip install "agent-squad[aws]"
```
### Basic Example
import { Tabs, TabItem } from '@astrojs/starlight/components';
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { BedrockFlowsAgent } from 'agent-squad';
const techFlowAgent = new BedrockFlowsAgent({
name: 'tech-flow-agent',
description: 'Specialized in AWS services',
flowIdentifier: 'AEXAMPLID',
flowAliasIdentifier: 'AEXAMPLEALIASID',
enableTrace:true
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
from agent_squad.agents import BedrockFlowsAgent, BedrockFlowsAgentOptions
tech_flow_agent = BedrockFlowsAgent(BedrockFlowsAgentOptions(
name="tech-flow-agent",
description="Specializes in handling tech questions about AWS services",
flowIdentifier='AEXAMPLID',
flowAliasIdentifier='AEXAMPLEALIASID',
enableTrace=True
))
```
</TabItem>
</Tabs>
### Flow Input Encoder callback
Amazon [Bedrock Flows Input](https://docs.aws.amazon.com/bedrock/latest/userguide/flows-nodes.html) supports multiple type of document output:
- String
- Number
- Boolean
- Object
- Array
In the default definition of the BedrockFlowsAgent, the output document type is a string.
If you need to send an object, array, number or a boolean to your Flow input, you can use the flow input callback to transform the input payload based on your needs.
Here are an example for TS and python:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
// implementation of the custom flowInputEncoder callback
const flowInputEncoder = (
agent: Agent,
input: string,
kwargs: {
userId?: string,
sessionId?: string,
chatHistory?: any[],
[key: string]: any // This allows any additional properties
}
) => {
if (agent.name == 'tech-flow-agent'){
return {
"question":input,
};
} else {
return input
}
}
// passing flowInputEncoder to our BedrockFlowsAgent
const techFlowAgent = new BedrockFlowsAgent({
name: 'tech-flow-agent',
description: 'Specialized in AWS services',
flowIdentifier: 'AEXAMPLID',
flowAliasIdentifier: 'AEXAMPLEALIASID',
flowInputEncoder: flowInputEncoder,
enableTrace: true
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
# implementation of the custom flowInputEncoder callback
def flow_input_encoder(agent:Agent, input: str, **kwargs) -> Any:
if agent.name == 'tech-flow-agent':
# return a dict
return {
"question": input
}
else:
return input #input as string
# passing flowInputEncoder to our BedrockFlowsAgent
tech_flow_agent = BedrockFlowsAgent(BedrockFlowsAgentOptions(
name="tech-flow-agent",
description="Specializes in handling tech questions about AWS services",
flowIdentifier='AEXAMPLID',
flowAliasIdentifier='AEXAMPLEALIASID',
flow_input_encoder=flow_input_encoder,
enableTrace=True
))
```
</TabItem>
</Tabs>
## Sample Code
You can find sample code for using the BedrockFlowsAgent in both TypeScript and Python:
- [TypeScript Sample](https://github.com/awslabs/agent-squad/tree/main/examples/bedrock-flows/typescript)
- [Python Sample](https://github.com/awslabs/agent-squad/tree/main/examples/bedrock-flows/python)
================================================
FILE: docs/src/content/docs/agents/built-in/bedrock-inline-agent.mdx
================================================
---
title: Bedrock Inline Agent
description: Documentation for the BedrockInlineAgent in the Agent Squad
---
## Overview
The **Bedrock Inline Agent** represents a powerful new approach to dynamic agent creation. At its core, it leverages [Amazon Bedrock's Converse API](https://docs.aws.amazon.com/bedrock/latest/userguide/conversation-inference.html) and its tool capabilities to interact with foundation models and orchestrate agent creation. Through a specialized tool, it intelligently analyzes user requests and selects the most relevant action groups and knowledge bases from your available resources.
Once the optimal [Action Groups](https://docs.aws.amazon.com/bedrock/latest/userguide/agents-action-create.html) and/or [Knowledge Bases](https://aws.amazon.com/bedrock/knowledge-bases/) are identified, the agent uses the [InvokeInlineAgent API](https://docs.aws.amazon.com/bedrock/latest/userguide/agents-create-inline.html) to dynamically create purpose-specific Agents for Amazon Bedrock. This eliminates the need to pre-configure static agent combinations - instead, agents are created on-demand with precisely the capabilities needed for each specific request.
This architecture removes practical limits on the number of action groups and knowledge bases you can maintain. Whether you have dozens or hundreds of different action groups and knowledge bases, the agent can efficiently select and combine just the ones needed for each query. This enables sophisticated use cases that would be impractical with traditional static agent configurations.
## Key Features
- Dynamic agent creation through InvokeInlineAgent API
- Tool-based selection of action groups and knowledge bases
- Support for multiple foundation models
- Customizable inference configuration
- Enhanced debug logging capabilities
- Support for custom logging implementations
## Creating a BedrockInlineAgent
### Python Package
If you haven't already installed the AWS-related dependencies, make sure to install them:
```bash
pip install "agent-squad[aws]"
```
### Basic Example
import { Tabs, TabItem } from '@astrojs/starlight/components';
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { BedrockInlineAgent } from 'agent-squad';
import { CustomLogger } from './logger';
const actionGroups = [
{
actionGroupName: "OrderManagement",
description: "Handles order-related operations like status checks and updates"
},
{
actionGroupName: "InventoryLookup",
description: "Checks product availability and stock levels"
}
];
const knowledgeBases = [
{
knowledgeBaseId: "KB001",
description: "Product catalog and specifications"
}
];
const agent = new BedrockInlineAgent({
name: 'Inline Agent Creator for Agents for Amazon Bedrock',
description: 'Specialized in creating Agent to solve customer request dynamically. You are provided with a list of Action groups and Knowledge bases which can help you in answering customer request',
actionGroupsList: actionGroups,
knowledgeBases: knowledgeBases,
region: "us-east-1",
LOG_AGENT_DEBUG_TRACE: true,
inferenceConfig: {
maxTokens: 500,
temperature: 0.5,
topP: 0.9
}
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
from agent_squad.agents import BedrockInlineAgent, BedrockInlineAgentOptions
from custom_logger import CustomLogger
action_groups = [
{
"actionGroupName": "OrderManagement",
"description": "Handles order-related operations like status checks and updates"
},
{
"actionGroupName": "InventoryLookup",
"description": "Checks product availability and stock levels"
}
]
knowledge_bases = [
{
"knowledgeBaseId": "KB001",
"description": "Product catalog and specifications"
}
]
agent = BedrockInlineAgent(BedrockInlineAgentOptions(
name='Inline Agent Creator for Agents for Amazon Bedrock',
description='Specialized in creating Agent to solve customer request dynamically. You are provided with a list of Action groups and Knowledge bases which can help you in answering customer request',
action_groups_list=action_groups,
knowledge_bases=knowledge_bases,
region="us-east-1",
LOG_AGENT_DEBUG_TRACE=True,
inference_config={
'maxTokens': 500,
'temperature': 0.5,
'topP': 0.9
}
))
```
</TabItem>
</Tabs>
## Debug Logging
### LOG_AGENT_DEBUG_TRACE
When enabled, this flag activates detailed debug logging that helps you understand the agent's operation. Example output:
```text
> BedrockInlineAgent
> Inline Agent Creator for Agents for Amazon Bedrock
> System Prompt
> You are a Inline Agent Creator for Agents for Amazon Bedrock...
> BedrockInlineAgent
> Inline Agent Creator for Agents for Amazon Bedrock
> Tool Handler Parameters
> {
userRequest: 'Please execute...',
actionGroupNames: ['CodeInterpreterAction'],
knowledgeBases: [],
description: 'To solve this request...',
sessionId: 'session-456'
}
> BedrockInlineAgent
> Inline Agent Creator for Agents for Amazon Bedrock
> Action Group & Knowledge Base
> {
actionGroups: [
{
actionGroupName: 'CodeInterpreterAction',
parentActionGroupSignature: 'AMAZON.CodeInterpreter'
}
],
knowledgeBases: []
}
```
### Custom Logger Implementation
You can provide your own logger implementation to customize log formatting and handling. Here's an example:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
export class CustomLogger {
private static instance: CustomLogger;
private constructor() {}
static getInstance(): CustomLogger {
if (!CustomLogger.instance) {
CustomLogger.instance = new CustomLogger();
}
return CustomLogger.instance;
}
info(message: string, ...args: any[]): void {
console.info(">>: " + message, ...args);
}
warn(message: string, ...args: any[]): void {
console.warn(">>: " + message, ...args);
}
error(message: string, ...args: any[]): void {
console.error(">>: " + message, ...args);
}
debug(message: string, ...args: any[]): void {
console.debug(">>: " + message, ...args);
}
log(message: string, ...args: any[]): void {
console.log(">>: " + message, ...args);
}
}
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
class CustomLogger:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(CustomLogger, cls).__new__(cls)
return cls._instance
@classmethod
def get_instance(cls):
if cls._instance is None:
cls._instance = CustomLogger()
return cls._instance
def info(self, message: str, *args):
print(f">>: {message}", *args)
def warn(self, message: str, *args):
print(f">>: [WARNING] {message}", *args)
def error(self, message: str, *args):
print(f">>: [ERROR] {message}", *args)
def debug(self, message: str, *args):
print(f">>: [DEBUG] {message}", *args)
def log(self, message: str, *args):
print(f">>: {message}", *args)
```
</TabItem>
</Tabs>
## Sample Code
You can find sample code for using the BedrockInlineAgent in both TypeScript and Python:
- [TypeScript Sample](https://github.com/awslabs/agent-squad/tree/main/examples/bedrock-inline-agents/typescript)
- [Python Sample](https://github.com/awslabs/agent-squad/tree/main/examples/bedrock-inline-agents/python)
The BedrockInlineAgent represents a significant advancement in agent flexibility and efficiency, enabling truly dynamic, context-aware responses while optimizing resource usage.
================================================
FILE: docs/src/content/docs/agents/built-in/bedrock-llm-agent.mdx
================================================
---
title: Bedrock LLM Agent
description: Documentation for the BedrockLLMAgent in the Agent Squad
---
## Overview
The **Bedrock LLM Agent** is a powerful and flexible agent class in the Agent Squad System. It leverages [Amazon Bedrock's Converse API](https://docs.aws.amazon.com/bedrock/latest/userguide/conversation-inference.html) to interact with various LLMs supported by Amazon Bedrock.
This agent can handle a wide range of processing tasks, making it suitable for diverse applications such as conversational AI, question-answering systems, and more.
## Key Features
- Integration with Amazon Bedrock's Converse API
- Support for multiple LLM models available on Amazon Bedrock
- Streaming and non-streaming response options
- Customizable inference configuration
- Ability to set and update custom system prompts
- Optional integration with [retrieval systems](/agent-squad/retrievers/overview) for enhanced context
- Support for [Tool use](https://docs.aws.amazon.com/bedrock/latest/userguide/tool-use.html) within the conversation flow
## Creating a BedrockLLMAgent
By default, the **Bedrock LLM Agent** uses the `anthropic.claude-3-haiku-20240307-v1:0` model.
### Python Package
If you haven't already installed the AWS-related dependencies, make sure to install them:
```bash
pip install "agent-squad[aws]"
```
**1. Minimal Configuration**
import { Tabs, TabItem } from '@astrojs/starlight/components';
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const agent = new BedrockLLMAgent({
name: 'Bedrock Assistant',
description: 'A versatile AI assistant'
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
agent = BedrockLLMAgent(BedrockLLMAgentOptions(
name='Bedrock Assistant',
description='A versatile AI assistant'
))
```
</TabItem>
</Tabs>
<hr/>
**2. Using Custom Client**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime";
const customClient = new BedrockRuntimeClient({ region: 'us-east-1' });
const agent = new BedrockLLMAgent({
name: 'Bedrock Assistant',
description: 'A versatile AI assistant',
client: customClient
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
import boto3
custom_client = boto3.client('bedrock-runtime', region_name='us-east-1')
agent = BedrockLLMAgent(BedrockLLMAgentOptions(
name='Bedrock Assistant',
description='A versatile AI assistant',
client=custom_client
))
```
</TabItem>
</Tabs>
<hr/>
**3. Custom Model and Streaming**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const agent = new BedrockLLMAgent({
name: 'Bedrock Assistant',
description: 'A streaming-enabled assistant',
modelId: 'anthropic.claude-3-sonnet-20240229-v1:0',
streaming: true
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
agent = BedrockLLMAgent(BedrockLLMAgentOptions(
name='Bedrock Assistant',
description='A streaming-enabled assistant',
model_id='anthropic.claude-3-sonnet-20240229-v1:0',
streaming=True
))
```
</TabItem>
</Tabs>
<hr/>
**4. With Inference Configuration**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const agent = new BedrockLLMAgent({
name: 'Bedrock Assistant',
description: 'An assistant with custom inference settings',
inferenceConfig: {
maxTokens: 500,
temperature: 0.7,
topP: 0.9,
stopSequences: ['Human:', 'AI:']
}
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
agent = BedrockLLMAgent(BedrockLLMAgentOptions(
name='Bedrock Assistant',
description='An assistant with custom inference settings',
inference_config={
'maxTokens': 500,
'temperature': 0.7,
'topP': 0.9,
'stopSequences': ['Human:', 'AI:']
}
))
```
</TabItem>
</Tabs>
<hr/>
**5. With Simple System Prompt**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const agent = new BedrockLLMAgent({
name: 'Bedrock Assistant',
description: 'An assistant with custom prompt',
customSystemPrompt: {
template: 'You are a helpful AI assistant focused on technical support.'
}
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
agent = BedrockLLMAgent(BedrockLLMAgentOptions(
name='Bedrock Assistant',
description='An assistant with custom prompt',
custom_system_prompt={
'template': 'You are a helpful AI assistant focused on technical support.'
}
))
```
</TabItem>
</Tabs>
<hr/>
**6. With System Prompt Variables**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const agent = new BedrockLLMAgent({
name: 'Bedrock Assistant',
description: 'An assistant with variable prompt',
customSystemPrompt: {
template: 'You are an AI assistant specialized in {{DOMAIN}}. Always use a {{TONE}} tone.',
variables: {
DOMAIN: 'technical support',
TONE: 'friendly and helpful'
}
}
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
agent = BedrockLLMAgent(BedrockLLMAgentOptions(
name='Bedrock Assistant',
description='An assistant with variable prompt',
custom_system_prompt={
'template': 'You are an AI assistant specialized in {{DOMAIN}}. Always use a {{TONE}} tone.',
'variables': {
'DOMAIN': 'technical support',
'TONE': 'friendly and helpful'
}
}
))
```
</TabItem>
</Tabs>
<hr/>
**7. With Custom Retriever**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const retriever = new CustomRetriever({
// Retriever configuration
});
const agent = new BedrockLLMAgent({
name: 'Bedrock Assistant',
description: 'An assistant with retriever',
retriever: retriever
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
retriever = CustomRetriever(
# Retriever configuration
)
agent = BedrockLLMAgent(BedrockLLMAgentOptions(
name='Bedrock Assistant',
description='An assistant with retriever',
retriever=retriever
))
```
</TabItem>
</Tabs>
<hr/>
**8. With Tool Configuration**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const agent = new BedrockLLMAgent({
name: 'Bedrock Assistant',
description: 'An assistant with tool support',
toolConfig: {
tool: [
{
name: "Weather_Tool",
description: "Get current weather data",
input_schema: {
type: "object",
properties: {
location: {
type: "string",
description: "City name",
}
},
required: ["location"]
}
}
]
}
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
agent = BedrockLLMAgent(BedrockLLMAgentOptions(
name='Bedrock Assistant',
description='An assistant with tool support',
tool_config={
'tool': [{
'name': 'Weather_Tool',
'description': 'Get current weather data',
'input_schema': {
'type': 'object',
'properties': {
'location': {
'type': 'string',
'description': 'City name'
}
},
'required': ['location']
}
}]
}
))
```
</TabItem>
</Tabs>
<hr/>
**9. With Thinking enabled**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const agent = new BedrockLLMAgent({
name: "Tech Agent",
modelId: "us.anthropic.claude-3-7-sonnet-20250219-v1:0",
description:"Specializes in technology areas including software development, hardware, AI, cybersecurity, \
blockchain, cloud computing, emerging tech innovations, and pricing/costs related to technology products and services.",
inferenceConfig: {
maxTokens: 2500,
temperature: 1, // 1 for thinking and unset topP
},
additional_model_request_fields: {
thinking: {type: "enabled", budget_tokens: 1024},
},
streaming: true,
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
agent = BedrockLLMAgent(
BedrockLLMAgentOptions(
name="Tech Agent",
streaming=False,
description="Specializes in technology areas including software development, hardware, AI, \
cybersecurity, blockchain, cloud computing, emerging tech innovations, and pricing/costs \
related to technology products and services.",
model_id="us.anthropic.claude-3-7-sonnet-20250219-v1:0",
callbacks=LLMAgentCallbacks(),
inference_config={"maxTokens": 2500, "temperature": 1},
additional_model_request_fields={"thinking": {"type": "enabled", "budget_tokens": 2000}},
)
)
```
</TabItem>
</Tabs>
<hr/>
**10. Complete Example with All Options**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { BedrockLLMAgent } from "agent-squad";
const agent = new BedrockLLMAgent({
// Required fields
name: "Advanced Bedrock Assistant",
description: "A fully configured AI assistant powered by Bedrock models",
// Optional fields
modelId: "anthropic.claude-3-sonnet-20240229-v1:0",
region: "us-west-2",
streaming: true,
retriever: customRetriever, // Custom retriever for additional context
inferenceConfig: {
maxTokens: 500,
temperature: 0.7,
topP: 0.9,
stopSequences: ["Human:", "AI:"],
},
guardrailConfig: {
guardrailIdentifier: "my-guardrail",
guardrailVersion: "1.0",
},
toolConfig: {
tool: [
{
name: "Weather_Tool",
description: "Get current weather data",
input_schema: {
type: "object",
properties: {
location: {
type: "string",
description: "City name",
},
},
required: ["location"],
},
},
],
},
customSystemPrompt: {
template: `You are an AI assistant specialized in {{DOMAIN}}.
Your core competencies:
{{SKILLS}}
Communication style:
- Maintain a {{TONE}} tone
- Focus on {{FOCUS}}
- Prioritize {{PRIORITY}}`,
variables: {
DOMAIN: "scientific research",
SKILLS: [
"- Advanced data analysis",
"- Statistical methodology",
"- Research design",
"- Technical writing",
],
TONE: "professional and academic",
FOCUS: "accuracy and clarity",
PRIORITY: "evidence-based insights",
},
},
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
from agent_squad.agents import BedrockLLMAgent, BedrockLLMAgentOptions
agent = BedrockLLMAgent(BedrockLLMAgentOptions(
# Required fields
name='Advanced Bedrock Assistant',
description='A fully configured AI assistant powered by Bedrock models',
# Optional fields
model_id='anthropic.claude-3-sonnet-20240229-v1:0',
region='us-west-2',
streaming=True,
retriever=custom_retriever, # Custom retriever for additional context
inference_config={
'maxTokens': 500,
'temperature': 0.7,
'topP': 0.9,
'stopSequences': ['Human:', 'AI:']
},
guardrail_config={
'guardrailIdentifier': 'my-guardrail',
'guardrailVersion': '1.0'
},
tool_config={
'tool': [{
'name': 'Weather_Tool',
'description': 'Get current weather data',
'input_schema': {
'type': 'object',
'properties': {
'location': {
'type': 'string',
'description': 'City name'
}
},
'required': ['location']
}
}]
},
custom_system_prompt={
'template': """You are an AI assistant specialized in {{DOMAIN}}.
Your core competencies:
{{SKILLS}}
Communication style:
- Maintain a {{TONE}} tone
- Focus on {{FOCUS}}
- Prioritize {{PRIORITY}}""",
'variables': {
'DOMAIN': 'scientific research',
'SKILLS': [
'- Advanced data analysis',
'- Statistical methodology',
'- Research design',
'- Technical writing'
],
'TONE': 'professional and academic',
'FOCUS': 'accuracy and clarity',
'PRIORITY': 'evidence-based insights'
}
}
))
```
</TabItem>
</Tabs>
<hr/>
The `BedrockLLMAgent` provides multiple ways to set custom prompts. You can set them either during initialization or after the agent is created, and you can use prompts with or without variables.
**11. Setting Custom Prompt After Initialization (Without Variables)**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const agent = new BedrockLLMAgent({
name: 'Business Consultant',
description: 'Business strategy and management expert'
});
agent.setSystemPrompt(`You are a business strategy consultant.
Key Areas of Focus:
1. Strategic Planning
2. Market Analysis
3. Risk Management
4. Performance Optimization
When providing business advice:
- Begin with clear objectives
- Use data-driven insights
- Consider market context
- Provide actionable steps`);
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
agent = BedrockLLMAgent(BedrockLLMAgentOptions(
name='Business Consultant',
description='Business strategy and management expert'
))
agent.set_system_prompt("""You are a business strategy consultant.
Key Areas of Focus:
1. Strategic Planning
2. Market Analysis
3. Risk Management
4. Performance Optimization
When providing business advice:
- Begin with clear objectives
- Use data-driven insights
- Consider market context
- Provide actionable steps""")
```
</TabItem>
</Tabs>
<hr/>
**12. Setting Custom Prompt After Initialization (With Variables)**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const agent = new BedrockLLMAgent({
name: 'Education Expert',
description: 'Educational specialist and learning consultant'
});
agent.setSystemPrompt(
`You are a {{ROLE}} focusing on {{SPECIALTY}}.
Your expertise includes:
{{EXPERTISE}}
Teaching approach:
{{APPROACH}}
Core principles:
{{PRINCIPLES}}
Always maintain a {{TONE}} tone.`,
{
ROLE: 'education specialist',
SPECIALTY: 'personalized learning',
EXPERTISE: [
'- Curriculum development',
'- Learning assessment',
'- Educational technology'
],
APPROACH: [
'- Student-centered learning',
'- Active engagement',
'- Continuous feedback'
],
PRINCIPLES: [
'- Clear objectives',
'- Scaffolded learning',
'- Regular assessment'
],
TONE: 'supportive and encouraging'
}
);
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
agent = BedrockLLMAgent(BedrockLLMAgentOptions(
name='Education Expert',
description='Educational specialist and learning consultant'
))
agent.set_system_prompt(
"""You are a {{ROLE}} focusing on {{SPECIALTY}}.
Your expertise includes:
{{EXPERTISE}}
Teaching approach:
{{APPROACH}}
Core principles:
{{PRINCIPLES}}
Always maintain a {{TONE}} tone.""",
{
"ROLE": "education specialist",
"SPECIALTY": "personalized learning",
"EXPERTISE": [
"- Curriculum development",
"- Learning assessment",
"- Educational technology"
],
"APPROACH": [
"- Student-centered learning",
"- Active engagement",
"- Continuous feedback"
],
"PRINCIPLES": [
"- Clear objectives",
"- Scaffolded learning",
"- Regular assessment"
],
"TONE": "supportive and encouraging"
}
)
```
</TabItem>
</Tabs>
### Notes on Custom Prompts
- Variables in templates use the `{{VARIABLE_NAME}}` syntax
- When using arrays in variables, items are automatically joined with newlines
- The same template and variable functionality is available both during initialization and after
- Variables are optional - you can use plain text templates without any variables
- Setting a new prompt will completely replace the previous prompt
- The agent will use its default prompt if no custom prompt is specified
Choose the approach that best fits your needs:
- Use initialization when the prompt is part of the agent's core configuration
- Use post-initialization when prompts need to be changed dynamically
- Use variables when parts of the prompt need to be modified frequently
- Use direct templates when the prompt is static
### Option Explanations
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
| Parameter | Description | Required/Optional |
|------------|-------------|-------------------|
| `name` | Identifies the agent within the system | **Required** |
| `description` | Describes the agent's purpose and capabilities | **Required** |
| `modelId` | Specifies the LLM model to use (e.g., Claude 3 Sonnet) | Optional |
| `region` | AWS region for the Bedrock service | Optional |
| `streaming` | Enables streaming responses for real-time output | Optional |
| `inferenceConfig` | Fine-tunes the model's output characteristics | Optional |
| `guardrailConfig` | Applies predefined guardrails to the model's responses | Optional |
| `reasoningConfig` | Enables thinking and configuration for budget_tokens | Optional |
| `retriever` | Integrates a retrieval system for enhanced context | Optional |
| `toolConfig` | Defines tools the agent can use and how to handle their responses | Optional |
| `customSystemPrompt` | Defines the agent's system prompt and behavior, with optional variables for dynamic content | Optional |
| `client` | Optional custom Bedrock client for specialized configurations | Optional |
</TabItem>
<TabItem label="Python" icon="seti:python">
| Parameter | Description | Required/Optional |
|--------|-------------|-------------------|
| `name` | Identifies the agent within the system | **Required** |
| `description` | Describes the agent's purpose and capabilities | **Required** |
| `model_id` | Specifies the LLM model to use (e.g., Claude 3 Sonnet) | Optional |
| `region` | AWS region for the Bedrock service | Optional |
| `streaming` | Enables streaming responses for real-time output | Optional |
| `inference_config` | Fine-tunes the model's output characteristics | Optional |
| `guardrail_config` | Applies predefined guardrails to the model's responses | Optional |
| `additional_model_request_fields` | Additional fields to send to the model, including thinking capability | Optional |
| `retriever` | Integrates a retrieval system for enhanced context | Optional |
| `tool_config` | Defines tools the agent can use and how to handle their responses | Optional |
| `custom_system_prompt` | Defines the agent's system prompt and behavior, with optional variables for dynamic content | Optional |
| `client` | Optional custom Bedrock client for specialized configurations | Optional |
</TabItem>
</Tabs>
================================================
FILE: docs/src/content/docs/agents/built-in/bedrock-translator-agent.mdx
================================================
---
title: Bedrock Translator Agent
description: Documentation for the Bedrock Translator Agent in the Agent Squad System
---
The `BedrockTranslatorAgent` uses Amazon Bedrock's language models to translate text between different languages.
## Key Features
- Utilizes Amazon Bedrock's language models
- Supports translation between multiple languages
- Allows dynamic setting of source and target languages
- Can be used standalone or as part of a [ChainAgent](/agent-squad/agents/built-in/chain-agent)
- Configurable inference parameters for fine-tuned control
## Creating a Bedrock Translator Agent
### Python Package
If you haven't already installed the AWS-related dependencies, make sure to install them:
```bash
pip install "agent-squad[aws]"
```
### Basic Example
To create a new `BedrockTranslatorAgent` with minimal configuration:
import { Tabs, TabItem } from '@astrojs/starlight/components';
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { BedrockTranslatorAgent, BedrockTranslatorAgentOptions } from 'agent-squad';
const agent = new BedrockTranslatorAgent({
name: 'BasicTranslator',
description: 'Translates text to English',
targetLanguage: 'English'
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
from agent_squad.agents import BedrockTranslatorAgent, BedrockTranslatorAgentOptions
agent = BedrockTranslatorAgent(BedrockTranslatorAgentOptions(
name='BasicTranslator',
description='Translates text to English',
target_language='English'
))
```
</TabItem>
</Tabs>
### Advanced Example
For more complex use cases, you can create a BedrockTranslatorAgent with custom settings:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { BedrockTranslatorAgent, BedrockTranslatorAgentOptions, BEDROCK_MODEL_ID_CLAUDE_3_SONNET } from 'agent-squad';
const options: BedrockTranslatorAgentOptions = {
name: 'AdvancedTranslator',
description: 'Advanced translator with custom settings',
sourceLanguage: 'French',
targetLanguage: 'German',
modelId: BEDROCK_MODEL_ID_CLAUDE_3_SONNET,
region: 'us-west-2',
inferenceConfig: {
maxTokens: 2000,
temperature: 0.1,
topP: 0.95,
stopSequences: ['###']
}
};
const agent = new BedrockTranslatorAgent(options);
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
from agent_squad.agents import BedrockTranslatorAgent, BedrockTranslatorAgentOptions
from agent_squad.types import BEDROCK_MODEL_ID_CLAUDE_3_SONNET
options = BedrockTranslatorAgentOptions(
name='AdvancedTranslator',
description='Advanced translator with custom settings',
source_language='French',
target_language='German',
model_id=BEDROCK_MODEL_ID_CLAUDE_3_SONNET,
region='us-west-2',
inference_config={
'maxTokens': 2000,
'temperature': 0.1,
'topP': 0.95,
'stopSequences': ['###']
}
)
agent = BedrockTranslatorAgent(options)
```
</TabItem>
</Tabs>
## Dynamic Language Setting
To set the language during the invocation:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { AgentSquad, BedrockTranslatorAgent } from 'agent-squad';
const translator = new BedrockTranslatorAgent({
name: 'DynamicTranslator',
description: 'Translator with dynamically set languages'
});
const orchestrator = new AgentSquad();
orchestrator.addAgent(translator);
async function translateWithDynamicLanguages(text: string, fromLang: string, toLang: string) {
translator.setSourceLanguage(fromLang);
translator.setTargetLanguage(toLang);
const response = await orchestrator.routeRequest(
text,
'user123',
'session456'
);
console.log(`Translated from ${fromLang} to ${toLang}:`, response);
}
// Usage
translateWithDynamicLanguages("Hello, world!", "English", "French");
translateWithDynamicLanguages("Bonjour le monde!", "French", "Spanish");
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
from agent_squad.orchestrator import AgentSquad
from agent_squad.agents import BedrockTranslatorAgent, BedrockTranslatorAgentOptions
translator = BedrockTranslatorAgent(BedrockTranslatorAgentOptions(
name='DynamicTranslator',
description='Translator with dynamically set languages'
))
orchestrator = AgentSquad()
orchestrator.add_agent(translator)
async def translate_with_dynamic_languages(text: str, from_lang: str, to_lang: str):
translator.set_source_language(from_lang)
translator.set_target_language(to_lang)
response = await orchestrator.route_request(
text,
'user123',
'session456'
)
print(f"Translated from {from_lang} to {to_lang}:", response)
# Usage
import asyncio
asyncio.run(translate_with_dynamic_languages("Hello, world!", "English", "French"))
asyncio.run(translate_with_dynamic_languages("Bonjour le monde!", "French", "Spanish"))
```
</TabItem>
</Tabs>
## Usage with ChainAgent
The `BedrockTranslatorAgent` can be effectively used within a `ChainAgent` for complex multilingual processing workflows. Here's an example that demonstrates translating user input and processing it:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { AgentSquad, ChainAgent, BedrockTranslatorAgent, BedrockLLMAgent } from 'agent-squad';
// Create translator agents
const translatorToEnglish = new BedrockTranslatorAgent({
name: 'TranslatorToEnglish',
description: 'Translates input to English',
targetLanguage: 'English'
});
// Create a processing agent (e.g., a BedrockLLMAgent)
const processor = new BedrockLLMAgent({
name: 'EnglishProcessor',
description: 'Processes text in English'
});
// Create a ChainAgent
const chainAgent = new ChainAgent({
name: 'TranslateProcessTranslate',
description: 'Translates, processes, and translates back',
agents: [translatorToEnglish, processor]
});
const orchestrator = new AgentSquad();
orchestrator.addAgent(chainAgent);
// Function to handle user input
async function handleMultilingualInput(input: string, sourceLanguage: string) {
translatorToEnglish.setSourceLanguage(sourceLanguage);
const response = await orchestrator.routeRequest(
input,
'user123',
'session456'
);
console.log('Response:', response);
}
// Usage
handleMultilingualInput("Hola, ¿cómo estás?", "Spanish");
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
from agent_squad.orchestrator import AgentSquad
from agent_squad.agents import ChainAgent, BedrockTranslatorAgent, BedrockLLMAgent
from agent_squad.agents import ChainAgentOptions, BedrockTranslatorAgentOptions, BedrockLLMAgentOptions
# Create translator agents
translator_to_english = BedrockTranslatorAgent(BedrockTranslatorAgentOptions(
name='TranslatorToEnglish',
description='Translates input to English',
target_language='English'
))
# Create a processing agent (e.g., a BedrockLLMAgent)
processor = BedrockLLMAgent(BedrockLLMAgentOptions(
name='EnglishProcessor',
description='Processes text in English'
))
# Create a ChainAgent
chain_agent = ChainAgent(ChainAgentOptions(
name='TranslateProcessTranslate',
description='Translates, processes, and translates back',
agents=[translator_to_english, processor]
))
orchestrator = AgentSquad()
orchestrator.add_agent(chain_agent)
# Function to handle user input
async def handle_multilingual_input(input_text: str, source_language: str):
translator_to_english.set_source_language(source_language)
response = await orchestrator.route_request(
input_text,
'user123',
'session456'
)
print('Response:', response)
# Usage
import asyncio
asyncio.run(handle_multilingual_input("Hola, ¿cómo estás?", "Spanish"))
```
</TabItem>
</Tabs>
In this example:
1. The first translator agent converts the input to English.
2. The processor agent (e.g., a `BedrockLLMAgent`) processes the English text.
This setup allows for seamless multilingual processing, where the core logic can be implemented in English while supporting input and output in various languages.
---
By leveraging the `BedrockTranslatorAgent`, you can create sophisticated multilingual applications and workflows, enabling seamless communication and processing across language barriers in your Agent Squad system.
================================================
FILE: docs/src/content/docs/agents/built-in/chain-agent.mdx
================================================
---
title: Chain Agent
description: Documentation for the Chain Agent in the Agent Squad System
---
The `ChainAgent` is an agent class in the Agent Squad System that allows for the sequential execution of multiple agents. It processes a request by passing the output of one agent as input to the next, creating a chain of agent interactions.
## Creating a ChainAgent
### Basic Example
### Python Package
If you haven't already installed the AWS-related dependencies, make sure to install them:
```bash
pip install "agent-squad[aws]"
```
Here's how to create a ChainAgent with only the required parameters:
import { Tabs, TabItem } from '@astrojs/starlight/components';
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { ChainAgent, ChainAgentOptions } from 'agent-squad';
import { BedrockLLMAgent } from 'agent-squad';
const agent1 = new BedrockLLMAgent({
name: 'Agent 1',
description: '..AGENT DESCRIPTION..'
});
const agent2 = new BedrockLLMAgent({
name: 'Agent 2',
description: '..AGENT DESCRIPTION..'
});
const chainAgent = new ChainAgent({
name: 'Chain Tech Agent',
description: 'Specializes in technology areas including software development, hardware, AI, cybersecurity, blockchain, cloud computing, emerging tech innovations, and pricing/costs related to technology products and services.',
agents: [agent1, agent2]
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
from agent_squad.agents import ChainAgent, ChainAgentOptions
from agent_squad.agents import BedrockLLMAgent, BedrockLLMAgentOptions
agent1 = BedrockLLMAgent(BedrockLLMAgentOptions(
name='Agent 1',
description='..AGENT DESCRIPTION..'
))
agent2 = BedrockLLMAgent(BedrockLLMAgentOptions(
name='Agent 2',
description='..AGENT DESCRIPTION..'
))
chain_agent = ChainAgent(ChainAgentOptions(
name='BasicChainAgent',
description='A simple chain of multiple agents',
agents=[agent1, agent2]
))
```
</TabItem>
</Tabs>
### Intermediate Example
This example shows how to create a ChainAgent with a custom default output:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { ChainAgent, ChainAgentOptions } from 'agent-squad';
import { BedrockLLMAgent } from 'agent-squad';
const agent1 = new BedrockLLMAgent({
name: 'Agent 1',
description: '..AGENT DESCRIPTION..'
});
const agent2 = new BedrockLLMAgent({
name: 'Agent 2',
description: '..AGENT DESCRIPTION..',
streaming: true
});
const chainAgent = new ChainAgent({
name: 'IntermediateChainAgent',
description: 'A chain of agents with custom default output',
agents: [agent1, agent2],
defaultOutput: 'The chain encountered an issue during processing.'
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
from agent_squad.agents import ChainAgent, ChainAgentOptions
from agent_squad.agents import BedrockLLMAgent, BedrockLLMAgentOptions
agent1 = BedrockLLMAgent(BedrockLLMAgentOptions(
name='Agent 1',
description='..AGENT DESCRIPTION..'
))
agent2 = BedrockLLMAgent(BedrockLLMAgentOptions(
name='Agent 2',
description='..AGENT DESCRIPTION..'
))
chain_agent = ChainAgent(ChainAgentOptions(
name='IntermediateChainAgent',
description='A chain of agents with custom default output',
agents=[agent1, agent2],
default_output='The chain encountered an issue during processing.'
))
```
</TabItem>
</Tabs>
### Advanced Example
For more complex use cases, you can create a ChainAgent with all available options:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { ChainAgent, ChainAgentOptions } from 'agent-squad';
import { BedrockLLMAgent } from 'agent-squad';
const agent1 = new BedrockLLMAgent({
name: 'Agent 1',
description: '..AGENT DESCRIPTION..'
});
const agent2 = new BedrockLLMAgent({
name: 'Agent 2',
description: '..AGENT DESCRIPTION..',
streaming: true
});
const options: ChainAgentOptions = {
name: 'AdvancedChainAgent',
description: 'A sophisticated chain of agents with all options',
agents: [agent1, agent2],
defaultOutput: 'The chain processing encountered an issue.',
saveChat: true
};
const chainAgent = new ChainAgent(options);
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
from agent_squad.agents import ChainAgent, ChainAgentOptions
from agent_squad.agents import BedrockLLMAgent, BedrockLLMAgentOptions
agent1 = BedrockLLMAgent(BedrockLLMAgentOptions(
name='Agent 1',
description='..AGENT DESCRIPTION..'
))
agent2 = BedrockLLMAgent(BedrockLLMAgentOptions(
name='Agent 2',
description='..AGENT DESCRIPTION..',
streaming=True
))
options = ChainAgentOptions(
name='AdvancedChainAgent',
description='A sophisticated chain of agents with all options',
agents=[agent1, agent2],
default_output='The chain processing encountered an issue.',
save_chat=True
)
chain_agent = ChainAgent(options)
```
</TabItem>
</Tabs>
## Integrating ChainAgent into the Agent Squad
To integrate the ChainAgent into your Agent Squad:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { AgentSquad } from "agent-squad";
const orchestrator = new AgentSquad();
orchestrator.addAgent(chainAgent);
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
from agent_squad.orchestrator import AgentSquad
orchestrator = AgentSquad()
orchestrator.add_agent(chain_agent)
```
</TabItem>
</Tabs>
## Streaming Responses
The ChainAgent supports streaming responses only for the last agent in the chain.
This design ensures efficient processing through the chain while still enabling streaming capabilities for the end result.
---
By leveraging the ChainAgent, you can create sophisticated, multi-step processing pipelines within your Agent Squad system, allowing for complex interactions and transformations of user inputs, with the added flexibility of streaming output from the final processing step.
================================================
FILE: docs/src/content/docs/agents/built-in/comprehend-filter-agent.mdx
================================================
---
title: Comprehend Filter Agent
description: Documentation for the Comprehend Filter Agent in the Agent Squad System
---
The `ComprehendFilterAgent` is an agent class in the Agent Squad System that uses [Amazon Comprehend](https://aws.amazon.com/comprehend/?nc1=h_ls) to analyze and filter content based on sentiment, Personally Identifiable Information (PII), and toxicity.
It can be used as a standalone agent within the Agent Squad or as part of a chain in the ChainAgent.
When used in a [ChainAgent](/agent-squad/agents/built-in/chain-agent) configuration, it's particularly effective as the first agent in the list. In this setup, it can check the user input against all configured filters, and if the content passes these checks, it will forward the original user input to the next agent in the chain. This allows for a robust content moderation system that can be seamlessly integrated into more complex processing pipelines, ensuring that only appropriate content is processed by subsequent agents.
## Key Features
- Content analysis using Amazon Comprehend
- Configurable checks for sentiment, PII, and toxicity
- Customizable thresholds for sentiment and toxicity
- Support for multiple languages
- Ability to add custom content checks
## Creating a Comprehend Filter Agent
### Python Package
If you haven't already installed the AWS-related dependencies, make sure to install them:
```bash
pip install "agent-squad[aws]"
```
### Basic Example
To create a new `ComprehendFilterAgent` with default settings:
import { Tabs, TabItem } from '@astrojs/starlight/components';
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { ComprehendFilterAgent, ComprehendFilterAgentOptions } from 'agent-squad';
const agent = new ComprehendFilterAgent({
name: 'ContentModerator',
description: 'Analyzes and filters content using Amazon Comprehend'
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
from agent_squad.agents import ComprehendFilterAgent, ComprehendFilterAgentOptions
agent = ComprehendFilterAgent(ComprehendFilterAgentOptions(
name='ContentModerator',
description='Analyzes and filters content using Amazon Comprehend'
))
```
</TabItem>
</Tabs>
### Advanced Example
For more complex use cases, you can create a `ComprehendFilterAgent` with custom settings:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { ComprehendFilterAgent, ComprehendFilterAgentOptions } from 'agent-squad';
const options: ComprehendFilterAgentOptions = {
name: 'AdvancedContentModerator',
description: 'Advanced content moderation with custom settings',
region: 'us-west-2',
enableSentimentCheck: true,
enablePiiCheck: true,
enableToxicityCheck: true,
sentimentThreshold: 0.8,
toxicityThreshold: 0.6,
allowPii: false,
languageCode: 'en'
};
const agent = new ComprehendFilterAgent(options);
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
from agent_squad.agents import ComprehendFilterAgent, ComprehendFilterAgentOptions
options = ComprehendFilterAgentOptions(
name='AdvancedContentModerator',
description='Advanced content moderation with custom settings',
region='us-west-2',
enable_sentiment_check=True,
enable_pii_check=True,
enable_toxicity_check=True,
sentiment_threshold=0.8,
toxicity_threshold=0.6,
allow_pii=False,
language_code='en'
)
agent = ComprehendFilterAgent(options)
```
</TabItem>
</Tabs>
## Integrating Comprehend Filter Agent
To integrate the `ComprehendFilterAgent` into your orchestrator:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { AgentSquad } from "agent-squad";
const orchestrator = new AgentSquad();
orchestrator.addAgent(agent);
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
from agent_squad.orchestrator import AgentSquad
orchestrator = AgentSquad()
orchestrator.add_agent(agent)
```
</TabItem>
</Tabs>
## Adding Custom Checks
This example demonstrates how to add a **Custom Check** to the `ComprehendFilterAgent`:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { ComprehendFilterAgent, ComprehendFilterAgentOptions } from 'agent-squad';
const filterAgent = new ComprehendFilterAgent({
name: 'AdvancedContentFilter',
description: 'Advanced content filter with custom checks'
});
// Add a custom check for specific keywords
filterAgent.addCustomCheck(async (text: string) => {
const keywords = ['banned', 'inappropriate', 'offensive'];
for (const keyword of keywords) {
if (text.toLowerCase().includes(keyword)) {
return `Banned keyword detected: ${keyword}`;
}
}
return null;
});
const orchestrator = new AgentSquad();
orchestrator.addAgent(filterAgent);
const response = await orchestrator.routeRequest(
"This message contains a banned word.",
"user789",
"session101"
);
if (response) {
console.log("Content passed all checks");
} else {
console.log("Content was flagged by the filter");
}
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
from agent_squad.orchestrator import AgentSquad
from agent_squad.agents import ComprehendFilterAgent, ComprehendFilterAgentOptions
filter_agent = ComprehendFilterAgent(ComprehendFilterAgentOptions(
name='AdvancedContentFilter',
description='Advanced content filter with custom checks'
))
# Add a custom check for specific keywords
async def custom_keyword_check(text: str) -> Optional[str]:
keywords = ['banned', 'inappropriate', 'offensive']
for keyword in keywords:
if keyword in text.lower():
return f"Banned keyword detected: {keyword}"
return None
filter_agent.add_custom_check(custom_keyword_check)
orchestrator = AgentSquad()
orchestrator.add_agent(filter_agent)
response = await orchestrator.route_request(
"This message contains a banned word.",
"user789",
"session101"
)
if response:
print("Content passed all checks")
else:
print("Content was flagged by the filter")
```
</TabItem>
</Tabs>
## Dynamic Language Detection and Handling
The `ComprehendFilterAgent` offers flexible language handling capabilities. You can specify the language either at initialization or dynamically during invocation. Additionally, it supports automatic language detection, allowing it to adapt to content in various languages without manual specification.
This example demonstrates dynamic language detection and handling:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { AgentSquad, ComprehendFilterAgent } from 'agent-squad';
import { ComprehendClient, DetectDominantLanguageCommand } from "@aws-sdk/client-comprehend";
const filterAgent = new ComprehendFilterAgent({
name: 'MultilingualContentFilter',
description: 'Filters content in multiple languages'
});
const orchestrator = new AgentSquad();
orchestrator.addAgent(filterAgent);
async function detectLanguage(text: string): Promise<string> {
const comprehendClient = new ComprehendClient({ region: "us-east-1" });
const command = new DetectDominantLanguageCommand({ Text: text });
const response = await comprehendClient.send(command);
return response.Languages[0].LanguageCode;
}
let detectedLanguage: string | null = null;
async function processUserInput(userInput: string, userId: string, sessionId: string): Promise<void> {
if (!detectedLanguage) {
detectedLanguage = await detectLanguage(userInput);
console.log(`Detected language: ${detectedLanguage}`);
}
try {
const response = await orchestrator.routeRequest(
userInput,
userId,
sessionId,
{ languageCode: detectedLanguage }
);
console.log("Processed response:", response);
} catch (error) {
console.error("Error:", error);
}
}
// Example usage
processUserInput("Hello, world!", "user123", "session456");
// Subsequent calls will use the same detected language
processUserInput("How are you?", "user123", "session456");
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
from agent_squad.orchestrator import AgentSquad
from agent_squad.agents import ComprehendFilterAgent, ComprehendFilterAgentOptions
import boto3
import asyncio
filter_agent = ComprehendFilterAgent(ComprehendFilterAgentOptions(
name='MultilingualContentFilter',
description='Filters content in multiple languages'
))
orchestrator = AgentSquad()
orchestrator.add_agent(filter_agent)
def detect_language(text: str) -> str:
comprehend = boto3.client('comprehend', region_name='us-east-1')
response = comprehend.detect_dominant_language(Text=text)
return response['Languages'][0]['LanguageCode']
detected_language = None
async def process_user_input(user_input: str, user_id: str, session_id: str):
global detected_language
if not detected_language:
detected_language = detect_language(user_input)
print(f"Detected language: {detected_language}")
try:
response = await orchestrator.route_request(
user_input,
user_id,
session_id,
additional_params={"language_code": detected_language}
)
print("Processed response:", response)
except Exception as error:
print("Error:", error)
# Example usage
asyncio.run(process_user_input("Hello, world!", "user123", "session456"))
# Subsequent calls will use the same detected language
asyncio.run(process_user_input("How are you?", "user123", "session456"))
```
</TabItem>
</Tabs>
## Usage with ChainAgent
This example demonstrates how to use the `ComprehendFilterAgent` as part of a `ChainAgent` configuration:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { AgentSquad, ChainAgent, ComprehendFilterAgent, BedrockLLMAgent } from 'agent-squad';
// Create a ComprehendFilterAgent
const filterAgent = new ComprehendFilterAgent({
name: 'ContentFilter',
description: 'Filters inappropriate content',
enableSentimentCheck: true,
enablePiiCheck: true,
enableToxicityCheck: true,
sentimentThreshold: 0.7,
toxicityThreshold: 0.6
});
// Create a BedrockLLMAgent (or any other agent you want to use after filtering)
const llmAgent = new BedrockLLMAgent({
name: 'LLMProcessor',
description: 'Processes filtered content using a language model',
streaming: true
});
// Create a ChainAgent that combines the filter and LLM agents
const chainAgent = new ChainAgent({
name: 'FilteredLLMChain',
description: 'Chain that filters content before processing with LLM',
agents: [filterAgent, llmAgent]
});
// Add the chain agent to the orchestrator
const orchestrator = new AgentSquad();
orchestrator.addAgent(chainAgent);
// Use the chain
const response = await orchestrator.routeRequest(
"Process this message after ensuring it's appropriate.",
"user123",
"session456"
);
if (response) {
console.log("Message processed successfully:", response);
} else {
console.log("Message was filtered out due to inappropriate content");
}
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
from agent_squad.orchestrator import AgentSquad
from agent_squad.agents import ChainAgent, ComprehendFilterAgent, BedrockLLMAgent
from agent_squad.agents import ChainAgentOptions, ComprehendFilterAgentOptions, BedrockLLMAgentOptions
# Create a ComprehendFilterAgent
filter_agent = ComprehendFilterAgent(ComprehendFilterAgentOptions(
name='ContentFilter',
description='Filters inappropriate content',
enable_sentiment_check=True,
enable_pii_check=True,
enable_toxicity_check=True,
sentiment_threshold=0.7,
toxicity_threshold=0.6
))
# Create a BedrockLLMAgent (or any other agent you want to use after filtering)
llm_agent = BedrockLLMAgent(BedrockLLMAgentOptions(
name='LLMProcessor',
description='Processes filtered content using a language model',
streaming=True
))
# Create a ChainAgent that combines the filter and LLM agents
chain_agent = ChainAgent(ChainAgentOptions(
name='FilteredLLMChain',
description='Chain that filters content before processing with LLM',
agents=[filter_agent, llm_agent]
))
# Add the chain agent to the orchestrator
orchestrator = AgentSquad()
orchestrator.add_agent(chain_agent)
# Use the chain
response = await orchestrator.route_request(
"Process this message after ensuring it's appropriate.",
"user123",
"session456"
)
if response:
print("Message processed successfully:", response)
else:
print("Message was filtered out due to inappropriate content")
```
</TabItem>
</Tabs>
## Configuration Options
The `ComprehendFilterAgent` supports the following configuration options:
- `enableSentimentCheck`: Enable sentiment analysis (default: true)
- `enablePiiCheck`: Enable PII detection (default: true)
- `enableToxicityCheck`: Enable toxicity detection (default: true)
- `sentimentThreshold`: Threshold for negative sentiment (default: 0.7)
- `toxicityThreshold`: Threshold for toxic content (default: 0.7)
- `allowPii`: Allow PII in content (default: false)
- `languageCode`: ISO 639-1 language code for analysis (default: 'en')
## Supported Languages
The `ComprehendFilterAgent` supports the following languages:
'en' (English), 'es' (Spanish), 'fr' (French), 'de' (German), 'it' (Italian), 'pt' (Portuguese), 'ar' (Arabic), 'hi' (Hindi), 'ja' (Japanese), 'ko' (Korean), 'zh' (Chinese Simplified), 'zh-TW' (Chinese Traditional)
---
By leveraging the `ComprehendFilterAgent`, you can implement robust content moderation in your Agent Squad system, ensuring safe and appropriate interactions while leveraging the power of Amazon Comprehend for advanced content analysis.
================================================
FILE: docs/src/content/docs/agents/built-in/lambda-agent.mdx
================================================
---
title: LambdaAgent
description: Documentation for the LambdaAgent in the Agent Squad System
---
The `LambdaAgent` is a versatile agent class in the Agent Squad System that allows integration with existing AWS Lambda functions. This agent will invoke your existing Lambda function written in any language (e.g., Python, Node.js, Java), providing a seamless way to utilize your existing serverless logic within the orchestrator.
## Key Features
- Integration with any AWS Lambda function runtime
- Custom payload encoder/decoder methods to match your payload format
- Support for cross-region Lambda invocation
- Default payload encoding/decoding for quick setup
## Creating a LambdaAgent
### Python Package
If you haven't already installed the AWS-related dependencies, make sure to install them:
```bash
pip install "agent-squad[aws]"
```
import { Tabs, TabItem } from '@astrojs/starlight/components';
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { LambdaAgent } from 'agent-squad';
const myCustomInputPayloadEncoder = (input, chatHistory, userId, sessionId, additionalParams) => {
return JSON.stringify({
userQuestion: input,
myCustomField: "Hello world!",
history: chatHistory,
user: userId,
session: sessionId,
...additionalParams
});
};
const myCustomOutputPayloadDecoder = (input) => {
const decodedResponse = JSON.parse(new TextDecoder("utf-8").decode(input.Payload)).body;
return {
role: "assistant",
content: [{ text: `Response: ${decodedResponse}` }]
};
};
const options: LambdaAgentOptions = {
name: 'My Advanced Lambda Agent',
description: 'A versatile agent that calls a custom Lambda function',
functionName: 'my-advanced-lambda-function',
functionRegion: 'us-west-2',
inputPayloadEncoder: myCustomInputPayloadEncoder,
outputPayloadDecoder: myCustomOutputPayloadDecoder
};
const agent = new LambdaAgent(options);
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
import json
from typing import List, Dict, Optional
from agent_squad.agents import LambdaAgent, LambdaAgentOptions
from agent_squad.types import ConversationMessage, ParticipantRole
def my_custom_input_payload_encoder(input_text: str,
chat_history: List[ConversationMessage],
user_id: str,
session_id: str,
additional_params: Optional[Dict[str, str]] = None) -> str:
return json.dumps({
"userQuestion": input_text,
"myCustomField": "Hello world!",
"history": [message.__dict__ for message in chat_history],
"user": user_id,
"session": session_id,
**(additional_params or {})
})
def my_custom_output_payload_decoder(response: Dict[str, Any]) -> ConversationMessage:
decoded_response = json.loads(response['Payload'].read().decode('utf-8'))['body']
return ConversationMessage(
role=ParticipantRole.ASSISTANT.value,
content=[{"text": f"Response: {decoded_response}"}]
)
options = LambdaAgentOptions(
name='My Advanced Lambda Agent',
description='A versatile agent that calls a custom Lambda function',
function_name='my-advanced-lambda-function',
function_region='us-west-2',
input_payload_encoder=my_custom_input_payload_encoder,
output_payload_decoder=my_custom_output_payload_decoder
)
agent = LambdaAgent(options)
```
</TabItem>
</Tabs>
### Parameter Explanations
- `name`: (Required) Identifies the agent within your system.
- `description`: (Required) Describes the agent's purpose or capabilities.
- `function_name`: (Required) The name or ARN of the Lambda function to invoke.
- `function_region`: (Required) The AWS region where the Lambda function is deployed.
- `input_payload_encoder`: (Optional) A custom function to encode the input payload.
- `output_payload_decoder`: (Optional) A custom function to decode the Lambda function's response.
## Adding the Agent to the Orchestrator
To integrate the LambdaAgent into your Agent Squad System, follow these steps:
1. First, ensure you have created an instance of the orchestrator:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { AgentSquad } from "agent-squad";
const orchestrator = new AgentSquad();
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
from agent_squad.orchestrator import AgentSquad
orchestrator = AgentSquad()
```
</TabItem>
</Tabs>
2. Then, add the LambdaAgent to the orchestrator:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
orchestrator.addAgent(agent);
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
orchestrator.add_agent(agent)
```
</TabItem>
</Tabs>
3. Now you can use the orchestrator to route requests to the appropriate agent, including your Lambda function:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const response = await orchestrator.routeRequest(
"I need help with my order",
"user123",
"session456"
);
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
response = await orchestrator.route_request(
"I need help with my order",
"user123",
"session456"
)
```
</TabItem>
</Tabs>
If you don't provide custom encoder/decoder functions, the LambdaAgent uses default methods:
Default Input Payload
```json
{
"query": "inputText",
"chatHistory": [...],
"additionalParams": {...},
"userId": "userId",
"sessionId": "sessionId"
}
```
Expected Default Output Payload
```json
{
"body": "{\"response\":\"this is the response\"}"
}
```
---
By leveraging the `LambdaAgent`, you can easily incorporate ***existing AWS Lambda functions*** into your Agent Squad System, combining serverless compute with your custom orchestration logic.
================================================
FILE: docs/src/content/docs/agents/built-in/lex-bot-agent.mdx
================================================
---
title: LexBotAgent
description: Documentation for the LexBotAgent in the Agent Squad System
---
The `LexBotAgent` is a specialized agent class in the Agent Squad System that integrates [Amazon Lex bots](https://aws.amazon.com/lex/).
## Key Features
- Seamless integration with Amazon Lex V2 bots
- Support for multiple locales
- Easy configuration with bot ID and alias
## Creating a LexBotAgent
### Python Package
If you haven't already installed the AWS-related dependencies, make sure to install them:
```bash
pip install "agent-squad[aws]"
```
To create a new `LexBotAgent` with the required parameters, use the following code:
import { Tabs, TabItem } from '@astrojs/starlight/components';
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { LexBotAgent } from 'agent-squad';
const agent = new LexBotAgent({
name: 'My Basic Lex Bot Agent',
description: 'An agent specialized in flight booking',
botId: 'your-bot-id',
botAliasId: 'your-bot-alias-id',
localeId: 'en_US',
region: 'us-east-1'
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
from agent_squad.agents import LexBotAgent, LexBotAgentOptions
agent = LexBotAgent(LexBotAgentOptions(
name='My Basic Lex Bot Agent',
description='An agent specialized in flight booking',
bot_id='your-bot-id',
bot_alias_id='your-bot-alias-id',
locale_id='en_US',
region='us-east-1'
))
```
</TabItem>
</Tabs>
### Parameter Explanations
- `name`: (Required) Identifies the agent within your system.
- `description`: (Required) Describes the agent's purpose or capabilities.
- `bot_id`: (Required) The ID of the Amazon Lex bot you want to use.
- `bot_alias_id`: (Required) The alias ID of the Amazon Lex bot.
- `locale_id`: (Required) The locale ID for the bot (e.g., 'en_US').
- `region`: (Optional) The AWS region where the Lex bot is deployed. If not provided, it will use the `AWS_REGION` environment variable or default to 'us-east-1'.
## Adding the Agent to the Orchestrator
To integrate the LexBotAgent into your Agent Squad, follow these steps:
1. First, ensure you have created an instance of the orchestrator:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { AgentSquad } from 'agent-squad';
const orchestrator = new AgentSquad();
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
from agent_squad.orchestrator import AgentSquad
orchestrator = AgentSquad()
```
</TabItem>
</Tabs>
2. Then, add the LexBotAgent to the orchestrator:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
orchestrator.addAgent(agent);
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
orchestrator.add_agent(agent)
```
</TabItem>
</Tabs>
3. Now you can use the orchestrator to route requests to the appropriate agent, including your Lex bot:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const response = await orchestrator.routeRequest(
"I would like to book a flight",
"user123",
"session456"
);
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
response = await orchestrator.route_request(
"I would like to book a flight",
"user123",
"session456"
)
```
</TabItem>
</Tabs>
---
By leveraging the `LexBotAgent`, you can easily integrate **pre-built Amazon Lex Bots** into your Agent Squad.
================================================
FILE: docs/src/content/docs/agents/built-in/openai-agent.mdx
================================================
---
title: Open AI Agent
description: Documentation for the OpenAI Agent
---
The `OpenAIAgent` is a powerful agent class in the Agent Squad framework that integrates with OpenAI's Chat Completion API. This agent allows you to leverage OpenAI's language models for various natural language processing tasks.
## Key Features
- Integration with OpenAI's Chat Completion API
- Support for multiple OpenAI models (e.g., GPT-4, GPT-3.5)
- Streaming and non-streaming response options
- Customizable inference configuration
- Conversation history handling for context-aware responses
- Customizable system prompts with variable support
- Support for retrievers to enhance responses with additional context
- Flexible initialization with API key or custom client
## Configuration Options
The `OpenAIAgentOptions` extends the base `AgentOptions` with the following fields:
### Required Fields
- `name`: Name of the agent
- `description`: Description of the agent's capabilities
- Authentication (one of the following is required):
- `apiKey`: Your OpenAI API key
- `client`: Custom OpenAI client instance
### Optional Fields
- `model`: OpenAI model identifier (e.g., 'gpt-4', 'gpt-3.5-turbo'). Defaults to `OPENAI_MODEL_ID_GPT_O_MINI`
- `streaming`: Enable streaming responses. Defaults to `false`
- `retriever`: Custom retriever instance for enhancing responses with additional context
- `inferenceConfig`: Configuration for model inference:
- `maxTokens`: Maximum tokens to generate (default: 1000)
- `temperature`: Controls randomness (0-1)
- `topP`: Controls diversity via nucleus sampling
- `stopSequences`: Sequences that stop generation
- `customSystemPrompt`: System prompt configuration:
- `template`: Template string with optional variable placeholders
- `variables`: Key-value pairs for template variables
## Creating an OpenAIAgent
### Python Package
If you haven't already installed the OpenAI-related dependencies, make sure to install them:
```bash
pip install "agent-squad[openai]"
```
Here are various examples showing different ways to create and configure an OpenAIAgent:
### Basic Examples
**1. Minimal Configuration**
import { Tabs, TabItem } from '@astrojs/starlight/components';
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const agent = new OpenAIAgent({
name: 'OpenAI Assistant',
description: 'A versatile AI assistant',
apiKey: 'your-openai-api-key'
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
agent = OpenAIAgent(OpenAIAgentOptions(
name='OpenAI Assistant',
description='A versatile AI assistant',
api_key='your-openai-api-key'
))
```
</TabItem>
</Tabs>
<hr/>
**2. Using Custom Client**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import OpenAI from 'openai';
const customClient = new OpenAI({ apiKey: 'your-openai-api-key' });
const agent = new OpenAIAgent({
name: 'OpenAI Assistant',
description: 'A versatile AI assistant',
client: customClient
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
from openai import OpenAI
custom_client = OpenAI(api_key='your-openai-api-key')
agent = OpenAIAgent(OpenAIAgentOptions(
name='OpenAI Assistant',
description='A versatile AI assistant',
client=custom_client
))
```
</TabItem>
</Tabs>
<hr/>
**3. Custom Model and Streaming**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const agent = new OpenAIAgent({
name: 'OpenAI Assistant',
description: 'A streaming-enabled assistant',
apiKey: 'your-openai-api-key',
model: 'gpt-4',
streaming: true
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
agent = OpenAIAgent(OpenAIAgentOptions(
name='OpenAI Assistant',
description='A streaming-enabled assistant',
api_key='your-openai-api-key',
model='gpt-4',
streaming=True
))
```
</TabItem>
</Tabs>
<hr/>
**4. With Inference Configuration**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const agent = new OpenAIAgent({
name: 'OpenAI Assistant',
description: 'An assistant with custom inference settings',
apiKey: 'your-openai-api-key',
inferenceConfig: {
maxTokens: 500,
temperature: 0.7,
topP: 0.9,
stopSequences: ['Human:', 'AI:']
}
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
agent = OpenAIAgent(OpenAIAgentOptions(
name='OpenAI Assistant',
description='An assistant with custom inference settings',
api_key='your-openai-api-key',
inference_config={
'maxTokens': 500,
'temperature': 0.7,
'topP': 0.9,
'stopSequences': ['Human:', 'AI:']
}
))
```
</TabItem>
</Tabs>
<hr/>
**5. With Simple System Prompt**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const agent = new OpenAIAgent({
name: 'OpenAI Assistant',
description: 'An assistant with custom prompt',
apiKey: 'your-openai-api-key',
customSystemPrompt: {
template: 'You are a helpful AI assistant focused on technical support.'
}
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
agent = OpenAIAgent(OpenAIAgentOptions(
name='OpenAI Assistant',
description='An assistant with custom prompt',
api_key='your-openai-api-key',
custom_system_prompt={
'template': 'You are a helpful AI assistant focused on technical support.'
}
))
```
</TabItem>
</Tabs>
<hr/>
**6. With System Prompt Variables**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const agent = new OpenAIAgent({
name: 'OpenAI Assistant',
description: 'An assistant with variable prompt',
apiKey: 'your-openai-api-key',
customSystemPrompt: {
template: 'You are an AI assistant specialized in {{DOMAIN}}. Always use a {{TONE}} tone.',
variables: {
DOMAIN: 'customer support',
TONE: 'friendly and helpful'
}
}
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
agent = OpenAIAgent(OpenAIAgentOptions(
name='OpenAI Assistant',
description='An assistant with variable prompt',
api_key='your-openai-api-key',
custom_system_prompt={
'template': 'You are an AI assistant specialized in {{DOMAIN}}. Always use a {{TONE}} tone.',
'variables': {
'DOMAIN': 'customer support',
'TONE': 'friendly and helpful'
}
}
))
```
</TabItem>
</Tabs>
<hr/>
**7. With Custom Retriever**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const retriever = new CustomRetriever({
// Retriever configuration
});
const agent = new OpenAIAgent({
name: 'OpenAI Assistant',
description: 'An assistant with retriever',
apiKey: 'your-openai-api-key',
retriever: retriever
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
retriever = CustomRetriever(
# Retriever configuration
)
agent = OpenAIAgent(OpenAIAgentOptions(
name='OpenAI Assistant',
description='An assistant with retriever',
api_key='your-openai-api-key',
retriever=retriever
))
```
</TabItem>
</Tabs>
<hr/>
**8. Combining Multiple Options**
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const agent = new OpenAIAgent({
name: 'OpenAI Assistant',
description: 'An assistant with multiple options',
apiKey: 'your-openai-api-key',
model: 'gpt-4',
streaming: true,
inferenceConfig: {
maxTokens: 500,
temperature: 0.7
},
customSystemPrompt: {
template: 'You are an AI assistant specialized in {{DOMAIN}}.',
variables: {
DOMAIN: 'technical support'
}
}
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
agent = OpenAIAgent(OpenAIAgentOptions(
name='OpenAI Assistant',
description='An assistant with multiple options',
api_key='your-openai-api-key',
model='gpt-4',
streaming=True,
inference_config={
'maxTokens': 500,
'temperature': 0.7
},
custom_system_prompt={
'template': 'You are an AI assistant specialized in {{DOMAIN}}.',
'variables': {
'DOMAIN': 'technical support'
}
}
))
```
</TabItem>
</Tabs>
<hr/>
**9. Complete Example with All Options**
Here's a comprehensive example showing all available configuration options:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import { OpenAIAgent } from 'agent-squad';
const agent = new OpenAIAgent({
// Required fields
name: 'Advanced OpenAI Assistant',
description: 'A fully configured AI assistant powered by OpenAI models',
apiKey: 'your-openai-api-key',
// Optional fields
model: 'gpt-4', // Choose OpenAI model
streaming: true, // Enable streaming responses
retriever: customRetriever, // Custom retriever for additional context
// Inference configuration
inferenceConfig: {
maxTokens: 500, // Maximum tokens to generate
temperature: 0.7, // Control randomness (0-1)
topP: 0.9, // Control diversity via nucleus sampling
stopSequences: ['Human:', 'AI:'] // Sequences that stop generation
},
// Custom system prompt with variables
customSystemPrompt: {
template: `You are an AI assistant specialized in {{DOMAIN}}.
Your core competencies:
{{SKILLS}}
Communication style:
- Maintain a {{TONE}} tone
- Focus on {{FOCUS}}
- Prioritize {{PRIORITY}}`,
variables: {
DOMAIN: 'scientific research',
SKILLS: [
'- Advanced data analysis',
'- Statistical methodology',
'- Research design',
'- Technical writing'
],
TONE: 'professional and academic',
FOCUS: 'accuracy and clarity',
PRIORITY: 'evidence-based insights'
}
}
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
from agent_squad import OpenAIAgent, OpenAIAgentOptions
agent = OpenAIAgent(OpenAIAgentOptions(
# Required fields
name='Advanced OpenAI Assistant',
description='A fully configured AI assistant powered by OpenAI models',
api_key='your-openai-api-key',
# Optional fields
model='gpt-4', # Choose OpenAI model
streaming=True, # Enable streaming responses
retriever=custom_retriever, # Custom retriever for additional context
# Inference configuration
inference_config={
'maxTokens': 500, # Maximum tokens to generate
'temperature': 0.7, # Control randomness (0-1)
'topP': 0.9, # Control diversity via nucleus sampling
'stopSequences': ['Human:', 'AI:'] # Sequences that stop generation
},
# Custom system prompt with variables
custom_system_prompt={
'template': """You are an AI assistant specialized in {{DOMAIN}}.
Your core competencies:
{{SKILLS}}
Communication style:
- Maintain a {{TONE}} tone
- Focus on {{FOCUS}}
- Prioritize {{PRIORITY}}""",
'variables': {
'DOMAIN': 'scientific research',
'SKILLS': [
'- Advanced data analysis',
'- Statistical methodology',
'- Research design',
'- Technical writing'
],
'TONE': 'professional and academic',
'FOCUS': 'accuracy and clarity',
'PRIORITY': 'evidence-based insights'
}
}
))
```
</TabItem>
</Tabs>
## Using the OpenAIAgent
There are two ways to use the OpenAIAgent: directly or through the Agent Squad.
### Direct Usage
Call the agent directly when you want to use a single agent without orchestrator routing:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const classifierResult = {
selectedAgent: agent,
confidence: 1.0
};
const response = await orchestrator.agentProcessRequest(
"What is the capital of France?",
"user123",
"session456",
classifierResult
);
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
classifier_result = ClassifierResult(selected_agent=agent, confidence=1.0)
response = await orchestrator.agent_process_request(
"What is the capital of France?",
"user123",
"session456",
classifier_result
)
```
</TabItem>
</Tabs>
### Using with the Orchestrator
Add the agent to Agent Squad for use in a multi-agent system:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const orchestrator = new AgentSquad();
orchestrator.addAgent(agent);
const response = await orchestrator.routeRequest(
"What is the capital of France?",
"user123",
"session456"
);
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
orchestrator = AgentSquad()
orchestrator.add_agent(agent)
response = await orchestrator.route_request(
"What is the capital of France?",
"user123",
"session456"
)
```
</TabItem>
</Tabs>
================================================
FILE: docs/src/content/docs/agents/built-in/supervisor-agent.mdx
================================================
---
title: Supervisor Agent
description: Documentation for the SupervisorAgent in the Agent Squad System
---
import { Tabs, TabItem } from '@astrojs/starlight/components';
The `SupervisorAgent` is an advanced orchestration component that enables sophisticated multi-agent coordination within the Agent Squad framework.
It implements a unique **"agent-as-tools"** architecture where team members are exposed to a supervisor agent as invocable tools, enabling parallel processing and contextual communication.
The diagram below illustrates the **SupervisorAgent** architecture, featuring a Lead Agent that coordinates with a team of specialized agents (A, B, and C). Two memory components—User-Supervisor Memory and Supervisor-Team Memory—support the interactions, enabling efficient information flow and conversation history management throughout the system.

## Usage Patterns
The SupervisorAgent can be used in two primary ways:
### 1. Direct Usage
You can use the SupervisorAgent directly, bypassing the classifier, when you want dedicated team coordination for specific tasks:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
// Create and configure SupervisorAgent
const supervisorAgent = new SupervisorAgent({
name: "SupervisorAgent",
description: "You are a supervisor agent that manages the team of agents for travel purposes",
leadAgent: new BedrockLLMAgent({
name: "Support Team Lead",
description: "Coordinates support inquiries"
}),
team: [
new LexBotAgent({
name: "Booking Agent",
description: "Handles travel bookings",
botId: "travel-bot-id",
botAliasId: "alias-id",
localeId: "en_US"
}),
new AmazonBedrockAgent({
name: "Payment Support",
description: "Handles payment issues",
agentId: "payment-agent-id",
agentAliasId: "alias-id"
})
]
});
// Use directly
const response = await supervisorAgent.processRequest(
"I need to modify my flight and check my refund status",
"user123",
"session456"
);
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
# Create and configure SupervisorAgent
supervisor_agent = SupervisorAgent(SupervisorAgentOptions(
name: "SupervisorAgent",
description: "You are a supervisor agent that manages the team of agents for travel purposes",
lead_agent=BedrockLLMAgent(BedrockLLMAgentOptions(
name="Support Team Lead",
description="Coordinates support inquiries"
)),
team=[
LexBotAgent(LexBotAgentOptions(
name="Booking Agent",
description="Handles travel bookings",
bot_id="travel-bot-id",
bot_alias_id="alias-id",
locale_id="en_US"
)),
BedrockAgent(BedrockAgentOptions(
name="Payment Support",
description="Handles payment issues",
agent_id="payment-agent-id",
agent_alias_id="alias-id"
))
]
))
# Use directly
response = await supervisor_agent.process_request(
"I need to modify my flight and check my refund status",
"user123",
"session456"
)
```
</TabItem>
</Tabs>
Here's a diagram illustrating the code implementation above, showing how the BedrockLLMAgent (Lead Agent) processes the user's flight modification request by coordinating with LexBotAgent and Amazon BedrockAgent, supported by dual memory systems for maintaining conversation context.

### 2. As Part of Classifier-Based Architecture
The SupervisorAgent can also be integrated into a larger system using the classifier, enabling complex hierarchical architectures:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const orchestrator = new AgentSquad();
// Add individual agents
orchestrator.addAgent(new BedrockLLMAgent({
name: "General Assistant",
description: "Handles general inquiries"
}));
// Add a SupervisorAgent for complex support tasks
orchestrator.addAgent(new SupervisorAgent({
name: "SupervisorAgent",
description: "You are a supervisor agent that manages the team of agents for product development purposes",
leadAgent: new BedrockLLMAgent({
name: "Support Team",
description: "Coordinates support inquiries requiring multiple specialists"
}),
team: [techAgent, billingAgent, lexBookingBot]
}));
// Add another SupervisorAgent for product development
orchestrator.addAgent(new SupervisorAgent({
leadAgent: new AnthropicAgent({
name: "Product Team",
description: "Coordinates product development and feature requests"
}),
team: [designAgent, engineeringAgent, productManagerAgent]
}));
// Process through classifier
const response = await orchestrator.routeRequest(
userInput,
userId,
sessionId
);
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
orchestrator = AgentSquad()
# Add individual agents
orchestrator.add_agent(BedrockLLMAgent(BedrockLLMAgentOptions(
name="General Assistant",
description="Handles general inquiries"
)))
# Add a SupervisorAgent for complex support tasks
orchestrator.add_agent(SupervisorAgent(SupervisorAgentOptions(
name: "SupervisorAgent",
description: "You are a supervisor agent that manages the team of agents for product development purposes",
lead_agent=BedrockLLMAgent(BedrockLLMAgentOptions(
name="Support Team",
description="Coordinates support inquiries requiring multiple specialists"
)),
team=[tech_agent, billing_agent, lex_booking_bot]
)))
# Add another SupervisorAgent for product development
orchestrator.add_agent(SupervisorAgent(SupervisorAgentOptions(
lead_agent=AnthropicAgent(AnthropicAgentOptions(
name="Product Team",
description="Coordinates product development and feature requests"
)),
team=[design_agent, engineering_agent, product_manager_agent]
)))
# Process through classifier
response = await orchestrator.route_request(
user_input,
user_id,
session_id
)
```
</TabItem>
</Tabs>
Here's a diagram illustrating the code implementation above, showing a Classifier that routes user requests to appropriate teams. Three specialized units are shown: a General Assistant, a Support Team (handling tech, billing, and booking), and a Product Team (comprising design, engineering, and product management agents). Each team uses different agent types (BedrockLLMAgent, LexBotAgent, AnthropicAgent, AmazonBedrockAgent) based on their specific functions.

<hr/>
This flexibility allows you to:
- Use SupervisorAgent directly for dedicated team coordination
- Integrate it into classifier-based systems for dynamic routing
- Create hierarchical structures with multiple specialized teams
- Mix different types of agents (LexBot, Bedrock, Anthropic, etc.) in teams
- Scale and adapt the architecture as needs evolve
## Core Components
### 1. Supervisor (Lead Agent)
- Must be either a [BedrockLLMAgent](/agent-squad/agents/built-in/bedrock-llm-agent) or [AnthropicAgent](/agent-squad/agents/built-in/anthropic-agent)
- Acts as the central coordinator
- Communicates with team members through a tool interface
- Maintains conversation context with both user and team members
### 2. Team Members
- Collection of agents - each agent is wrapped as a tool for the supervisor
- Can be any agent type supported by the framework
- Operate independently and in parallel when possible
## Memory Architecture
The SupervisorAgent implements a sophisticated three-tier memory system to maintain context across conversations:
### 1. User-Supervisor Memory
This is like the main conversation between a customer and the team leader:
```text
User: I'm having trouble with my billing and the mobile app isn't working
Assistant: I understand you're having two issues. Let me help you with both your billing and app problems.
User: Yes, the app crashes when I try to view my bill
Assistant: I'll look into both issues. Let me check with our technical and billing teams.
```
### 2. Supervisor-Team Memory
Each team member maintains a private conversation with the supervisor:
```text
# Tech Support Conversation
Supervisor: User is experiencing app crashes when viewing bills. Can you investigate?
Tech Support: Based on the symptoms, this might be a cache issue. I'll provide steps to clear it.
# Billing Team Conversation
Supervisor: Please check the user's billing status
Billing Team: Account is active, last payment received Jan 15, next due Feb 15
```
### 3. Combined Memory
The supervisor keeps track of all important information in an organized way:
```text
<agents_memory>
User: I'm having trouble with the mobile app, what should I do?
Assistant: [Tech Support] The app crash is likely due to corrupted cache. Please ask the user to clear the app cache.
User: What is the status of my bills?
Assistant: [Billing Team] Account status is good. Last payment: Jan 15, Next due: Feb 15
</agents_memory>
```
### Memory Processing Flow
Here's a complete interaction showing how memory and communication work together:
1. **Initial Request**
```text
User: I'm having trouble with my bill and the mobile app
```
2. **Parallel Processing**
```text
# Supervisor communicates simultaneously with both teams
Supervisor → Tech Support: What could cause app issues when viewing bills?
Supervisor → Billing: Please verify account status
```
3. **Team Responses**
```text
Tech Support → Supervisor: Likely a cache issue. Common after recent updates.
Billing → Supervisor: Account in good standing, no payment issues.
```
4. **Unified Response**
```text
Supervisor → User: I've checked both issues. Your billing account is in good standing. For the app problem, it appears to be a cache issue. Would you like me to guide you through clearing your app's cache?
```
## Configuration
### Configuration Options
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
interface SupervisorAgentOptions extends AgentOptions {
leadAgent: BedrockLLMAgent | AnthropicAgent; // The agent that leads the team coordination
team: Agent[]; // Team of agents to coordinate
storage?: ChatStorage; // Memory storage implementation
trace?: boolean; // Enable detailed logging
extraTools?: AgentTools | AgentTool[]; // Additional tools for supervisor
}
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
@dataclass
class SupervisorAgentOptions(AgentOptions):
lead_agent: Agent # The agent that leads the team coordination
team: list[Agent] # Team of agents that can help in resolving tasks
storage: Optional[ChatStorage] # Memory storage for the team
trace: Optional[bool] # Enable tracing/logging
extra_tools: Optional[Union[AgentTools, list[AgentTool]]] # Additional tools for supervisor
```
</TabItem>
</Tabs>
### Required Parameters
- `leadAgent`/`lead_agent`: Must be either a BedrockLLMAgent or AnthropicAgent instance
- `team`: List of agents that will be coordinated by the supervisor
### Optional Parameters
- `storage`: Custom storage implementation for conversation history (defaults to InMemoryChatStorage)
- `trace`: Enable detailed logging of agent interactions
- `extraTools`/`extra_tools`: Additional tools to be made available to the supervisor
### Built-in Tools
#### send_messages Tool
The SupervisorAgent includes a built-in tool for parallel message processing:
```json
{
"name": "send_messages",
"description": "Send messages to multiple agents in parallel.",
"properties": {
"messages": {
"type": "array",
"items": {
"type": "object",
"properties": {
"recipient": {
"type": "string",
"description": "Agent name to send message to."
},
"content": {
"type": "string",
"description": "Message content."
}
},
"required": ["recipient", "content"]
},
"description": "Array of messages for different agents.",
"minItems": 1
}
}
}
```
### Adding Custom Tools
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
const customTools = [
new AgentTool({
name: "analyze_sentiment",
description: "Analyze message sentiment",
properties: {
text: {
type: "string",
description: "Text to analyze"
}
},
required: ["text"],
func: analyzeSentiment
})
];
const supervisorAgent = new SupervisorAgent({
leadAgent: supervisor,
team: [techAgent, billingAgent],
extraTools: customTools
});
```
</TabItem>
<TabItem label="Python" icon="seti:python">
```python
custom_tools = [
AgentTool(
name="analyze_sentiment",
description="Analyze message sentiment",
properties={
"text": {
"type": "string",
"description": "Text to analyze"
}
},
required=["text"],
func=analyze_sentiment
)
]
supervisor_agent = SupervisorAgent(SupervisorAgentOptions(
lead_agent=supervisor,
team=[tech_agent, billing_agent],
extra_tools=custom_tools
))
```
</TabItem>
</Tabs>
## Communication Guidelines
1. **Response Handling**
- Aggregates responses from all relevant agents
- Maintains original agent responses without summarization
- Provides final answers only when all necessary responses are received
2. **Agent Interaction**
- Optimizes for parallel processing when possible
- Maintains agent isolation (agents are unaware of each other)
- Keeps inter-agent communications concise
3. **Context Management**
- Provides full context when necessary
- Reuses previous responses when appropriate
- Maintains efficient conversation history
4. **Input Processing**
- Forwards simple inputs directly to relevant agents
- Extracts all relevant data before creating action plans
- Never assumes parameter values
## Best Practices
1. **Agent Team Composition**
- Choose specialized agents with clear, distinct roles
- Ensure agent descriptions are detailed and non-overlapping
- Consider communication patterns when selecting team size
2. **Storage Configuration**
- Use persistent storage (e.g., DynamoDBChatStorage) for production
- Consider memory usage with large conversation histories
- Implement appropriate cleanup strategies
3. **Tool Management**
- Add custom tools through extraTools/extra_tools parameter
- Keep tool functions focused and well-documented
- Consider performance impact of tool complexity
4. **Performance Optimization**
4. **Performance Optimization**
- Enable parallel processing where appropriate
- Monitor and adjust team size based on requirements
- Use tracing to identify bottlenecks
- Configure memory storage based on expected conversation volumes
## Complete Example
Here's a complete example showing how to use the SupervisorAgent in a typical scenario:
<Tabs syncKey="runtime">
<TabItem label="TypeScript" icon="seti:typescript" color="blue">
```typescript
import {
AgentSquad,
BedrockLLMAgent,
SupervisorAgent,
DynamoDBChatStorage,
AgentTool,
AgentTools
} from 'agent-squad';
// Function to analyze sentiment (implementation would go here)
async function analyzeSentiment(text: string): Promise<{ sentiment: string; score: number }> {
return {
sentiment: "positive",
score: 0.8
};
}
async function main() {
// Create orchestrator
const orchestrator = new AgentSquad();
// Create supervisor (lead agent)
const supervisor = new BedrockLLMAgent({
name: "Team Lead",
description: "Coordinates specialized team members",
modelId: "anthropic.claude-3-sonnet-20240229-v1:0"
});
// Create team members
const techAgent = new BedrockLLMAgent({
name: "Tech Support",
description: "Handles technical issues",
modelId: "anthropic.claude-3-sonnet-20240229-v1:0"
});
const billingAgent = new BedrockLLMAgent({
name: "Billing Expert",
description: "Handles billing and payment queries",
modelId: "anthropic.claude-3-sonnet-20240229-v1:0"
});
// Create custom tools
const customTools = [
new AgentTool({
name: "analyze_sentiment",
description: "Analyze message sentiment",
properties: {
text: {
type: "string",
description: "Text to analyze"
}
},
required: ["text"],
func: analyzeSentiment
})
];
// Create SupervisorAgent
const supervisorAgent = new SupervisorAgent({
leadAgent: supervisor,
team: [techAgent, billingAgent],
storage: new DynamoDBChatStorage("conversation-table", "us-east-1"),
trace: true,
extraTools: new AgentTools(customTools)
});
// Add supervisor agent to orchestrator
orchestrator.addAgent(supervisorAgent);
try {
// Process request
const response = await orchestrator.routeRequest(
"I'm having issues with my bill and the mobile app",
"user123",
"session456"
);
// Handle the response (streaming or non-streaming)
if (response.streaming) {
console.log("\n** STREAMING RESPONSE **");
console.log(`Agent: ${response.metadata.agentName}`);
// Handle streaming response
for await (const chunk of response.output) {
gitextract_g9hwz37y/
├── .gitattributes
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ ├── bug_report.yml
│ │ └── feature_request.yml
│ ├── PULL_REQUEST_TEMPLATE.md
│ └── workflows/
│ ├── npm-publish.yml
│ ├── on-docs-update.yml
│ ├── on-issue-opened.yml
│ ├── on-push.yml
│ ├── pr-issue-link-checker.yml
│ ├── py-run-tests.yml
│ ├── pypi-publish.yml
│ ├── ts-run-lint.yml
│ ├── ts-run-security-checks.yml
│ └── ts-run-tests.yml
├── .gitignore
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── docs/
│ ├── .gitignore
│ ├── README.md
│ ├── astro.config.mjs
│ ├── package.json
│ ├── src/
│ │ ├── components/
│ │ │ └── code.astro
│ │ ├── content/
│ │ │ ├── config.ts
│ │ │ └── docs/
│ │ │ ├── agents/
│ │ │ │ ├── built-in/
│ │ │ │ │ ├── amazon-bedrock-agent.mdx
│ │ │ │ │ ├── anthropic-agent.mdx
│ │ │ │ │ ├── bedrock-flows-agent.mdx
│ │ │ │ │ ├── bedrock-inline-agent.mdx
│ │ │ │ │ ├── bedrock-llm-agent.mdx
│ │ │ │ │ ├── bedrock-translator-agent.mdx
│ │ │ │ │ ├── chain-agent.mdx
│ │ │ │ │ ├── comprehend-filter-agent.mdx
│ │ │ │ │ ├── lambda-agent.mdx
│ │ │ │ │ ├── lex-bot-agent.mdx
│ │ │ │ │ ├── openai-agent.mdx
│ │ │ │ │ └── supervisor-agent.mdx
│ │ │ │ ├── custom-agents.mdx
│ │ │ │ ├── overview.mdx
│ │ │ │ └── tools.mdx
│ │ │ ├── classifiers/
│ │ │ │ ├── built-in/
│ │ │ │ │ ├── anthropic-classifier.mdx
│ │ │ │ │ ├── bedrock-classifier.mdx
│ │ │ │ │ └── openai-classifier.mdx
│ │ │ │ ├── custom-classifier.mdx
│ │ │ │ └── overview.mdx
│ │ │ ├── cookbook/
│ │ │ │ ├── examples/
│ │ │ │ │ ├── api-agent.mdx
│ │ │ │ │ ├── chat-chainlit-app.md
│ │ │ │ │ ├── chat-demo-app.md
│ │ │ │ │ ├── ecommerce-support-simulator.md
│ │ │ │ │ ├── fast-api-streaming.md
│ │ │ │ │ ├── ollama-agent.mdx
│ │ │ │ │ ├── ollama-classifier.mdx
│ │ │ │ │ ├── python-local-demo.md
│ │ │ │ │ └── typescript-local-demo.md
│ │ │ │ ├── lambda/
│ │ │ │ │ ├── aws-lambda-nodejs.md
│ │ │ │ │ └── aws-lambda-python.md
│ │ │ │ ├── monitoring/
│ │ │ │ │ ├── agent-overlap.md
│ │ │ │ │ ├── logging.mdx
│ │ │ │ │ └── observability.mdx
│ │ │ │ ├── patterns/
│ │ │ │ │ ├── cost-efficient.md
│ │ │ │ │ └── multi-lingual.md
│ │ │ │ └── tools/
│ │ │ │ ├── math-operations.md
│ │ │ │ └── weather-api.mdx
│ │ │ ├── general/
│ │ │ │ ├── faq.md
│ │ │ │ ├── how-it-works.md
│ │ │ │ ├── introduction.md
│ │ │ │ └── quickstart.mdx
│ │ │ ├── index.mdx
│ │ │ ├── orchestrator/
│ │ │ │ └── overview.mdx
│ │ │ ├── retrievers/
│ │ │ │ ├── built-in/
│ │ │ │ │ └── bedrock-kb-retriever.mdx
│ │ │ │ ├── custom-retriever.mdx
│ │ │ │ └── overview.md
│ │ │ └── storage/
│ │ │ ├── custom.mdx
│ │ │ ├── dynamodb.mdx
│ │ │ ├── in-memory.mdx
│ │ │ ├── overview.md
│ │ │ └── sql.mdx
│ │ ├── env.d.ts
│ │ └── styles/
│ │ ├── custom.css
│ │ ├── font.css
│ │ ├── landing.css
│ │ └── terminal.css
│ └── tsconfig.json
├── examples/
│ ├── bedrock-flows/
│ │ ├── python/
│ │ │ └── main.py
│ │ ├── readme.md
│ │ └── typescript/
│ │ └── main.ts
│ ├── bedrock-inline-agents/
│ │ ├── python/
│ │ │ └── main.py
│ │ └── typescript/
│ │ └── main.ts
│ ├── bedrock-prompt-routing/
│ │ ├── main.py
│ │ └── readme.md
│ ├── chat-chainlit-app/
│ │ ├── .gitignore
│ │ ├── README.md
│ │ ├── agents.py
│ │ ├── app.py
│ │ ├── chainlit.md
│ │ ├── ollamaAgent.py
│ │ └── requirements.txt
│ ├── chat-demo-app/
│ │ ├── .gitignore
│ │ ├── .npmignore
│ │ ├── README.md
│ │ ├── bin/
│ │ │ └── chat-demo-app.ts
│ │ ├── cdk.json
│ │ ├── jest.config.js
│ │ ├── lambda/
│ │ │ ├── auth/
│ │ │ │ ├── index.mjs
│ │ │ │ └── package.json
│ │ │ ├── find-my-name/
│ │ │ │ └── lambda.py
│ │ │ ├── multi-agent/
│ │ │ │ ├── index.ts
│ │ │ │ ├── math_tool.ts
│ │ │ │ ├── prompts.ts
│ │ │ │ └── weather_tool.ts
│ │ │ └── sync_bedrock_knowledgebase/
│ │ │ └── lambda.py
│ │ ├── lib/
│ │ │ ├── CustomResourcesLambda/
│ │ │ │ ├── aoss-index-create.ts
│ │ │ │ ├── data-source-sync.ts
│ │ │ │ └── permission-validation.ts
│ │ │ ├── airlines.yaml
│ │ │ ├── bedrock-agent-construct.ts
│ │ │ ├── chat-demo-app-stack.ts
│ │ │ ├── constants.ts
│ │ │ ├── knowledge-base-construct.ts
│ │ │ ├── lex-agent-construct.ts
│ │ │ ├── user-interface-stack.ts
│ │ │ └── utils/
│ │ │ ├── OpensearchServerlessHelper.ts
│ │ │ └── utils.ts
│ │ ├── package.json
│ │ ├── scripts/
│ │ │ └── download.js
│ │ ├── test/
│ │ │ └── chat-demo-app.ts
│ │ ├── tsconfig.json
│ │ └── ui/
│ │ ├── .babelrc
│ │ ├── .gitignore
│ │ ├── .vscode/
│ │ │ ├── extensions.json
│ │ │ └── launch.json
│ │ ├── README.md
│ │ ├── astro.config.mjs
│ │ ├── package.json
│ │ ├── src/
│ │ │ ├── components/
│ │ │ │ ├── ChatWindow.tsx
│ │ │ │ ├── emojiHelper.ts
│ │ │ │ └── loadingScreen.tsx
│ │ │ ├── pages/
│ │ │ │ └── index.astro
│ │ │ └── utils/
│ │ │ ├── ApiClient.ts
│ │ │ └── amplifyConfig.ts
│ │ ├── tailwind.config.cjs
│ │ └── tsconfig.json
│ ├── ecommerce-support-simulator/
│ │ ├── .gitignore
│ │ ├── .npmignore
│ │ ├── README.md
│ │ ├── bin/
│ │ │ └── ai-ecommerce-support-simulator.ts
│ │ ├── cdk.json
│ │ ├── graphql/
│ │ │ ├── Query.sendMessage.js
│ │ │ ├── schema.graphql
│ │ │ ├── sendResponse.js
│ │ │ └── sendResponsePipeline.js
│ │ ├── jest.config.js
│ │ ├── lambda/
│ │ │ ├── customerMessage/
│ │ │ │ ├── agents.ts
│ │ │ │ ├── index.ts
│ │ │ │ └── sqsLogger.ts
│ │ │ ├── sendResponse/
│ │ │ │ └── index.ts
│ │ │ └── supportMessage/
│ │ │ └── index.ts
│ │ ├── lib/
│ │ │ ├── ai-ecommerce-support-simulator-stack.ts
│ │ │ └── utils/
│ │ │ └── utils.ts
│ │ ├── package.json
│ │ ├── resources/
│ │ │ └── ui/
│ │ │ ├── .gitignore
│ │ │ ├── .vscode/
│ │ │ │ ├── extensions.json
│ │ │ │ └── launch.json
│ │ │ ├── README.md
│ │ │ ├── astro.config.mjs
│ │ │ ├── package.json
│ │ │ ├── public/
│ │ │ │ └── mock_data.json
│ │ │ ├── src/
│ │ │ │ ├── components/
│ │ │ │ │ ├── ChatMode.tsx
│ │ │ │ │ ├── EmailMode.tsx
│ │ │ │ │ ├── SupportSimulator.tsx
│ │ │ │ │ └── email-templates.json
│ │ │ │ ├── consts.ts
│ │ │ │ ├── content/
│ │ │ │ │ └── config.ts
│ │ │ │ ├── layouts/
│ │ │ │ │ └── Layout.astro
│ │ │ │ ├── pages/
│ │ │ │ │ └── index.astro
│ │ │ │ ├── styles/
│ │ │ │ │ └── global.css
│ │ │ │ ├── types.ts
│ │ │ │ └── utils/
│ │ │ │ └── amplifyConfig.ts
│ │ │ ├── tailwind.config.js
│ │ │ └── tsconfig.json
│ │ ├── test/
│ │ │ └── ai-ecommerce-support-simulator.test.ts
│ │ └── tsconfig.json
│ ├── fast-api-streaming/
│ │ ├── README.MD
│ │ ├── main.py
│ │ └── requirements.txt
│ ├── langfuse-demo/
│ │ ├── main.py
│ │ ├── readme.md
│ │ ├── requirements.txt
│ │ └── tools/
│ │ └── weather_tool.py
│ ├── local-demo/
│ │ ├── local-orchestrator.ts
│ │ ├── package.json
│ │ └── tools/
│ │ ├── math_tool.ts
│ │ └── weather_tool.ts
│ ├── python/
│ │ ├── imports.py
│ │ ├── main-app.py
│ │ ├── movie-production/
│ │ │ ├── movie-production-demo.py
│ │ │ ├── readme.md
│ │ │ ├── requirements.txt
│ │ │ └── search_web.py
│ │ ├── pages/
│ │ │ └── home.py
│ │ ├── readme.md
│ │ ├── requirements.txt
│ │ └── travel-planner/
│ │ ├── readme.md
│ │ ├── requirements.txt
│ │ ├── search_web.py
│ │ └── travel-planner-demo.py
│ ├── python-demo/
│ │ ├── main-stream.py
│ │ ├── main.py
│ │ └── tools/
│ │ └── weather_tool.py
│ ├── strands-agents-demo/
│ │ ├── main.py
│ │ └── requirements.txt
│ ├── supervisor-mode/
│ │ ├── main.py
│ │ └── weather_tool.py
│ ├── text-2-structured-output/
│ │ ├── README.md
│ │ ├── multi_agent_query_analyzer.py
│ │ ├── product_search_agent.py
│ │ ├── prompts.py
│ │ └── requirements.txt
│ └── tools/
│ └── python/
│ └── weather_tool_example.py
├── python/
│ ├── .gitignore
│ ├── CONTRIBUTING.md
│ ├── Makefile
│ ├── README.md
│ ├── pyproject.toml
│ ├── ruff.toml
│ ├── setup.cfg
│ ├── setup.py
│ ├── src/
│ │ ├── agent_squad/
│ │ │ ├── __init__.py
│ │ │ ├── agents/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── agent.py
│ │ │ │ ├── amazon_bedrock_agent.py
│ │ │ │ ├── anthropic_agent.py
│ │ │ │ ├── bedrock_flows_agent.py
│ │ │ │ ├── bedrock_inline_agent.py
│ │ │ │ ├── bedrock_llm_agent.py
│ │ │ │ ├── bedrock_translator_agent.py
│ │ │ │ ├── chain_agent.py
│ │ │ │ ├── comprehend_filter_agent.py
│ │ │ │ ├── lambda_agent.py
│ │ │ │ ├── lex_bot_agent.py
│ │ │ │ ├── openai_agent.py
│ │ │ │ ├── strands_agent.py
│ │ │ │ └── supervisor_agent.py
│ │ │ ├── classifiers/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── anthropic_classifier.py
│ │ │ │ ├── bedrock_classifier.py
│ │ │ │ ├── classifier.py
│ │ │ │ └── openai_classifier.py
│ │ │ ├── orchestrator.py
│ │ │ ├── retrievers/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── amazon_kb_retriever.py
│ │ │ │ └── retriever.py
│ │ │ ├── shared/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── user_agent.py
│ │ │ │ └── version.py
│ │ │ ├── storage/
│ │ │ │ ├── __init__.py
│ │ │ │ ├── chat_storage.py
│ │ │ │ ├── dynamodb_chat_storage.py
│ │ │ │ ├── in_memory_chat_storage.py
│ │ │ │ └── sql_chat_storage.py
│ │ │ ├── types/
│ │ │ │ ├── __init__.py
│ │ │ │ └── types.py
│ │ │ └── utils/
│ │ │ ├── __init__.py
│ │ │ ├── helpers.py
│ │ │ ├── logger.py
│ │ │ └── tool.py
│ │ └── tests/
│ │ ├── __init__.py
│ │ ├── agents/
│ │ │ ├── __init__.py
│ │ │ ├── test_agent.py
│ │ │ ├── test_amazon_bedrock_agent.py
│ │ │ ├── test_anthropic_agent.py
│ │ │ ├── test_bedrock_flows_agent.py
│ │ │ ├── test_bedrock_inline_agent.py
│ │ │ ├── test_bedrock_llm_agent.py
│ │ │ ├── test_comprehend_agent.py
│ │ │ ├── test_lambda_agent.py
│ │ │ ├── test_lex_bot_agent.py
│ │ │ ├── test_openai_agent.py
│ │ │ ├── test_strands_agent.py
│ │ │ └── test_supervisor_agent.py
│ │ ├── classifiers/
│ │ │ ├── __init__.py
│ │ │ ├── test_anthropic_classifier.py
│ │ │ └── test_classifier.py
│ │ ├── pytest.ini
│ │ ├── retrievers/
│ │ │ └── test_retriever.py
│ │ ├── storage/
│ │ │ ├── __init__.py
│ │ │ ├── test_chat_storage.py
│ │ │ ├── test_dynamodb_chat_storage.py
│ │ │ ├── test_in_memory_chat_storage.py
│ │ │ └── test_sql_chat_storage.py
│ │ ├── test_orchestrator.py
│ │ └── utils/
│ │ ├── test_helpers.py
│ │ ├── test_logger.py
│ │ └── test_tool.py
│ └── test_requirements.txt
└── typescript/
├── .eslintrc.js
├── .npmignore
├── README.md
├── jest.config.js
├── package.json
├── src/
│ ├── agentOverlapAnalyzer.ts
│ ├── agents/
│ │ ├── agent.ts
│ │ ├── amazonBedrockAgent.ts
│ │ ├── anthropicAgent.ts
│ │ ├── bedrockFlowsAgent.ts
│ │ ├── bedrockInlineAgent.ts
│ │ ├── bedrockLLMAgent.ts
│ │ ├── bedrockTranslatorAgent.ts
│ │ ├── chainAgent.ts
│ │ ├── comprehendFilterAgent.ts
│ │ ├── lambdaAgent.ts
│ │ ├── lexBotAgent.ts
│ │ ├── openAIAgent.ts
│ │ └── supervisorAgent.ts
│ ├── classifiers/
│ │ ├── anthropicClassifier.ts
│ │ ├── bedrockClassifier.ts
│ │ ├── classifier.ts
│ │ └── openAIClassifier.ts
│ ├── common/
│ │ └── src/
│ │ ├── awsSdkUtils.ts
│ │ ├── types/
│ │ │ └── awsSdk.ts
│ │ └── version.ts
│ ├── index.ts
│ ├── orchestrator.ts
│ ├── retrievers/
│ │ ├── AmazonKBRetriever.ts
│ │ └── retriever.ts
│ ├── storage/
│ │ ├── chatStorage.ts
│ │ ├── dynamoDbChatStorage.ts
│ │ ├── memoryChatStorage.ts
│ │ └── sqlChatStorage.ts
│ ├── types/
│ │ └── index.ts
│ └── utils/
│ ├── chatUtils.ts
│ ├── helpers.ts
│ ├── logger.ts
│ └── tool.ts
├── tests/
│ ├── Orchestrator.test.ts
│ ├── agents/
│ │ ├── Agents.test.ts
│ │ ├── LambdaAgent.test.ts
│ │ └── OpenAi.test.ts
│ ├── classifiers/
│ │ ├── AnthropicClassifier.test.ts
│ │ ├── BedrockClassifier.test.ts
│ │ ├── Classifier.test.ts
│ │ └── OpenAIClassifier.test.ts
│ ├── mock/
│ │ └── mockAgent.ts
│ ├── retrievers/
│ │ └── Retriever.test.ts
│ ├── storage/
│ │ └── ChatStorage.test.ts
│ └── utils/
│ └── Utils.test.ts
└── tsconfig.json
SYMBOL INDEX (1186 symbols across 153 files)
FILE: examples/bedrock-flows/python/main.py
function handle_request (line 10) | async def handle_request(_orchestrator: AgentSquad,agent:Agent, _user_in...
function flow_input_encoder (line 21) | def flow_input_encoder(agent:Agent, input: str, **kwargs) -> Any:
function flow_output_decode (line 35) | def flow_output_decode(agent:Agent, response: Any, **kwargs) -> Any:
FILE: examples/bedrock-flows/typescript/main.ts
function createOrchestrator (line 44) | function createOrchestrator(): AgentSquad {
function runLocalConversation (line 71) | async function runLocalConversation(): Promise<void> {
FILE: examples/bedrock-inline-agents/python/main.py
function run_inline_agent (line 55) | async def run_inline_agent(user_input, user_id, session_id):
FILE: examples/bedrock-inline-agents/typescript/main.ts
function runInlineAgent (line 62) | async function runInlineAgent(userInput: string, userId: string, session...
function main (line 73) | async function main() {
FILE: examples/bedrock-prompt-routing/main.py
class LLMAgentCallbacks (line 16) | class LLMAgentCallbacks(AgentCallbacks):
method on_llm_new_token (line 17) | def on_llm_new_token(self, token: str) -> None:
function handle_request (line 22) | async def handle_request(_orchestrator: AgentSquad, _user_input:str, _us...
function custom_input_payload_encoder (line 35) | def custom_input_payload_encoder(input_text: str,
function custom_output_payload_decoder (line 44) | def custom_output_payload_decoder(response: dict[str, Any]) -> Any:
FILE: examples/chat-chainlit-app/agents.py
class ChainlitAgentCallbacks (line 7) | class ChainlitAgentCallbacks(AgentCallbacks):
method on_llm_new_token (line 8) | def on_llm_new_token(self, token: str) -> None:
function create_tech_agent (line 11) | def create_tech_agent():
function create_travel_agent (line 20) | def create_travel_agent():
function create_health_agent (line 29) | def create_health_agent():
FILE: examples/chat-chainlit-app/app.py
function start (line 39) | async def start():
function main (line 47) | async def main(message: cl.Message):
FILE: examples/chat-chainlit-app/ollamaAgent.py
class OllamaAgentOptions (line 9) | class OllamaAgentOptions(AgentOptions):
class OllamaAgent (line 13) | class OllamaAgent(Agent):
method __init__ (line 14) | def __init__(self, options: OllamaAgentOptions):
method handle_streaming_response (line 19) | async def handle_streaming_response(self, messages: List[Dict[str, str...
method process_request (line 42) | async def process_request(
FILE: examples/chat-demo-app/lambda/auth/index.mjs
constant REGION (line 20) | const REGION = "us-east-1";
function Sha256 (line 39) | function Sha256(secret) {
function signRequest (line 43) | async function signRequest(request) {
function verifyToken (line 123) | async function verifyToken(authorization) {
FILE: examples/chat-demo-app/lambda/find-my-name/lambda.py
function lambda_handler (line 3) | def lambda_handler(event, context):
FILE: examples/chat-demo-app/lambda/multi-agent/index.ts
type LexAgentConfig (line 32) | interface LexAgentConfig {
type BodyData (line 40) | interface BodyData {
constant LEX_AGENT_ENABLED (line 46) | const LEX_AGENT_ENABLED = process.env.LEX_AGENT_ENABLED || "false";
function eventHandler (line 222) | async function eventHandler(
FILE: examples/chat-demo-app/lambda/multi-agent/math_tool.ts
function executeMathOperation (line 78) | function executeMathOperation(
function calculateStatistics (line 140) | function calculateStatistics(operation: string, args: number[]): { resul...
function mathToolHanlder (line 181) | async function mathToolHanlder(response:any, conversation: ConversationM...
FILE: examples/chat-demo-app/lambda/multi-agent/prompts.ts
constant WEATHER_AGENT_PROMPT (line 3) | const WEATHER_AGENT_PROMPT = `
constant HEALTH_AGENT_PROMPT (line 65) | const HEALTH_AGENT_PROMPT = `
constant TECH_AGENT_PROMPT (line 128) | const TECH_AGENT_PROMPT = `
constant MATH_AGENT_PROMPT (line 196) | const MATH_AGENT_PROMPT = `
FILE: examples/chat-demo-app/lambda/multi-agent/weather_tool.ts
type InputData (line 32) | interface InputData {
type WeatherData (line 37) | interface WeatherData {
function weatherToolHanlder (line 43) | async function weatherToolHanlder(response:ConversationMessage, conversa...
function fetchWeatherData (line 77) | async function fetchWeatherData(inputData: InputData): Promise<WeatherDa...
FILE: examples/chat-demo-app/lambda/sync_bedrock_knowledgebase/lambda.py
function lambda_handler (line 6) | def lambda_handler(event, context):
FILE: examples/chat-demo-app/lib/CustomResourcesLambda/aoss-index-create.ts
constant CLIENT_TIMEOUT_MS (line 12) | const CLIENT_TIMEOUT_MS = 1000;
constant CLIENT_MAX_RETRIES (line 13) | const CLIENT_MAX_RETRIES = 5;
constant CREATE_INDEX_RETRY_CONFIG (line 14) | const CREATE_INDEX_RETRY_CONFIG = {
constant DEFAULT_INDEX_CONFIG (line 21) | const DEFAULT_INDEX_CONFIG = {
FILE: examples/chat-demo-app/lib/CustomResourcesLambda/permission-validation.ts
constant CLIENT_TIMEOUT_MS (line 12) | const CLIENT_TIMEOUT_MS = 10000;
constant CLIENT_MAX_RETRIES (line 13) | const CLIENT_MAX_RETRIES = 5;
constant RETRY_CONFIG (line 15) | const RETRY_CONFIG = {
function sleep (line 123) | async function sleep(ms: number): Promise<void> {
FILE: examples/chat-demo-app/lib/bedrock-agent-construct.ts
class BedrockKbConstruct (line 12) | class BedrockKbConstruct extends Construct {
method constructor (line 18) | constructor(scope: Construct, id: string) {
FILE: examples/chat-demo-app/lib/chat-demo-app-stack.ts
class ChatDemoStack (line 15) | class ChatDemoStack extends cdk.Stack {
method constructor (line 18) | constructor(scope: Construct, id: string, props?: cdk.StackProps) {
FILE: examples/chat-demo-app/lib/constants.ts
constant USER_INPUT_ACTION_NAME (line 1) | const USER_INPUT_ACTION_NAME = "UserInputAction";
constant USER_INPUT_PARENT_SIGNATURE (line 2) | const USER_INPUT_PARENT_SIGNATURE = "AMAZON.UserInput";
constant AMAZON_BEDROCK_METADATA (line 4) | const AMAZON_BEDROCK_METADATA = 'AMAZON_BEDROCK_METADATA';
constant AMAZON_BEDROCK_TEXT_CHUNK (line 5) | const AMAZON_BEDROCK_TEXT_CHUNK = 'AMAZON_BEDROCK_TEXT_CHUNK';
constant KB_DEFAULT_VECTOR_FIELD (line 6) | const KB_DEFAULT_VECTOR_FIELD = 'bedrock-knowledge-base-default-vector';
constant MAX_KB_SUPPORTED (line 7) | const MAX_KB_SUPPORTED = 2;
constant DEFAULT_BLOCKED_INPUT_MESSAGE (line 9) | const DEFAULT_BLOCKED_INPUT_MESSAGE ='Invalid input. Query violates our ...
constant DEFAULT_BLOCKED_OUTPUT_MESSAGE (line 10) | const DEFAULT_BLOCKED_OUTPUT_MESSAGE = 'Unable to process. Query violate...
class BedrockKnowledgeBaseModels (line 12) | class BedrockKnowledgeBaseModels {
method constructor (line 20) | constructor(modelName: string, vectorDimension: number) {
method getArn (line 24) | public getArn(region:string): string {
FILE: examples/chat-demo-app/lib/knowledge-base-construct.ts
type KnowledgeBaseStorageConfigurationTypes (line 13) | enum KnowledgeBaseStorageConfigurationTypes {
type KnowledgeBaseStorageConfigurationProps (line 19) | interface KnowledgeBaseStorageConfigurationProps {
type BedrockKnowledgeBaseProps (line 24) | interface BedrockKnowledgeBaseProps {
class BedrockKnowledgeBase (line 59) | class BedrockKnowledgeBase extends Construct {
method constructor (line 68) | constructor(scope: Construct, id: string, props: BedrockKnowledgeBaseP...
method addAssetFiles (line 105) | public addAssetFiles(files: Buffer[] | FileBufferMap | undefined) {
method createKnowledgeBase (line 124) | private createKnowledgeBase(kbName: string) {
method createRoleForKB (line 148) | private createRoleForKB(): Role {
method addS3Permissions (line 171) | public addS3Permissions(bucketName: string) {
method syncDataSource (line 203) | private syncDataSource(dataSourceId: string, knowledgeBaseId: string) {
method createAndSyncDataSource (line 273) | public createAndSyncDataSource(assetBucketArn: string): bedrock.CfnDat...
method setupOpensearchServerless (line 323) | private setupOpensearchServerless(kbName: string, region: string, acco...
method addAOSSStorageConfigurationToKB (line 351) | private addAOSSStorageConfigurationToKB(collectionArn: string, collect...
method addAOSSPermissions (line 370) | private addAOSSPermissions(collectionArn: string) {
method createValidationLambdaRole (line 384) | private createValidationLambdaRole() {
method waitForPermissionPropagation (line 415) | private waitForPermissionPropagation(validationRole: Role, collectionE...
FILE: examples/chat-demo-app/lib/lex-agent-construct.ts
class LexAgentConstruct (line 6) | class LexAgentConstruct extends Construct {
method constructor (line 12) | constructor(scope: Construct, id: string) {
FILE: examples/chat-demo-app/lib/user-interface-stack.ts
type UserInterfaceProps (line 20) | interface UserInterfaceProps extends cdk.StackProps{
class UserInterfaceStack (line 24) | class UserInterfaceStack extends cdk.Stack {
method constructor (line 29) | constructor(scope: Construct, id: string, props?: UserInterfaceProps ) {
FILE: examples/chat-demo-app/lib/utils/OpensearchServerlessHelper.ts
type OpenSearchServerlessHelperProps (line 12) | interface OpenSearchServerlessHelperProps {
type CollectionType (line 22) | enum CollectionType {
class OpenSearchServerlessHelper (line 35) | class OpenSearchServerlessHelper extends Construct {
method constructor (line 38) | constructor(scope: Construct, id: string, props: OpenSearchServerlessH...
method createIndex (line 73) | createIndex(region:string, lambdaExecutionRole: Role, indexConfigurati...
method createAccessPolicy (line 124) | createAccessPolicy(kbCollectionName: string, accessRoleArns: string[])...
method createEncryptionPolicy (line 174) | createEncryptionPolicy(kbCollectionName: string): opensearch.CfnSecuri...
method createNetworkPolicy (line 198) | createNetworkPolicy(kbCollectionName: string): opensearch.CfnSecurityP...
method createLambdaExecutionRoleForIndex (line 227) | createLambdaExecutionRoleForIndex(region: string, accountId: string): ...
FILE: examples/chat-demo-app/lib/utils/utils.ts
method copyDirRecursive (line 8) | static copyDirRecursive(sourceDir: string, targetDir: string): void {
type FileBufferMap (line 41) | interface FileBufferMap {
function generateFileBufferMap (line 45) | function generateFileBufferMap(files: Buffer[]) {
function writeFilesToDir (line 59) | function writeFilesToDir(dirPath: string, files: FileBufferMap) {
function generateNamesForAOSS (line 74) | function generateNamesForAOSS(resourceName: string, suffix: string) {
FILE: examples/chat-demo-app/scripts/download.js
function downloadFile (line 5) | function downloadFile(url, outputPath) {
FILE: examples/chat-demo-app/ui/src/components/ChatWindow.tsx
method code (line 40) | code({ node, className, children, ...props }) {
FILE: examples/chat-demo-app/ui/src/components/emojiHelper.ts
function replaceTextEmotesWithEmojis (line 46) | function replaceTextEmotesWithEmojis(text: string): string {
FILE: examples/chat-demo-app/ui/src/utils/ApiClient.ts
class ApiClientBase (line 4) | class ApiClientBase {
method getHeaders (line 6) | async getHeaders(): Promise<Record<string, string>> {
method getAccessToken (line 13) | async getAccessToken(): Promise<string | undefined> {
method callStreamingAPI (line 18) | async callStreamingAPI(resource: string, method: string = "GET", body:...
class ChatApiClient (line 42) | class ChatApiClient extends ApiClientBase {
method query (line 43) | async query(path: string, message: string): Promise<Response> {
FILE: examples/chat-demo-app/ui/src/utils/amplifyConfig.ts
type ExtendedResourcesConfig (line 4) | interface ExtendedResourcesConfig extends ResourcesConfig {
function configureAmplify (line 12) | async function configureAmplify(): Promise<void> {
function getAuthToken (line 36) | async function getAuthToken(): Promise<string | undefined> {
function getAwsExports (line 46) | async function getAwsExports(): Promise<ExtendedResourcesConfig> {
FILE: examples/ecommerce-support-simulator/graphql/Query.sendMessage.js
function request (line 3) | function request(ctx) {
function response (line 42) | function response(ctx) {
FILE: examples/ecommerce-support-simulator/graphql/sendResponse.js
function request (line 1) | function request(ctx) {
function response (line 10) | function response(ctx) {
FILE: examples/ecommerce-support-simulator/graphql/sendResponsePipeline.js
function request (line 1) | function request(ctx) {
function response (line 5) | function response(ctx) {
FILE: examples/ecommerce-support-simulator/lambda/customerMessage/agents.ts
function orderManagementToolHandler (line 100) | async function orderManagementToolHandler(
type HumanAgentOptions (line 209) | interface HumanAgentOptions {
class HumanAgent (line 216) | class HumanAgent extends Agent {
method constructor (line 220) | constructor(options: HumanAgentOptions) {
method processRequest (line 231) | async processRequest(
method sendSQSMessage (line 250) | private async sendSQSMessage(destination: string, message: string) {
FILE: examples/ecommerce-support-simulator/lambda/customerMessage/sqsLogger.ts
type LogMessage (line 3) | interface LogMessage {
class SQSLogger (line 8) | class SQSLogger {
method constructor (line 13) | constructor(queueUrl: string, destination: string, region: string = "u...
method sendToSQS (line 19) | private async sendToSQS(message: string): Promise<void> {
method formatMessage (line 39) | private formatMessage(...args: any[]): string {
method log (line 45) | log(...args: any[]): void {
method info (line 50) | info(...args: any[]): void {
method warn (line 54) | warn(...args: any[]): void {
method error (line 58) | error(...args: any[]): void {
method debug (line 62) | debug(...args: any[]): void {
FILE: examples/ecommerce-support-simulator/lambda/sendResponse/index.ts
constant APPSYNC_API_URL (line 7) | const APPSYNC_API_URL = process.env.APPSYNC_API_URL;
constant REGION (line 8) | const REGION = process.env.REGION;
function sendSignedRequest (line 34) | async function sendSignedRequest(variables: { destination: string; messa...
FILE: examples/ecommerce-support-simulator/lib/ai-ecommerce-support-simulator-stack.ts
class AiEcommerceSupportSimulatorStack (line 28) | class AiEcommerceSupportSimulatorStack extends cdk.Stack {
method constructor (line 29) | constructor(scope: Construct, id: string, props?: cdk.StackProps) {
FILE: examples/ecommerce-support-simulator/lib/utils/utils.ts
method copyDirRecursive (line 5) | static copyDirRecursive(sourceDir: string, targetDir: string): void {
FILE: examples/ecommerce-support-simulator/resources/ui/src/components/SupportSimulator.tsx
type OnResponseReceivedSubscription (line 34) | type OnResponseReceivedSubscription = {
FILE: examples/ecommerce-support-simulator/resources/ui/src/consts.ts
constant SITE_TITLE (line 4) | const SITE_TITLE = 'AI-Powered E-commerce Support system';
constant SITE_DESCRIPTION (line 5) | const SITE_DESCRIPTION = 'Welcome to my website!';
FILE: examples/ecommerce-support-simulator/resources/ui/src/types.ts
type Message (line 3) | interface Message {
FILE: examples/ecommerce-support-simulator/resources/ui/src/utils/amplifyConfig.ts
function configureAmplify (line 6) | async function configureAmplify(): Promise<void> {
function getAuthToken (line 30) | async function getAuthToken(): Promise<string | undefined> {
function getAwsExports (line 41) | async function getAwsExports(): Promise<ResourcesConfig> {
FILE: examples/fast-api-streaming/main.py
class Body (line 25) | class Body(BaseModel):
function setup_orchestrator (line 30) | def setup_orchestrator():
function response_generator (line 66) | async def response_generator(query, user_id, session_id):
function stream_chat (line 77) | async def stream_chat(body: Body):
FILE: examples/langfuse-demo/main.py
class BedrockClassifierCallbacks (line 28) | class BedrockClassifierCallbacks(ClassifierCallbacks):
method on_classifier_start (line 30) | async def on_classifier_start(
method on_classifier_stop (line 56) | async def on_classifier_stop(
class LLMAgentCallbacks (line 87) | class LLMAgentCallbacks(AgentCallbacks):
method on_agent_start (line 89) | async def on_agent_start(
method on_agent_end (line 111) | async def on_agent_end(
method on_llm_start (line 135) | async def on_llm_start(
method on_llm_end (line 148) | async def on_llm_end(
class ToolsCallbacks (line 180) | class ToolsCallbacks(AgentToolCallbacks):
method on_tool_start (line 183) | async def on_tool_start(
method on_tool_end (line 198) | async def on_tool_end(
function classify_request (line 213) | async def classify_request(_orchestrator: AgentSquad, _user_input:str, _...
function agent_process_request (line 218) | async def agent_process_request(_orchestrator: AgentSquad, user_input: str,
function handle_request (line 250) | async def handle_request(_orchestrator: AgentSquad, _user_input:str, _us...
function custom_input_payload_encoder (line 260) | def custom_input_payload_encoder(input_text: str,
function custom_output_payload_decoder (line 269) | def custom_output_payload_decoder(response: dict[str, Any]) -> Any:
function run_main (line 286) | def run_main():
FILE: examples/langfuse-demo/tools/weather_tool.py
function fetch_weather_data (line 8) | async def fetch_weather_data(latitude:str, longitude:str):
function anthropic_weather_tool_handler (line 49) | async def anthropic_weather_tool_handler(response: Any, conversation: Li...
function bedrock_weather_tool_handler (line 84) | async def bedrock_weather_tool_handler(response: ConversationMessage, co...
FILE: examples/local-demo/local-orchestrator.ts
function createOrchestrator (line 14) | function createOrchestrator(): AgentSquad {
function runLocalConversation (line 125) | async function runLocalConversation(): Promise<void> {
FILE: examples/local-demo/tools/math_tool.ts
constant MATH_AGENT_PROMPT (line 3) | const MATH_AGENT_PROMPT = `
function executeMathOperation (line 84) | function executeMathOperation(
function calculateStatistics (line 146) | function calculateStatistics(operation: string, args: number[]): { resul...
function mathToolHanlder (line 187) | async function mathToolHanlder(response:any, conversation: ConversationM...
FILE: examples/local-demo/tools/weather_tool.ts
constant WEATHER_PROMPT (line 30) | const WEATHER_PROMPT = `
type InputData (line 47) | interface InputData {
type WeatherData (line 52) | interface WeatherData {
function weatherToolHanlder (line 58) | async function weatherToolHanlder(response:ConversationMessage, conversa...
function fetchWeatherData (line 92) | async function fetchWeatherData(inputData: InputData): Promise<WeatherDa...
FILE: examples/python-demo/main-stream.py
class LLMAgentCallbacks (line 22) | class LLMAgentCallbacks(AgentCallbacks):
method on_agent_start (line 23) | async def on_agent_start(
method on_agent_end (line 36) | async def on_agent_end(
method on_llm_start (line 48) | async def on_llm_start(
method on_llm_end (line 59) | async def on_llm_end(
class CustomToolCallbacks (line 71) | class CustomToolCallbacks(AgentToolCallbacks):
method on_tool_start (line 72) | async def on_tool_start(
method on_tool_end (line 85) | async def on_tool_end(
function handle_request (line 99) | async def handle_request(_orchestrator: AgentSquad, _user_input:str, _us...
function custom_input_payload_encoder (line 132) | def custom_input_payload_encoder(input_text: str,
function custom_output_payload_decoder (line 141) | def custom_output_payload_decoder(response: dict[str, Any]) -> Any:
FILE: examples/python-demo/main.py
class LLMAgentCallbacks (line 20) | class LLMAgentCallbacks(AgentCallbacks):
method on_llm_new_token (line 21) | def on_llm_new_token(self, token: str) -> None:
function handle_request (line 26) | async def handle_request(_orchestrator: AgentSquad, _user_input:str, _us...
function custom_input_payload_encoder (line 39) | def custom_input_payload_encoder(input_text: str,
function custom_output_payload_decoder (line 48) | def custom_output_payload_decoder(response: Dict[str, Any]) -> Any:
FILE: examples/python-demo/tools/weather_tool.py
function fetch_weather_data (line 8) | async def fetch_weather_data(latitude:str, longitude:str):
function anthropic_weather_tool_handler (line 54) | async def anthropic_weather_tool_handler(response: Any, conversation: Li...
function bedrock_weather_tool_handler (line 89) | async def bedrock_weather_tool_handler(response: ConversationMessage, co...
FILE: examples/python/movie-production/movie-production-demo.py
function test_aws_connection (line 18) | def test_aws_connection():
function handle_request (line 118) | async def handle_request(_orchestrator: AgentSquad, _user_input: str, _u...
FILE: examples/python/movie-production/search_web.py
function search_web (line 5) | def search_web(query: str, num_results: int = 2) -> str:
FILE: examples/python/travel-planner/search_web.py
function search_web (line 3) | def search_web(query: str, num_results: int = 2) -> str:
FILE: examples/python/travel-planner/travel-planner-demo.py
function handle_request (line 82) | async def handle_request(_orchestrator: AgentSquad, _user_input: str, _u...
FILE: examples/strands-agents-demo/main.py
function get_user_location (line 40) | def get_user_location() -> str:
function weather (line 48) | def weather(location: str) -> str:
function handle_request (line 59) | async def handle_request(_orchestrator: AgentSquad, _user_input:str, _us...
FILE: examples/supervisor-mode/main.py
class LLMAgentCallbacks (line 36) | class LLMAgentCallbacks(AgentCallbacks):
method on_llm_new_token (line 37) | async def on_llm_new_token(self, token: str, **kwargs) -> None:
class SupervisorToolsCallbacks (line 42) | class SupervisorToolsCallbacks (AgentToolCallbacks):
method on_tool_start (line 43) | async def on_tool_start(
method on_tool_end (line 54) | async def on_tool_end(
method on_tool_error (line 65) | async def on_tool_error(
function get_current_date (line 179) | async def get_current_date():
function handle_request (line 204) | async def handle_request(_orchestrator: AgentSquad, _user_input:str, _us...
FILE: examples/supervisor-mode/weather_tool.py
function weather_tool_handler (line 48) | async def weather_tool_handler(response: ConversationMessage, conversati...
function fetch_weather_data (line 83) | async def fetch_weather_data(input_data):
FILE: examples/text-2-structured-output/multi_agent_query_analyzer.py
class MyCustomHandler (line 24) | class MyCustomHandler(AgentCallbacks):
method __init__ (line 25) | def __init__(self, queue) -> None:
method on_llm_new_token (line 30) | async def on_llm_new_token(self, token: str, **kwargs) -> None:
method on_llm_start (line 33) | async def on_llm_start(self, serialized: Dict[str, Any], prompts: List...
method on_llm_end (line 36) | async def on_llm_end(self, response: Any, **kwargs: Any) -> None:
function setup_orchestrator (line 40) | def setup_orchestrator(streamer_queue):
function start_generation (line 114) | async def start_generation(query, user_id, session_id, streamer_queue):
function response_generator (line 130) | async def response_generator(query, user_id, session_id):
function run_chatbot (line 148) | async def run_chatbot():
FILE: examples/text-2-structured-output/product_search_agent.py
class ProductSearchAgentOptions (line 17) | class ProductSearchAgentOptions(AgentOptions):
class ProductSearchAgent (line 23) | class ProductSearchAgent(Agent):
method __init__ (line 24) | def __init__(self, options: ProductSearchAgentOptions):
method generate_key_from_name (line 42) | def generate_key_from_name(name: str) -> str:
method _create_client (line 48) | def _create_client(self):
method process_request (line 54) | async def process_request(
FILE: examples/text-2-structured-output/prompts.py
function GREETING_AGENT_PROMPT (line 185) | def GREETING_AGENT_PROMPT(agent_list: str) -> str:
FILE: examples/tools/python/weather_tool_example.py
function get_weather (line 11) | def get_weather(city:str):
function bedrock_weather_tool_handler (line 42) | async def bedrock_weather_tool_handler(
function anthropic_weather_tool_handler (line 91) | async def anthropic_weather_tool_handler(response: Any, conversation: li...
function get_weather_info (line 137) | async def get_weather_info(agent:Agent):
FILE: python/src/agent_squad/agents/agent.py
class AgentProcessingResult (line 15) | class AgentProcessingResult:
class AgentStreamResponse (line 37) | class AgentStreamResponse:
class AgentResponse (line 53) | class AgentResponse:
class AgentCallbacks (line 68) | class AgentCallbacks:
method on_agent_start (line 70) | async def on_agent_start(
method on_agent_end (line 102) | async def on_agent_end(
method on_llm_start (line 132) | async def on_llm_start(
method on_llm_new_token (line 166) | async def on_llm_new_token(self,
method on_llm_end (line 180) | async def on_llm_end(
class AgentOptions (line 211) | class AgentOptions:
class Agent (line 232) | class Agent(ABC):
method __init__ (line 240) | def __init__(self, options: AgentOptions):
method is_streaming_enabled (line 256) | def is_streaming_enabled(self) -> bool:
method generate_key_from_name (line 266) | def generate_key_from_name(name: str) -> str:
method process_request (line 282) | async def process_request(
method log_debug (line 305) | def log_debug(self, class_name: str, message: str, data: Any = None) -...
FILE: python/src/agent_squad/agents/amazon_bedrock_agent.py
class AmazonBedrockAgentOptions (line 21) | class AmazonBedrockAgentOptions(AgentOptions):
class AmazonBedrockAgent (line 41) | class AmazonBedrockAgent(Agent):
method __init__ (line 52) | def __init__(self, options: AmazonBedrockAgentOptions):
method is_streaming_enabled (line 85) | def is_streaming_enabled(self) -> bool:
method process_request (line 93) | async def process_request(
FILE: python/src/agent_squad/agents/anthropic_agent.py
class AnthropicAgentOptions (line 13) | class AnthropicAgentOptions(AgentOptions):
class AnthropicAgent (line 40) | class AnthropicAgent(Agent):
method __init__ (line 41) | def __init__(self, options: AnthropicAgentOptions):
method is_streaming_enabled (line 108) | def is_streaming_enabled(self) -> bool:
method _prepare_system_prompt (line 111) | async def _prepare_system_prompt(self, input_text: str) -> str:
method _prepare_conversation (line 123) | def _prepare_conversation(self, input_text: str, chat_history: list[Co...
method _prepare_tool_config (line 137) | def _prepare_tool_config(self) -> dict:
method _build_input (line 150) | def _build_input(self, messages: list[Any], system_prompt: str) -> dict:
method _get_max_recursions (line 182) | def _get_max_recursions(self) -> int:
method _handle_streaming (line 188) | async def _handle_streaming(
method _process_with_strategy (line 258) | async def _process_with_strategy(
method _process_tool_block (line 282) | async def _process_tool_block(
method _handle_single_response_loop (line 299) | async def _handle_single_response_loop(
method process_request (line 326) | async def process_request(
method handle_single_response (line 351) | async def handle_single_response(self, input_data: dict) -> Any:
method handle_streaming_response (line 380) | async def handle_streaming_response(self, payload_input) -> AsyncGener...
method set_system_prompt (line 439) | def set_system_prompt(self, template: Optional[str] = None, variables:...
method update_system_prompt (line 446) | def update_system_prompt(self) -> None:
method replace_placeholders (line 451) | def replace_placeholders(template: str, variables: TemplateVariables) ...
FILE: python/src/agent_squad/agents/bedrock_flows_agent.py
class BedrockFlowsAgentOptions (line 12) | class BedrockFlowsAgentOptions(AgentOptions):
class BedrockFlowsAgent (line 23) | class BedrockFlowsAgent(Agent):
method __init__ (line 25) | def __init__(self, options: BedrockFlowsAgentOptions):
method __default_flow_input_encoder (line 51) | def __default_flow_input_encoder(self,
method __default_flow_output_decoder (line 66) | def __default_flow_output_decoder(self, response: Any, **kwargs) -> Co...
method process_request (line 74) | async def process_request(
FILE: python/src/agent_squad/agents/bedrock_inline_agent.py
class BedrockInlineAgentOptions (line 17) | class BedrockInlineAgentOptions(AgentOptions):
class BedrockInlineAgent (line 31) | class BedrockInlineAgent(Agent):
method __init__ (line 61) | def __init__(self, options: BedrockInlineAgentOptions):
method inline_agent_tool_handler (line 175) | async def inline_agent_tool_handler(self, session_id, response, conver...
method process_request (line 258) | async def process_request(
method set_system_prompt (line 324) | def set_system_prompt(self,
method update_system_prompt (line 333) | def update_system_prompt(self) -> None:
method replace_placeholders (line 338) | def replace_placeholders(template: str, variables: TemplateVariables) ...
FILE: python/src/agent_squad/agents/bedrock_llm_agent.py
class BedrockLLMAgentOptions (line 25) | class BedrockLLMAgentOptions(AgentOptions):
class BedrockLLMAgent (line 38) | class BedrockLLMAgent(Agent):
method __init__ (line 39) | def __init__(self, options: BedrockLLMAgentOptions):
method is_streaming_enabled (line 112) | def is_streaming_enabled(self) -> bool:
method _prepare_system_prompt (line 115) | async def _prepare_system_prompt(self, input_text: str) -> str:
method _prepare_conversation (line 127) | def _prepare_conversation(
method _build_conversation_command (line 135) | def _build_conversation_command(self, conversation: list[ConversationM...
method _prepare_tool_config (line 166) | def _prepare_tool_config(self) -> dict:
method _get_max_recursions (line 182) | def _get_max_recursions(self) -> int:
method _handle_single_response_loop (line 188) | async def _handle_single_response_loop(
method _handle_streaming (line 229) | async def _handle_streaming(
method _process_with_strategy (line 280) | async def _process_with_strategy(
method process_request (line 305) | async def process_request(
method _process_tool_block (line 333) | async def _process_tool_block(
method handle_single_response (line 359) | async def handle_single_response(
method handle_streaming_response (line 424) | async def handle_streaming_response(
method set_system_prompt (line 560) | def set_system_prompt(
method update_system_prompt (line 571) | def update_system_prompt(self) -> None:
method replace_placeholders (line 576) | def replace_placeholders(template: str, variables: TemplateVariables) ...
FILE: python/src/agent_squad/agents/bedrock_translator_agent.py
class BedrockTranslatorAgentOptions (line 9) | class BedrockTranslatorAgentOptions(AgentOptions):
class BedrockTranslatorAgent (line 17) | class BedrockTranslatorAgent(Agent):
method __init__ (line 18) | def __init__(self, options: BedrockTranslatorAgentOptions):
method process_request (line 56) | async def process_request(self,
method set_source_language (line 133) | def set_source_language(self, language: Optional[str]):
method set_target_language (line 137) | def set_target_language(self, language: str):
FILE: python/src/agent_squad/agents/chain_agent.py
class ChainAgentOptions (line 6) | class ChainAgentOptions(AgentOptions):
method __init__ (line 7) | def __init__(self, agents: list[Agent], default_output: Optional[str] ...
class ChainAgent (line 12) | class ChainAgent(Agent):
method __init__ (line 13) | def __init__(self, options: ChainAgentOptions):
method process_request (line 20) | async def process_request(
method is_async_iterable (line 70) | def is_async_iterable(obj: Any) -> bool:
method is_conversation_message (line 74) | def is_conversation_message(response: Any) -> bool:
method create_default_response (line 82) | def create_default_response(self) -> ConversationMessage:
FILE: python/src/agent_squad/agents/comprehend_filter_agent.py
class ComprehendFilterAgentOptions (line 15) | class ComprehendFilterAgentOptions(AgentOptions):
class ComprehendFilterAgent (line 26) | class ComprehendFilterAgent(Agent):
method __init__ (line 27) | def __init__(self, options: ComprehendFilterAgentOptions):
method process_request (line 55) | async def process_request(self,
method add_custom_check (line 105) | def add_custom_check(self, check: CheckFunction):
method check_sentiment (line 108) | def check_sentiment(self, result: dict[str, Any]) -> Optional[str]:
method check_pii (line 113) | def check_pii(self, result: dict[str, Any]) -> Optional[str]:
method check_toxicity (line 118) | def check_toxicity(self, result: dict[str, Any]) -> Optional[str]:
method detect_sentiment (line 124) | def detect_sentiment(self, text: str) -> dict[str, Any]:
method detect_pii_entities (line 130) | def detect_pii_entities(self, text: str) -> dict[str, Any]:
method detect_toxic_content (line 136) | def detect_toxic_content(self, text: str) -> dict[str, Any]:
method get_toxic_labels (line 142) | def get_toxic_labels(self, toxicity_result: dict[str, Any]) -> list[str]:
method set_language_code (line 150) | def set_language_code(self, language_code: str):
method validate_language_code (line 158) | def validate_language_code(language_code: Optional[str]) -> Optional[s...
FILE: python/src/agent_squad/agents/lambda_agent.py
class LambdaAgentOptions (line 11) | class LambdaAgentOptions(AgentOptions):
class LambdaAgent (line 25) | class LambdaAgent(Agent):
method __init__ (line 26) | def __init__(self, options: LambdaAgentOptions):
method __default_input_payload_encoder (line 44) | def __default_input_payload_encoder(self,
method __default_output_payload_decoder (line 61) | def __default_output_payload_decoder(self, response: Dict[str, Any]) -...
method process_request (line 71) | async def process_request(
FILE: python/src/agent_squad/agents/lex_bot_agent.py
class LexBotAgentOptions (line 12) | class LexBotAgentOptions(AgentOptions):
class LexBotAgent (line 19) | class LexBotAgent(Agent):
method __init__ (line 20) | def __init__(self, options: LexBotAgentOptions):
method process_request (line 43) | async def process_request(self, input_text: str, user_id: str, session...
FILE: python/src/agent_squad/agents/openai_agent.py
class OpenAIAgentOptions (line 21) | class OpenAIAgentOptions(AgentOptions):
class OpenAIAgent (line 32) | class OpenAIAgent(Agent):
method __init__ (line 33) | def __init__(self, options: OpenAIAgentOptions):
method is_streaming_enabled (line 93) | def is_streaming_enabled(self) -> bool:
method process_request (line 96) | async def process_request(
method handle_single_response (line 144) | async def handle_single_response(self, request_options: dict[str, Any]...
method handle_streaming_response (line 166) | async def handle_streaming_response(self, request_options: dict[str, A...
method set_system_prompt (line 188) | def set_system_prompt(self,
method update_system_prompt (line 197) | def update_system_prompt(self) -> None:
method replace_placeholders (line 202) | def replace_placeholders(template: str, variables: TemplateVariables) ...
FILE: python/src/agent_squad/agents/strands_agent.py
class StrandsAgent (line 20) | class StrandsAgent(Agent):
method __init__ (line 29) | def __init__(self, options: AgentOptions,
method close (line 107) | def close(self):
method __del__ (line 123) | def __del__(self):
method is_streaming_enabled (line 132) | def is_streaming_enabled(self) -> bool:
method _convert_chat_history_to_strands_format (line 141) | def _convert_chat_history_to_strands_format(
method _convert_strands_result_to_conversation_message (line 174) | def _convert_strands_result_to_conversation_message(
method _prepare_conversation (line 199) | def _prepare_conversation(
method _handle_streaming_response (line 208) | async def _handle_streaming_response(
method _handle_single_response (line 288) | async def _handle_single_response(
method _process_with_strategy (line 349) | async def _process_with_strategy(
method process_request (line 409) | async def process_request(
FILE: python/src/agent_squad/agents/supervisor_agent.py
class SupervisorAgentOptions (line 15) | class SupervisorAgentOptions(AgentOptions):
method validate (line 22) | def validate(self) -> None:
class SupervisorAgent (line 58) | class SupervisorAgent(Agent):
method __init__ (line 67) | def __init__(self, options: SupervisorAgentOptions):
method _configure_supervisor_tools (line 84) | def _configure_supervisor_tools(self, extra_tools: Optional[Union[Agen...
method _configure_prompt (line 128) | def _configure_prompt(self) -> None:
method process_agent_streaming_response (line 178) | async def process_agent_streaming_response(self, response):
method send_message (line 187) | def send_message(
method send_messages (line 242) | async def send_messages(self, messages: list[dict[str, str]]) -> str:
method _format_agents_memory (line 271) | def _format_agents_memory(self, agents_history: list[ConversationMessa...
method is_streaming_enabled (line 280) | def is_streaming_enabled(self):
method process_request (line 283) | async def process_request(
FILE: python/src/agent_squad/classifiers/anthropic_classifier.py
class AnthropicClassifierOptions (line 11) | class AnthropicClassifierOptions:
method __init__ (line 12) | def __init__(self,
class AnthropicClassifier (line 23) | class AnthropicClassifier(Classifier):
method __init__ (line 24) | def __init__(self, options: AnthropicClassifierOptions):
method process_request (line 71) | async def process_request(self,
FILE: python/src/agent_squad/classifiers/bedrock_classifier.py
class BedrockClassifierOptions (line 11) | class BedrockClassifierOptions:
method __init__ (line 12) | def __init__(
class BedrockClassifier (line 27) | class BedrockClassifier(Classifier):
method __init__ (line 28) | def __init__(self, options: BedrockClassifierOptions):
method process_request (line 77) | async def process_request(self,
FILE: python/src/agent_squad/classifiers/classifier.py
class ClassifierCallbacks (line 9) | class ClassifierCallbacks():
method on_classifier_start (line 10) | async def on_classifier_start(
method on_classifier_stop (line 21) | async def on_classifier_stop(
class ClassifierResult (line 33) | class ClassifierResult:
class Classifier (line 37) | class Classifier(ABC):
method __init__ (line 38) | def __init__(self):
method set_agents (line 148) | def set_agents(self, agents: Dict[str, Agent]) -> None:
method set_history (line 153) | def set_history(self, messages: List[ConversationMessage]) -> None:
method set_system_prompt (line 156) | def set_system_prompt(self,
method format_messages (line 166) | def format_messages(messages: List[ConversationMessage]) -> str:
method classify (line 171) | async def classify(self,
method process_request (line 179) | async def process_request(self,
method update_system_prompt (line 184) | def update_system_prompt(self) -> None:
method replace_placeholders (line 193) | def replace_placeholders(template: str, variables: TemplateVariables) ...
method get_agent_by_id (line 200) | def get_agent_by_id(self, agent_id: str) -> Optional[Agent]:
FILE: python/src/agent_squad/classifiers/openai_classifier.py
class OpenAIClassifierOptions (line 11) | class OpenAIClassifierOptions:
method __init__ (line 12) | def __init__(self,
class OpenAIClassifier (line 20) | class OpenAIClassifier(Classifier):
method __init__ (line 21) | def __init__(self, options: OpenAIClassifierOptions):
method process_request (line 68) | async def process_request(self,
FILE: python/src/agent_squad/orchestrator.py
class AgentSquad (line 23) | class AgentSquad:
method __init__ (line 24) | def __init__(self,
method add_agent (line 63) | def add_agent(self, agent: Agent):
method get_default_agent (line 69) | def get_default_agent(self) -> Agent:
method set_default_agent (line 72) | def set_default_agent(self, agent: Agent):
method get_all_agents (line 75) | def get_all_agents(self) -> dict[str, dict[str, str]]:
method dispatch_to_agent (line 81) | async def dispatch_to_agent(self, params: dict[str, Any]
method classify_request (line 111) | async def classify_request(self,
method agent_process_request (line 137) | async def agent_process_request(self,
method route_request (line 244) | async def route_request(self,
method print_intent (line 291) | def print_intent(self, user_input: str, intent_classifier_result: Clas...
method measure_execution_time (line 302) | async def measure_execution_time(self, timer_name: str, fn):
method create_metadata (line 321) | def create_metadata(self,
method get_fallback_result (line 347) | def get_fallback_result(self) -> ClassifierResult:
method save_message (line 350) | async def save_message(self,
method save_messages (line 360) | async def save_messages(self,
FILE: python/src/agent_squad/retrievers/amazon_kb_retriever.py
class AmazonKnowledgeBasesRetrieverOptions (line 7) | class AmazonKnowledgeBasesRetrieverOptions:
class AmazonKnowledgeBasesRetriever (line 15) | class AmazonKnowledgeBasesRetriever(Retriever):
method __init__ (line 16) | def __init__(self, options: AmazonKnowledgeBasesRetrieverOptions):
method retrieve_and_generate (line 29) | async def retrieve_and_generate(self, text, retrieve_and_generate_conf...
method retrieve (line 32) | async def retrieve(self, text, knowledge_base_id=None, retrieval_confi...
method retrieve_and_combine_results (line 44) | async def retrieve_and_combine_results(self, text, knowledge_base_id=N...
method combine_retrieval_results (line 50) | def combine_retrieval_results(retrieval_results):
FILE: python/src/agent_squad/retrievers/retriever.py
class Retriever (line 4) | class Retriever(ABC):
method __init__ (line 10) | def __init__(self, options: dict):
method retrieve (line 20) | async def retrieve(self, text: str) -> Any:
method retrieve_and_combine_results (line 34) | async def retrieve_and_combine_results(self, text: str) -> Any:
method retrieve_and_generate (line 49) | async def retrieve_and_generate(self, text: str) -> Any:
FILE: python/src/agent_squad/shared/user_agent.py
function _initializer_botocore_session (line 24) | def _initializer_botocore_session(session):
function _create_feature_function (line 46) | def _create_feature_function(feature):
function register_feature_to_session (line 87) | def register_feature_to_session(session, feature):
function register_feature_to_botocore_session (line 112) | def register_feature_to_botocore_session(botocore_session, feature):
function register_feature_to_client (line 151) | def register_feature_to_client(client, feature):
function register_feature_to_resource (line 176) | def register_feature_to_resource(resource, feature):
function inject_user_agent (line 200) | def inject_user_agent():
FILE: python/src/agent_squad/storage/chat_storage.py
class ChatStorage (line 5) | class ChatStorage(ABC):
method is_same_role_as_last_message (line 8) | def is_same_role_as_last_message(self,
method trim_conversation (line 25) | def trim_conversation(self,
method save_chat_message (line 48) | async def save_chat_message(self,
method save_chat_messages (line 69) | async def save_chat_messages(self,
method fetch_chat (line 90) | async def fetch_chat(self,
method fetch_all_chats (line 109) | async def fetch_all_chats(self,
FILE: python/src/agent_squad/storage/dynamodb_chat_storage.py
class DynamoDbChatStorage (line 11) | class DynamoDbChatStorage(ChatStorage):
method __init__ (line 12) | def __init__(self,
method save_chat_message (line 25) | async def save_chat_message(
method save_chat_messages (line 70) | async def save_chat_messages(self,
method fetch_chat (line 122) | async def fetch_chat(
method fetch_chat_with_timestamp (line 139) | async def fetch_chat_with_timestamp(
method fetch_all_chats (line 156) | async def fetch_all_chats(self, user_id: str, session_id: str) -> list...
method _generate_key (line 197) | def _generate_key(self, user_id: str, session_id: str, agent_id: str) ...
method _remove_timestamps (line 200) | def _remove_timestamps(self,
method _dict_to_conversation (line 206) | def _dict_to_conversation(self,
FILE: python/src/agent_squad/storage/in_memory_chat_storage.py
class InMemoryChatStorage (line 8) | class InMemoryChatStorage(ChatStorage):
method __init__ (line 9) | def __init__(self):
method save_chat_message (line 13) | async def save_chat_message(
method save_chat_messages (line 41) | async def save_chat_messages(self,
method fetch_chat (line 70) | async def fetch_chat(
method fetch_all_chats (line 83) | async def fetch_all_chats(
method _generate_key (line 108) | def _generate_key(user_id: str, session_id: str, agent_id: str) -> str:
method _remove_timestamps (line 112) | def _remove_timestamps(messages: list[dict]) -> list[ConversationMessa...
FILE: python/src/agent_squad/storage/sql_chat_storage.py
class SqlChatStorage (line 9) | class SqlChatStorage(ChatStorage):
method __init__ (line 12) | def __init__(
method initialize (line 29) | async def initialize(self) -> None:
method _initialize_database (line 33) | async def _initialize_database(self) -> None:
method save_chat_message (line 59) | async def save_chat_message(
method _validate_message_content (line 130) | def _validate_message_content(self, content: Optional[list[dict[str, s...
method save_chat_messages (line 139) | async def save_chat_messages(
method fetch_chat (line 221) | async def fetch_chat(
method fetch_all_chats (line 256) | async def fetch_all_chats(
method _format_content (line 284) | def _format_content(
method close (line 296) | async def close(self) -> None:
FILE: python/src/agent_squad/types/types.py
class AgentProviderType (line 15) | class AgentProviderType(Enum):
class AgentTypes (line 20) | class AgentTypes(Enum):
class ToolInput (line 24) | class ToolInput(TypedDict):
class RequestMetadata (line 29) | class RequestMetadata(TypedDict):
class ParticipantRole (line 39) | class ParticipantRole(Enum):
class ConversationMessage (line 44) | class ConversationMessage:
method __init__ (line 48) | def __init__(self, role: ParticipantRole, content: Optional[list[Any]]...
class TimestampedMessage (line 52) | class TimestampedMessage(ConversationMessage):
method __init__ (line 53) | def __init__(self,
class AgentSquadConfig (line 63) | class AgentSquadConfig:
FILE: python/src/agent_squad/utils/helpers.py
function is_tool_input (line 7) | def is_tool_input(input_obj: Any) -> bool:
function conversation_to_dict (line 15) | def conversation_to_dict(
function message_to_dict (line 26) | def message_to_dict(message: ConversationMessage | TimestampedMessage) -...
FILE: python/src/agent_squad/utils/logger.py
class Logger (line 8) | class Logger:
method __new__ (line 12) | def __new__(cls, *args, **kwargs):
method __init__ (line 17) | def __init__(self,
method get_logger (line 26) | def get_logger(cls):
method set_logger (line 32) | def set_logger(cls, logger: Any) -> None:
method info (line 36) | def info(cls, message: str, *args: Any) -> None:
method warn (line 41) | def warn(cls, message: str, *args: Any) -> None:
method error (line 46) | def error(cls, message: str, *args: Any) -> None:
method debug (line 51) | def debug(cls, message: str, *args: Any) -> None:
method log_header (line 56) | def log_header(cls, title: str) -> None:
method print_chat_history (line 61) | def print_chat_history(self,
method log_classifier_output (line 85) | def log_classifier_output(self, output: Any, is_raw: bool = False) -> ...
method print_execution_times (line 95) | def print_execution_times(self, execution_times: Dict[str, float]) -> ...
FILE: python/src/agent_squad/utils/tool.py
class PropertyDefinition (line 15) | class PropertyDefinition:
class AgentToolResult (line 22) | class AgentToolResult:
method to_anthropic_format (line 26) | def to_anthropic_format(self) -> dict:
method to_bedrock_format (line 33) | def to_bedrock_format(self) -> dict:
class AgentToolCallbacks (line 42) | class AgentToolCallbacks:
method on_tool_start (line 43) | async def on_tool_start(
method on_tool_end (line 54) | async def on_tool_end(
method on_tool_error (line 66) | async def on_tool_error(
class AgentTool (line 79) | class AgentTool:
method __init__ (line 80) | def __init__(
method _extract_properties (line 116) | def _extract_properties(self, func: Callable) -> dict[str, dict[str, A...
method _wrap_function (line 162) | def _wrap_function(self, func: Callable) -> Callable:
method to_claude_format (line 174) | def to_claude_format(self) -> dict[str, Any]:
method to_bedrock_format (line 186) | def to_bedrock_format(self) -> dict[str, Any]:
method to_openai_format (line 202) | def to_openai_format(self) -> dict[str, Any]:
class AgentTools (line 219) | class AgentTools:
method __init__ (line 220) | def __init__(
method tool_handler (line 226) | async def tool_handler(
method _get_tool_use_block (line 293) | def _get_tool_use_block(
method _process_tool (line 306) | async def _process_tool(self, tool_name, input_data):
method to_claude_format (line 313) | def to_claude_format(self) -> list[dict[str, Any]]:
method to_bedrock_format (line 317) | def to_bedrock_format(self) -> list[dict[str, Any]]:
FILE: python/src/tests/agents/test_agent.py
class TestAgent (line 15) | class TestAgent:
method mock_agent_options (line 17) | def mock_agent_options(self):
method mock_agent (line 27) | def mock_agent(self, mock_agent_options):
method test_agent_processing_result (line 41) | def test_agent_processing_result(self):
method test_agent_processing_result_with_params (line 57) | def test_agent_processing_result_with_params(self):
method test_agent_stream_response (line 74) | def test_agent_stream_response(self):
method test_agent_response (line 88) | def test_agent_response(self):
method test_agent_callbacks (line 104) | async def test_agent_callbacks(self):
method test_agent_options (line 108) | def test_agent_options(self, mock_agent_options):
method test_agent_options_with_debug_trace (line 114) | def test_agent_options_with_debug_trace(self):
method test_agent_initialization (line 128) | def test_agent_initialization(self, mock_agent, mock_agent_options):
method test_generate_key_from_name (line 135) | def test_generate_key_from_name(self):
method test_process_request (line 151) | async def test_process_request(self, mock_agent):
method test_streaming (line 163) | def test_streaming(self, mock_agent):
method test_log_debug (line 167) | async def test_log_debug(self, mock_agent, monkeypatch):
FILE: python/src/tests/agents/test_amazon_bedrock_agent.py
function mock_boto3_client (line 8) | def mock_boto3_client():
function bedrock_agent (line 13) | def bedrock_agent(mock_boto3_client):
function test_init (line 23) | def test_init(bedrock_agent, mock_boto3_client):
function test_process_request_success (line 29) | async def test_process_request_success(bedrock_agent):
function test_process_request_error (line 60) | async def test_process_request_error(bedrock_agent):
function test_process_request_empty_chunk (line 83) | async def test_process_request_empty_chunk(bedrock_agent):
function test_process_request_with_additional_params (line 104) | async def test_process_request_with_additional_params(bedrock_agent):
function test_streaming (line 125) | def test_streaming(mock_boto3_client):
FILE: python/src/tests/agents/test_anthropic_agent.py
function mock_anthropic (line 13) | def mock_anthropic():
function test_no_api_key_init (line 19) | def test_no_api_key_init(mock_anthropic):
function test_callbacks_initialization (line 31) | def test_callbacks_initialization():
function test_client (line 44) | def test_client(mock_anthropic):
function test_inference_config (line 84) | def test_inference_config(mock_anthropic):
function test_custom_system_prompt_with_variable (line 131) | def test_custom_system_prompt_with_variable(mock_anthropic):
function test_custom_system_prompt_with_wrong_variable (line 145) | def test_custom_system_prompt_with_wrong_variable(mock_anthropic):
function test_process_request_single_response (line 160) | async def test_process_request_single_response():
function test_streaming (line 199) | def test_streaming(mock_anthropic):
function test_prepare_system_prompt_with_retriever (line 244) | async def test_prepare_system_prompt_with_retriever():
function test_prepare_conversation (line 263) | async def test_prepare_conversation():
function test_prepare_tool_config (line 290) | async def test_prepare_tool_config():
function test_build_input (line 342) | def test_build_input():
function test_additional_model_request_fields (line 379) | def test_additional_model_request_fields():
function test_get_max_recursions (line 435) | def test_get_max_recursions():
function test_process_tool_block_with_handler (line 456) | async def test_process_tool_block_with_handler():
function test_handle_single_response_with_tools (line 495) | async def test_handle_single_response_with_tools():
function test_handle_streaming_response (line 547) | async def test_handle_streaming_response():
function test_process_with_strategy (line 596) | async def test_process_with_strategy():
function test_handle_single_response_error (line 667) | async def test_handle_single_response_error():
function test_handle_streaming_response_implementation (line 687) | async def test_handle_streaming_response_implementation():
function test_handle_streaming_with_tool_use (line 772) | async def test_handle_streaming_with_tool_use():
FILE: python/src/tests/agents/test_bedrock_flows_agent.py
class TestBedrockFlowsAgent (line 7) | class TestBedrockFlowsAgent:
method setup_method (line 9) | def setup_method(self):
method test_init_with_provided_client (line 22) | def test_init_with_provided_client(self):
method test_init_without_client (line 32) | def test_init_without_client(self, mock_boto3_client):
method test_init_with_env_region (line 55) | def test_init_with_env_region(self, mock_boto3_client):
method test_default_flow_input_encoder (line 75) | def test_default_flow_input_encoder(self):
method test_default_flow_output_decoder (line 94) | def test_default_flow_output_decoder(self):
method test_custom_encoders_decoders (line 105) | def test_custom_encoders_decoders(self):
method test_process_request_success (line 132) | async def test_process_request_success(self):
method test_process_request_no_response_stream (line 177) | async def test_process_request_no_response_stream(self):
method test_process_request_empty_event_stream (line 192) | async def test_process_request_empty_event_stream(self):
method test_process_request_multiple_events (line 213) | async def test_process_request_multiple_events(self):
method test_process_request_boto3_exception (line 255) | async def test_process_request_boto3_exception(self):
method test_process_request_generic_exception (line 275) | async def test_process_request_generic_exception(self):
method test_process_request_with_trace_disabled (line 290) | async def test_process_request_with_trace_disabled(self):
FILE: python/src/tests/agents/test_bedrock_inline_agent.py
class TestBedrockInlineAgent (line 9) | class TestBedrockInlineAgent(unittest.IsolatedAsyncioTestCase):
method asyncSetUp (line 10) | async def asyncSetUp(self):
method test_initialization (line 50) | async def test_initialization(self):
method test_process_request_without_tool_use (line 58) | async def test_process_request_without_tool_use(self):
method test_process_request_with_tool_use (line 88) | async def test_process_request_with_tool_use(self):
method test_error_handling (line 145) | async def test_error_handling(self):
method test_system_prompt_formatting (line 165) | async def test_system_prompt_formatting(self):
method test_inline_agent_tool_handler (line 178) | async def test_inline_agent_tool_handler(self):
method test_custom_prompt_template (line 217) | async def test_custom_prompt_template(self):
FILE: python/src/tests/agents/test_bedrock_llm_agent.py
function mock_boto3_client (line 16) | def mock_boto3_client():
function bedrock_llm_agent (line 21) | def bedrock_llm_agent(mock_boto3_client):
function test_no_region_init (line 51) | def test_no_region_init(bedrock_llm_agent, mock_boto3_client):
function test_custom_system_prompt_with_variable (line 64) | def test_custom_system_prompt_with_variable(bedrock_llm_agent, mock_boto...
function test_custom_system_prompt_with_wrong_variable (line 78) | def test_custom_system_prompt_with_wrong_variable(bedrock_llm_agent, moc...
function test_process_request_single_response (line 93) | async def test_process_request_single_response(bedrock_llm_agent, mock_b...
function test_agent_tracking_info_propagation (line 116) | async def test_agent_tracking_info_propagation(bedrock_llm_agent, mock_b...
function test_agent_tracking_info_streaming (line 166) | async def test_agent_tracking_info_streaming(bedrock_llm_agent, mock_bot...
function test_process_request_streaming (line 229) | async def test_process_request_streaming(bedrock_llm_agent, mock_boto3_c...
function test_process_request_with_tool_use (line 261) | async def test_process_request_with_tool_use(bedrock_llm_agent, mock_bot...
function test_set_system_prompt (line 304) | def test_set_system_prompt(bedrock_llm_agent):
function test_streaming (line 314) | def test_streaming(mock_boto3_client):
function test_prepare_system_prompt_with_retriever (line 355) | async def test_prepare_system_prompt_with_retriever(bedrock_llm_agent):
function test_prepare_tool_config_with_agent_tools (line 370) | def test_prepare_tool_config_with_agent_tools(bedrock_llm_agent):
function test_prepare_tool_config_with_agent_tool_list (line 385) | def test_prepare_tool_config_with_agent_tool_list(bedrock_llm_agent):
function test_prepare_tool_config_with_invalid_config (line 403) | def test_prepare_tool_config_with_invalid_config(bedrock_llm_agent):
function test_handle_single_response_error (line 413) | async def test_handle_single_response_error(bedrock_llm_agent, mock_boto...
function test_handle_streaming_response_error (line 422) | async def test_handle_streaming_response_error(bedrock_llm_agent, mock_b...
function test_process_tool_block_with_agent_tools (line 433) | async def test_process_tool_block_with_agent_tools(bedrock_llm_agent):
function test_process_tool_block_with_invalid_tool (line 461) | async def test_process_tool_block_with_invalid_tool(bedrock_llm_agent):
function test_handle_streaming_with_tool_use (line 477) | async def test_handle_streaming_with_tool_use(bedrock_llm_agent, mock_bo...
function test_handle_single_response_no_output (line 543) | async def test_handle_single_response_no_output(bedrock_llm_agent, mock_...
function test_handle_streaming_with_text_response (line 552) | async def test_handle_streaming_with_text_response(bedrock_llm_agent, mo...
function test_handle_streaming_response_no_output (line 593) | async def test_handle_streaming_response_no_output(bedrock_llm_agent, mo...
function test_handle_streaming_with_metadata (line 619) | async def test_handle_streaming_with_metadata(bedrock_llm_agent, mock_bo...
function test_get_max_recursions (line 654) | async def test_get_max_recursions(bedrock_llm_agent):
function test_update_system_prompt (line 668) | def test_update_system_prompt(bedrock_llm_agent):
function test_prepare_conversation (line 684) | def test_prepare_conversation(bedrock_llm_agent):
function test_build_conversation_command (line 710) | def test_build_conversation_command(bedrock_llm_agent):
function client_fixture (line 757) | def client_fixture():
function test_client_provided (line 762) | def test_client_provided(client_fixture):
function test_additional_model_request_fields (line 774) | def test_additional_model_request_fields(mock_boto3_client):
FILE: python/src/tests/agents/test_comprehend_agent.py
class TestComprehendFilterAgent (line 8) | class TestComprehendFilterAgent(unittest.IsolatedAsyncioTestCase):
method asyncSetUp (line 9) | async def asyncSetUp(self):
method test_initialization (line 43) | async def test_initialization(self):
method test_process_clean_content (line 52) | async def test_process_clean_content(self):
method test_negative_sentiment_blocking (line 68) | async def test_negative_sentiment_blocking(self):
method test_pii_detection_blocking (line 91) | async def test_pii_detection_blocking(self):
method test_toxic_content_blocking (line 111) | async def test_toxic_content_blocking(self):
method test_custom_check (line 132) | async def test_custom_check(self):
method test_language_code_validation (line 150) | async def test_language_code_validation(self):
method test_allow_pii_configuration (line 160) | async def test_allow_pii_configuration(self):
method test_error_handling (line 189) | async def test_error_handling(self):
method test_threshold_configuration (line 204) | async def test_threshold_configuration(self):
FILE: python/src/tests/agents/test_lambda_agent.py
function custom_payload_decoder (line 9) | def custom_payload_decoder(payload):
function lambda_agent_options (line 16) | def lambda_agent_options():
function mock_boto3_client (line 25) | def mock_boto3_client():
function lambda_agent (line 30) | def lambda_agent(lambda_agent_options, mock_boto3_client):
function test_init (line 33) | def test_init(lambda_agent, lambda_agent_options, mock_boto3_client):
function test_default_input_payload_encoder (line 39) | def test_default_input_payload_encoder(lambda_agent):
function test_default_output_payload_decoder (line 59) | def test_default_output_payload_decoder(lambda_agent):
function test_process_request (line 75) | async def test_process_request(mock_boto3_client):
function test_custom_encoder_decoder (line 136) | def test_custom_encoder_decoder(lambda_agent_options, mock_boto3_client):
FILE: python/src/tests/agents/test_lex_bot_agent.py
function lex_bot_options (line 9) | def lex_bot_options():
function mock_lex_client (line 20) | def mock_lex_client():
function lex_bot_agent (line 25) | def lex_bot_agent(lex_bot_options, mock_lex_client):
function test_lex_bot_agent_initialization (line 28) | def test_lex_bot_agent_initialization(lex_bot_options, lex_bot_agent):
function test_lex_bot_agent_initialization_missing_params (line 34) | def test_lex_bot_agent_initialization_missing_params(lex_bot_agent):
function test_process_request_success (line 43) | async def test_process_request_success(lex_bot_agent, mock_lex_client):
function test_process_request_no_response (line 66) | async def test_process_request_no_response(lex_bot_agent, mock_lex_client):
function test_process_request_error (line 78) | async def test_process_request_error(lex_bot_agent, mock_lex_client):
function test_process_request_client_error (line 87) | async def test_process_request_client_error(lex_bot_agent, mock_lex_clie...
FILE: python/src/tests/agents/test_openai_agent.py
function mock_openai_client (line 8) | def mock_openai_client():
function openai_agent (line 18) | def openai_agent(mock_openai_client):
function test_custom_system_prompt_with_variable (line 38) | def test_custom_system_prompt_with_variable():
function test_process_request_success (line 54) | async def test_process_request_success(openai_agent, mock_openai_client):
function test_process_request_streaming (line 75) | async def test_process_request_streaming(openai_agent, mock_openai_client):
function test_process_request_with_retriever (line 115) | async def test_process_request_with_retriever(openai_agent, mock_openai_...
function test_process_request_api_error (line 141) | async def test_process_request_api_error(openai_agent, mock_openai_client):
function test_handle_single_response_no_choices (line 155) | async def test_handle_single_response_no_choices(openai_agent, mock_open...
function test_is_streaming_enabled (line 169) | def test_is_streaming_enabled(openai_agent):
FILE: python/src/tests/agents/test_strands_agent.py
function mock_model (line 20) | def mock_model():
function mock_mcp_client (line 28) | def mock_mcp_client():
function mock_strands_agent (line 36) | def mock_strands_agent():
function agent_options (line 45) | def agent_options():
function conversation_messages (line 51) | def conversation_messages():
function mock_callbacks (line 66) | def mock_callbacks():
class TestStrandsAgent (line 77) | class TestStrandsAgent:
method test_init_basic (line 80) | def test_init_basic(self, agent_options, mock_model, mock_strands_agent):
method test_init_with_mcp_clients (line 95) | def test_init_with_mcp_clients(self, agent_options, mock_model, mock_m...
method test_init_with_tools (line 110) | def test_init_with_tools(self, agent_options, mock_model, mock_strands...
method test_init_mcp_client_error (line 122) | def test_init_mcp_client_error(self, agent_options, mock_model):
method test_del_with_mcp_clients (line 135) | def test_del_with_mcp_clients(self, mock_logger, agent_options, mock_m...
method test_del_with_mcp_clients_error (line 151) | def test_del_with_mcp_clients_error(self, mock_logger, agent_options, ...
method test_is_streaming_enabled (line 167) | def test_is_streaming_enabled(self, agent_options, mock_model, mock_st...
method test_convert_chat_history_to_strands_format (line 179) | def test_convert_chat_history_to_strands_format(self, agent_options, m...
method test_convert_chat_history_with_different_content_types (line 191) | def test_convert_chat_history_with_different_content_types(self, agent...
method test_convert_chat_history_with_empty_content (line 209) | def test_convert_chat_history_with_empty_content(self, agent_options, ...
method test_convert_chat_history_with_complex_nested_content (line 231) | def test_convert_chat_history_with_complex_nested_content(self, agent_...
method test_convert_strands_result_to_conversation_message (line 254) | def test_convert_strands_result_to_conversation_message(self, agent_op...
method test_convert_strands_result_with_multiple_content_blocks (line 268) | def test_convert_strands_result_with_multiple_content_blocks(self, age...
method test_convert_strands_result_with_empty_content (line 285) | def test_convert_strands_result_with_empty_content(self, agent_options...
method test_convert_strands_result_with_mixed_content_types (line 299) | def test_convert_strands_result_with_mixed_content_types(self, agent_o...
method test_convert_strands_result_with_tool_use (line 317) | def test_convert_strands_result_with_tool_use(self, agent_options, moc...
method test_prepare_conversation (line 335) | def test_prepare_conversation(self, agent_options, mock_model, convers...
method test_handle_streaming_response (line 347) | async def test_handle_streaming_response(self, agent_options, mock_mod...
method test_handle_streaming_response_error (line 386) | async def test_handle_streaming_response_error(self, agent_options, mo...
method test_handle_single_response (line 408) | async def test_handle_single_response(self, agent_options, mock_model,...
method test_handle_single_response_error (line 448) | async def test_handle_single_response_error(self, agent_options, mock_...
method test_process_with_strategy_streaming (line 468) | async def test_process_with_strategy_streaming(self, agent_options, mo...
method test_process_with_strategy_non_streaming (line 505) | async def test_process_with_strategy_non_streaming(self, agent_options...
method test_process_request_streaming (line 533) | async def test_process_request_streaming(self, agent_options, mock_mod...
method test_process_request_non_streaming (line 566) | async def test_process_request_non_streaming(self, agent_options, mock...
method test_process_request_error (line 602) | async def test_process_request_error(self, agent_options, mock_model, ...
method _async_generator (line 622) | async def _async_generator(items):
method test_handle_streaming_response_with_malformed_events (line 627) | async def test_handle_streaming_response_with_malformed_events(self, a...
method test_handle_streaming_response_with_network_interruption (line 656) | async def test_handle_streaming_response_with_network_interruption(sel...
method test_process_request_with_invalid_chat_history (line 679) | async def test_process_request_with_invalid_chat_history(self, agent_o...
FILE: python/src/tests/agents/test_supervisor_agent.py
function mock_boto3_client (line 19) | def mock_boto3_client():
function mock_storage (line 23) | def mock_storage():
class MockBedrockLLMAgent (line 49) | class MockBedrockLLMAgent(BedrockLLMAgent):
method process_request (line 50) | async def process_request(self, *args, **kwargs):
function supervisor_agent (line 59) | def supervisor_agent(mock_boto3_client):
function test_supervisor_agent_initialization (line 80) | async def test_supervisor_agent_initialization(mock_boto3_client):
function test_supervisor_agent_validation (line 106) | async def test_supervisor_agent_validation(mock_boto3_client):
function test_send_message (line 130) | def test_send_message(supervisor_agent, mock_boto3_client):
function test_send_messages (line 149) | async def test_send_messages(supervisor_agent):
function test_process_request (line 164) | async def test_process_request(supervisor_agent):
function test_format_agents_memory (line 183) | async def test_format_agents_memory(supervisor_agent):
function test_supervisor_agent_with_custom_tools (line 201) | async def test_supervisor_agent_with_custom_tools(mock_boto3_client):
function test_supervisor_agent_with_custom_tools_ (line 236) | async def test_supervisor_agent_with_custom_tools_(mock_boto3_client):
function test_supervisor_agent_with_extra_tools (line 272) | async def test_supervisor_agent_with_extra_tools(mock_boto3_client):
function test_supervisor_agent_error_handling (line 302) | async def test_supervisor_agent_error_handling(mock_boto3_client):
function test_supervisor_agent_parallel_processing (line 329) | async def test_supervisor_agent_parallel_processing(mock_boto3_client):
function test_supervisor_agent_memory_management (line 367) | async def test_supervisor_agent_memory_management(mock_boto3_client):
FILE: python/src/tests/classifiers/test_anthropic_classifier.py
class MockAgent (line 9) | class MockAgent(Agent):
method __init__ (line 11) | def __init__(self, agent_id, description="Test agent"):
method process_request (line 22) | async def process_request(self, input_text, user_id, session_id, chat_...
class TestAnthropicClassifierOptions (line 26) | class TestAnthropicClassifierOptions:
method test_init_with_required_params (line 28) | def test_init_with_required_params(self):
method test_init_with_all_params (line 37) | def test_init_with_all_params(self):
class TestAnthropicClassifier (line 60) | class TestAnthropicClassifier:
method setup_method (line 62) | def setup_method(self):
method test_init_with_valid_api_key (line 71) | def test_init_with_valid_api_key(self, mock_anthropic):
method test_init_without_api_key (line 83) | def test_init_without_api_key(self):
method test_init_with_none_api_key (line 90) | def test_init_with_none_api_key(self):
method test_init_with_custom_model_id (line 98) | def test_init_with_custom_model_id(self, mock_anthropic):
method test_init_with_custom_inference_config (line 109) | def test_init_with_custom_inference_config(self, mock_anthropic):
method test_init_with_partial_inference_config (line 130) | def test_init_with_partial_inference_config(self, mock_anthropic):
method test_tools_configuration (line 146) | def test_tools_configuration(self, mock_anthropic):
method test_process_request_success (line 171) | async def test_process_request_success(self, mock_anthropic):
method test_process_request_no_tool_use (line 218) | async def test_process_request_no_tool_use(self, mock_anthropic):
method test_process_request_invalid_tool_input (line 240) | async def test_process_request_invalid_tool_input(self, mock_is_tool_i...
method test_process_request_api_exception (line 266) | async def test_process_request_api_exception(self, mock_anthropic):
method test_process_request_with_callbacks (line 280) | async def test_process_request_with_callbacks(self, mock_anthropic):
method test_process_request_with_empty_chat_history (line 328) | async def test_process_request_with_empty_chat_history(self, mock_anth...
method test_process_request_agent_not_found (line 358) | async def test_process_request_agent_not_found(self, mock_anthropic):
method test_process_request_with_custom_inference_config (line 388) | async def test_process_request_with_custom_inference_config(self, mock...
method test_process_request_confidence_as_float (line 432) | async def test_process_request_confidence_as_float(self, mock_anthropic):
FILE: python/src/tests/classifiers/test_classifier.py
class MockAgent (line 11) | class MockAgent(Agent):
method __init__ (line 12) | def __init__(self, agent_id, description):
method process_request (line 16) | async def process_request(
class ConcreteClassifier (line 26) | class ConcreteClassifier(Classifier):
method process_request (line 27) | async def process_request(self, input_text, chat_history):
class TestClassifier (line 34) | class TestClassifier(unittest.TestCase):
method setUp (line 35) | def setUp(self):
method test_set_agents (line 46) | def test_set_agents(self):
method test_format_messages (line 56) | def test_format_messages(self):
method test_get_agent_by_id (line 66) | def test_get_agent_by_id(self):
method test_get_agent_by_id_not_found (line 77) | def test_get_agent_by_id_not_found(self):
method test_replace_placeholders (line 85) | def test_replace_placeholders(self):
method test_replace_placeholders_with_list (line 96) | def test_replace_placeholders_with_list(self):
method test_replace_placeholders_missing_key (line 106) | def test_replace_placeholders_missing_key(self):
method test_classify (line 115) | def test_classify(self):
method _async_test_classify (line 124) | async def _async_test_classify(self):
method test_update_system_prompt (line 132) | def test_update_system_prompt(self):
FILE: python/src/tests/retrievers/test_retriever.py
class ConcreteRetriever (line 7) | class ConcreteRetriever(Retriever):
method retrieve (line 10) | async def retrieve(self, text: str) -> str:
method retrieve_and_combine_results (line 13) | async def retrieve_and_combine_results(self, text: str) -> str:
method retrieve_and_generate (line 16) | async def retrieve_and_generate(self, text: str) -> str:
function retriever (line 20) | def retriever():
function test_retrieve (line 25) | async def test_retrieve(retriever):
function test_retrieve_and_combine_results (line 30) | async def test_retrieve_and_combine_results(retriever):
function test_retrieve_and_generate (line 35) | async def test_retrieve_and_generate(retriever):
function test_init (line 39) | def test_init():
function test_abstract_class (line 44) | def test_abstract_class():
function test_abstract_methods (line 49) | async def test_abstract_methods():
FILE: python/src/tests/storage/test_chat_storage.py
class MockChatStorage (line 6) | class MockChatStorage(ChatStorage):
method save_chat_message (line 7) | async def save_chat_message(self, user_id: str, session_id: str, agent...
method save_chat_messages (line 11) | async def save_chat_messages(self, user_id: str, session_id: str, agen...
method fetch_chat (line 14) | async def fetch_chat(self, user_id: str, session_id: str, agent_id: st...
method fetch_all_chats (line 17) | async def fetch_all_chats(self, user_id: str, session_id: str) -> list...
function chat_storage (line 21) | def chat_storage():
function test_is_same_role_as_last_message (line 24) | def test_is_same_role_as_last_message(chat_storage):
function test_trim_conversation (line 41) | def test_trim_conversation(chat_storage):
function test_save_chat_message (line 73) | async def test_save_chat_message(chat_storage):
function test_save_chat_messages (line 84) | async def test_save_chat_messages(chat_storage):
function test_fetch_chat (line 108) | async def test_fetch_chat(chat_storage):
function test_fetch_all_chats (line 118) | async def test_fetch_all_chats(chat_storage):
FILE: python/src/tests/storage/test_dynamodb_chat_storage.py
function dynamodb_table (line 9) | def dynamodb_table():
function chat_storage (line 27) | def chat_storage(dynamodb_table):
function test_save_and_fetch_chat_message (line 31) | async def test_save_and_fetch_chat_message(chat_storage):
function test_fetch_chat_with_timestamp (line 50) | async def test_fetch_chat_with_timestamp(chat_storage):
function test_fetch_all_chats (line 66) | async def test_fetch_all_chats(chat_storage):
function test_consecutive_message_handling (line 83) | async def test_consecutive_message_handling(chat_storage):
function test_trim_conversation (line 98) | async def test_trim_conversation(chat_storage):
function test_save_and_fetch_chat_messages (line 117) | async def test_save_and_fetch_chat_messages(chat_storage):
function test_save_and_fetch_chat_messages_timestamp (line 148) | async def test_save_and_fetch_chat_messages_timestamp(chat_storage):
FILE: python/src/tests/storage/test_in_memory_chat_storage.py
function mock_logger (line 10) | def mock_logger():
function storage (line 16) | def storage(mock_logger):
function test_save_chat_message (line 20) | async def test_save_chat_message(storage):
function test_save_consecutive_message (line 33) | async def test_save_consecutive_message(storage):
function test_fetch_chat (line 47) | async def test_fetch_chat(storage):
function test_fetch_all_chats (line 61) | async def test_fetch_all_chats(storage):
function test_fetch_all_chats (line 79) | async def test_fetch_all_chats(storage):
function test_trim_conversation (line 96) | async def test_trim_conversation(storage):
function test_generate_key (line 113) | def test_generate_key():
function test_remove_timestamps (line 117) | def test_remove_timestamps():
function test_save_chat_messages (line 132) | async def test_save_chat_messages(storage):
function test_save_chat_messages_timestamp (line 150) | async def test_save_chat_messages_timestamp(storage):
FILE: python/src/tests/storage/test_sql_chat_storage.py
function sql_storage (line 12) | async def sql_storage():
function test_save_and_fetch_message (line 26) | async def test_save_and_fetch_message(sql_storage: SqlChatStorage):
function test_save_consecutive_same_role_messages (line 55) | async def test_save_consecutive_same_role_messages(sql_storage: SqlChatS...
function test_max_history_size (line 96) | async def test_max_history_size(sql_storage: SqlChatStorage):
function test_save_multiple_messages (line 125) | async def test_save_multiple_messages(sql_storage: SqlChatStorage):
function test_fetch_all_chats (line 156) | async def test_fetch_all_chats(sql_storage: SqlChatStorage):
function test_multiple_users_and_sessions (line 184) | async def test_multiple_users_and_sessions(sql_storage: SqlChatStorage):
function test_empty_fetch (line 216) | async def test_empty_fetch(sql_storage: SqlChatStorage):
function test_save_empty_batch (line 232) | async def test_save_empty_batch(sql_storage: SqlChatStorage):
function test_message_ordering (line 243) | async def test_message_ordering(sql_storage: SqlChatStorage):
function test_invalid_database_url (line 278) | async def test_invalid_database_url():
function test_concurrent_access (line 285) | async def test_concurrent_access(sql_storage: SqlChatStorage):
function test_transaction_rollback (line 315) | async def test_transaction_rollback(sql_storage: SqlChatStorage):
function test_database_connection_handling (line 346) | async def test_database_connection_handling():
FILE: python/src/tests/test_orchestrator.py
function mock_boto3_client (line 25) | def mock_boto3_client():
function mock_logger (line 31) | def mock_logger():
function mock_storage (line 35) | def mock_storage():
function mock_classifier (line 43) | def mock_classifier():
function mock_agent (line 49) | def mock_agent():
function mock_streaming_agent (line 59) | def mock_streaming_agent():
function orchestrator (line 69) | def orchestrator(mock_storage, mock_classifier, mock_logger, mock_agent,...
function test_init_with_dict_options (line 77) | def test_init_with_dict_options(mock_boto3_client):
function test_init_with_invalid_options (line 85) | def test_init_with_invalid_options(mock_boto3_client):
function test_add_agent (line 90) | def test_add_agent(orchestrator, mock_agent):
function test_add_duplicate_agent (line 95) | def test_add_duplicate_agent(orchestrator, mock_agent):
function test_get_all_agents (line 100) | def test_get_all_agents(orchestrator, mock_agent):
function test_get_default_agent (line 107) | def test_get_default_agent(orchestrator, mock_agent):
function test_set_default_agent (line 110) | def test_set_default_agent(orchestrator, mock_agent):
function test_classify_request_success (line 117) | async def test_classify_request_success(orchestrator, mock_agent):
function test_classify_request_no_agent_with_default (line 125) | async def test_classify_request_no_agent_with_default(orchestrator):
function test_classify_request_error (line 133) | async def test_classify_request_error(orchestrator):
function test_dispatch_to_agent_success (line 141) | async def test_dispatch_to_agent_success(orchestrator, mock_agent):
function test_dispatch_to_agent_no_agent (line 160) | async def test_dispatch_to_agent_no_agent(orchestrator):
function test_agent_process_request_streaming (line 176) | async def test_agent_process_request_streaming(orchestrator, mock_stream...
function test_route_request_success (line 203) | async def test_route_request_success(orchestrator, mock_agent):
function test_route_request_error (line 223) | async def test_route_request_error(orchestrator):
function test_save_message (line 237) | async def test_save_message(orchestrator, mock_agent):
function test_save_messages (line 259) | async def test_save_messages(orchestrator, mock_agent):
function test_measure_execution_time (line 282) | async def test_measure_execution_time(orchestrator):
function test_measure_execution_time_error (line 294) | async def test_measure_execution_time_error(orchestrator):
function test_create_metadata (line 307) | def test_create_metadata(orchestrator, mock_agent):
function test_create_metadata_no_agent (line 325) | def test_create_metadata_no_agent(orchestrator):
function test_get_fallback_result (line 340) | def test_get_fallback_result(orchestrator, mock_agent):
FILE: python/src/tests/utils/test_helpers.py
function test_is_tool_input (line 9) | def test_is_tool_input():
function test_conversation_to_dict (line 25) | def test_conversation_to_dict():
FILE: python/src/tests/utils/test_logger.py
function logger_instance (line 8) | def logger_instance():
function mock_logger (line 12) | def mock_logger(mocker):
function test_logger_initialization (line 15) | def test_logger_initialization():
function test_logger_initialization_with_custom_config (line 20) | def test_logger_initialization_with_custom_config():
function test_set_logger (line 25) | def test_set_logger(mock_logger):
function test_log_methods (line 30) | def test_log_methods(mock_logger, log_method):
function test_log_header (line 36) | def test_log_header(mock_logger):
function test_print_chat_history_agent (line 42) | def test_print_chat_history_agent(logger_instance, mock_logger, mocker):
function test_not_print_chat_history_agent (line 52) | def test_not_print_chat_history_agent(logger_instance, mock_logger, mock...
function test_print_chat_history_classifier (line 62) | def test_print_chat_history_classifier(logger_instance, mock_logger, moc...
function test_not_print_chat_history_classifier (line 72) | def test_not_print_chat_history_classifier(logger_instance, mock_logger,...
function test_log_classifier_output (line 82) | def test_log_classifier_output(logger_instance, mock_logger):
function test_not_log_classifier_output (line 90) | def test_not_log_classifier_output(logger_instance, mock_logger):
function test_print_execution_times (line 97) | def test_print_execution_times(logger_instance, mock_logger):
function test_log_methods_with_args (line 104) | def test_log_methods_with_args(mock_logger):
function test_print_chat_history_empty (line 109) | def test_print_chat_history_empty(logger_instance, mock_logger):
function test_print_execution_times_empty (line 116) | def test_print_execution_times_empty(logger_instance, mock_logger):
function test_not_print_execution_times_empty (line 122) | def test_not_print_execution_times_empty(logger_instance, mock_logger):
FILE: python/src/tests/utils/test_tool.py
function _tool_hanlder (line 7) | def _tool_hanlder(input: str) -> str:
function fetch_weather_data (line 18) | async def fetch_weather_data(latitude:str, longitude:str):
function test_tools_without_description (line 32) | def test_tools_without_description():
function test_tools_with_description (line 44) | def test_tools_with_description():
function test_tools_format (line 108) | def test_tools_format():
function test_tool_handler_bedrock (line 186) | async def test_tool_handler_bedrock():
function test_tool_handler_anthropic (line 232) | async def test_tool_handler_anthropic():
function test_tools_format (line 263) | def test_tools_format():
function tool_with_enums (line 354) | def tool_with_enums(latitude:str, longitude:str, units:str):
function test_tool_with_enums (line 370) | def test_tool_with_enums():
function test_tool_with_properties (line 407) | def test_tool_with_properties():
function test_tool_not_found (line 475) | async def test_tool_not_found():
function test_get_tool_use_block (line 486) | def test_get_tool_use_block():
function test_no_func (line 495) | def test_no_func():
function test_no_tool_block (line 504) | async def test_no_tool_block():
function test_no_tool_use_block (line 516) | async def test_no_tool_use_block():
function test_self_param (line 528) | def test_self_param():
FILE: typescript/src/agentOverlapAnalyzer.ts
type OverlapResult (line 5) | interface OverlapResult {
type UniquenessScore (line 10) | interface UniquenessScore {
type AnalysisResult (line 15) | interface AnalysisResult {
class AgentOverlapAnalyzer (line 20) | class AgentOverlapAnalyzer {
method constructor (line 23) | constructor(agents: {
method analyzeOverlap (line 29) | analyzeOverlap(): void {
method calculateCosineSimilarity (line 118) | private calculateCosineSimilarity(
FILE: typescript/src/agents/agent.ts
type AgentProcessingResult (line 5) | interface AgentProcessingResult {
type AgentResponse (line 32) | type AgentResponse = {
class AgentCallbacks (line 39) | class AgentCallbacks {
method onAgentStart (line 45) | async onAgentStart(
method onAgentEnd (line 72) | async onAgentEnd(
method onLlmStart (line 99) | async onLlmStart(
method onLlmNewToken (line 124) | async onLlmNewToken(_token: string, ..._kwargs: any[]): Promise<void> {
method onLlmEnd (line 134) | async onLlmEnd(
type AgentOptions (line 160) | interface AgentOptions {
method constructor (line 208) | constructor(options: AgentOptions) {
method generateKeyFromName (line 230) | private generateKeyFromName(name: string): string {
method logDebug (line 244) | protected logDebug(className: string, message: string, data?: any): void {
FILE: typescript/src/agents/amazonBedrockAgent.ts
type AmazonBedrockAgentOptions (line 11) | interface AmazonBedrockAgentOptions extends AgentOptions {
class AmazonBedrockAgent (line 25) | class AmazonBedrockAgent extends Agent {
method constructor (line 37) | constructor(options: AmazonBedrockAgentOptions) {
method handleStreamingResponse (line 49) | private async *handleStreamingResponse(response: InvokeAgentCommandOut...
method processRequest (line 73) | async processRequest(
FILE: typescript/src/agents/anthropicAgent.ts
type AnthropicAgentOptions (line 14) | interface AnthropicAgentOptions extends AgentOptions {
type WithApiKey (line 52) | type WithApiKey = {
type WithClient (line 57) | type WithClient = {
type AnthropicAgentOptionsWithAuth (line 62) | type AnthropicAgentOptionsWithAuth = AnthropicAgentOptions &
class AnthropicAgent (line 65) | class AnthropicAgent extends Agent {
method constructor (line 97) | constructor(options: AnthropicAgentOptionsWithAuth) {
method isAgentTools (line 160) | private isAgentTools(
method formatTools (line 173) | private formatTools(tools: AgentTools): any[] {
method formatToolResults (line 190) | private formatToolResults(
method getToolName (line 215) | private getToolName(toolUseBlock: any): string {
method getToolId (line 226) | private getToolId(toolUseBlock: any): string {
method getInputData (line 238) | private getInputData(toolUseBlock: any): any {
method getToolUseBlock (line 249) | private getToolUseBlock(block: any): any {
method processRequest (line 254) | async processRequest(
method handleSingleResponse (line 384) | protected async handleSingleResponse(input: any): Promise<Anthropic.Me...
method handleStreamingResponse (line 394) | private async *handleStreamingResponse(
method setSystemPrompt (line 497) | setSystemPrompt(template?: string, variables?: TemplateVariables): void {
method updateSystemPrompt (line 509) | private updateSystemPrompt(): void {
method replaceplaceholders (line 520) | private replaceplaceholders(
FILE: typescript/src/agents/bedrockFlowsAgent.ts
type BedrockFlowsAgentOptions (line 9) | interface BedrockFlowsAgentOptions extends AgentOptions {
class BedrockFlowsAgent (line 19) | class BedrockFlowsAgent extends Agent {
method constructor (line 29) | constructor(options: BedrockFlowsAgentOptions) {
method defaultFlowInputEncoder (line 56) | defaultFlowInputEncoder(agent: Agent, inputText: string, ..._kwargs: a...
method defaultFlowOutputDecoder (line 60) | defaultFlowOutputDecoder(agent: Agent, response: any): ConversationMes...
method processRequest (line 67) | async processRequest(
FILE: typescript/src/agents/bedrockInlineAgent.ts
type BedrockInlineAgentOptions (line 16) | interface BedrockInlineAgentOptions extends AgentOptions {
class BedrockInlineAgent (line 38) | class BedrockInlineAgent extends Agent {
method constructor (line 101) | constructor(options: BedrockInlineAgentOptions) {
method inlineAgentToolHandler (line 207) | private async inlineAgentToolHandler(
method processRequest (line 307) | async processRequest(
method setSystemPrompt (line 381) | setSystemPrompt(template?: string, variables?: TemplateVariables): void {
method updateSystemPrompt (line 391) | private updateSystemPrompt(): void {
method replaceplaceholders (line 398) | private replaceplaceholders(template: string, variables: TemplateVaria...
FILE: typescript/src/agents/bedrockLLMAgent.ts
type BedrockLLMAgentOptions (line 20) | interface BedrockLLMAgentOptions extends AgentOptions {
class BedrockLLMAgent (line 58) | class BedrockLLMAgent extends Agent {
method constructor (line 112) | constructor(options: BedrockLLMAgentOptions) {
method isAgentTools (line 167) | private isAgentTools(tool: AgentTools | Tool[]): tool is AgentTools {
method formatToolResults (line 178) | private formatToolResults(
method formatTools (line 203) | private formatTools(tools: AgentTools): any[] {
method getToolName (line 226) | private getToolName(toolUseBlock: any): string {
method getToolId (line 237) | private getToolId(toolUseBlock: any): string {
method getInputData (line 248) | private getInputData(toolUseBlock: any): any {
method getToolUseBlock (line 259) | private getToolUseBlock(block: any): any {
method processRequest (line 273) | async processRequest(
method handleSingleResponse (line 402) | protected async handleSingleResponse(
method handleStreamingResponse (line 419) | private async *handleStreamingResponse(input: any): AsyncIterable<stri...
method setSystemPrompt (line 512) | setSystemPrompt(template?: string, variables?: TemplateVariables): void {
method updateSystemPrompt (line 524) | private updateSystemPrompt(): void {
method replaceplaceholders (line 537) | private replaceplaceholders(
FILE: typescript/src/agents/bedrockTranslatorAgent.ts
type BedrockTranslatorAgentOptions (line 6) | interface BedrockTranslatorAgentOptions extends AgentOptions {
type ToolInput (line 19) | interface ToolInput {
function isToolInput (line 23) | function isToolInput(input: unknown): input is ToolInput {
class BedrockTranslatorAgent (line 31) | class BedrockTranslatorAgent extends Agent {
method constructor (line 64) | constructor(options: BedrockTranslatorAgentOptions) {
method processRequest (line 83) | async processRequest(
method setSourceLanguage (line 172) | setSourceLanguage(language: string | undefined): void {
method setTargetLanguage (line 176) | setTargetLanguage(language: string): void {
FILE: typescript/src/agents/chainAgent.ts
type ChainAgentOptions (line 5) | interface ChainAgentOptions extends AgentOptions {
class ChainAgent (line 10) | class ChainAgent extends Agent {
method constructor (line 14) | constructor(options: ChainAgentOptions) {
method processRequest (line 34) | async processRequest(
method isAsyncIterable (line 96) | private isAsyncIterable(obj: any): obj is AsyncIterable<any> {
method isConversationMessage (line 101) | private isConversationMessage(response: any): response is Conversation...
method createDefaultResponse (line 105) | private createDefaultResponse(): ConversationMessage {
FILE: typescript/src/agents/comprehendFilterAgent.ts
type ToxicContent (line 16) | interface ToxicContent {
type ToxicLabels (line 22) | interface ToxicLabels {
type CheckFunction (line 28) | type CheckFunction = (input: string) => Promise<string | null>;
type ComprehendFilterAgentOptions (line 31) | interface ComprehendFilterAgentOptions extends AgentOptions {
class ComprehendFilterAgent (line 49) | class ComprehendFilterAgent extends Agent {
method constructor (line 65) | constructor(options: ComprehendFilterAgentOptions) {
method processRequest (line 99) | async processRequest(
method addCustomCheck (line 159) | addCustomCheck(check: CheckFunction) {
method checkSentiment (line 168) | private checkSentiment(result: DetectSentimentCommandOutput): string |...
method checkPii (line 181) | private checkPii(result: DetectPiiEntitiesCommandOutput): string | null {
method checkToxicity (line 193) | private checkToxicity(result: DetectToxicContentCommandOutput): string...
method detectSentiment (line 205) | private async detectSentiment(text: string) {
method detectPiiEntities (line 217) | private async detectPiiEntities(text: string) {
method detectToxicContent (line 229) | private async detectToxicContent(text: string) {
method getToxicLabels (line 242) | private getToxicLabels(toxicityResult: DetectToxicContentCommandOutput...
method setLanguageCode (line 264) | setLanguageCode(languageCode: LanguageCode): void {
method validateLanguageCode (line 278) | private validateLanguageCode(languageCode: LanguageCode | undefined): ...
FILE: typescript/src/agents/lambdaAgent.ts
type LambdaAgentOptions (line 6) | interface LambdaAgentOptions extends AgentOptions {
class LambdaAgent (line 13) | class LambdaAgent extends Agent {
method constructor (line 17) | constructor(options: LambdaAgentOptions) {
method defaultInputPayloadEncoder (line 24) | private defaultInputPayloadEncoder(inputText: string, chatHistory: Con...
method defaultOutputPayloaderDecoder (line 34) | private defaultOutputPayloaderDecoder(response: any): ConversationMess...
method processRequest (line 43) | async processRequest(
FILE: typescript/src/agents/lexBotAgent.ts
type LexBotAgentOptions (line 15) | interface LexBotAgentOptions extends AgentOptions {
class LexBotAgent (line 26) | class LexBotAgent extends Agent {
method constructor (line 36) | constructor(options: LexBotAgentOptions) {
method processRequest (line 61) | async processRequest(
FILE: typescript/src/agents/openAIAgent.ts
type WithApiKey (line 7) | type WithApiKey = {
type WithClient (line 12) | type WithClient = {
type OpenAIAgentOptions (line 17) | interface OpenAIAgentOptions extends AgentOptions {
type OpenAIAgentOptionsWithAuth (line 34) | type OpenAIAgentOptionsWithAuth = OpenAIAgentOptions & (WithApiKey | Wit...
constant DEFAULT_MAX_TOKENS (line 36) | const DEFAULT_MAX_TOKENS = 1000;
class OpenAIAgent (line 38) | class OpenAIAgent extends Agent {
method constructor (line 54) | constructor(options: OpenAIAgentOptionsWithAuth) {
method processRequest (line 110) | async processRequest(
method setSystemPrompt (line 162) | setSystemPrompt(template?: string, variables?: TemplateVariables): void {
method updateSystemPrompt (line 172) | private updateSystemPrompt(): void {
method replaceplaceholders (line 179) | private replaceplaceholders(template: string, variables: TemplateVaria...
method handleSingleResponse (line 189) | private async handleSingleResponse(input: any): Promise<ConversationMe...
method handleStreamingResponse (line 213) | private async *handleStreamingResponse(options: OpenAI.Chat.ChatComple...
FILE: typescript/src/agents/supervisorAgent.ts
type SupervisorAgentOptions (line 10) | interface SupervisorAgentOptions extends AgentOptions{
class SupervisorAgent (line 18) | class SupervisorAgent extends Agent {
method constructor (line 30) | constructor(options: SupervisorAgentOptions) {
method configureSupervisorTools (line 74) | private configureSupervisorTools(extraTools?: AgentTools): void {
method configurePrompt (line 117) | private configurePrompt(): void {
method accumulateStreamResponse (line 170) | private async accumulateStreamResponse(
method sendMessage (line 180) | private async sendMessage(
method sendMessages (line 262) | private async sendMessages(
method formatAgentsMemory (line 291) | private formatAgentsMemory(agentsHistory: ConversationMessage[]): stri...
method processRequest (line 310) | async processRequest(
FILE: typescript/src/classifiers/anthropicClassifier.ts
type AnthropicClassifierOptions (line 11) | interface AnthropicClassifierOptions {
class AnthropicClassifier (line 39) | class AnthropicClassifier extends Classifier {
method constructor (line 76) | constructor(options: AnthropicClassifierOptions) {
method processRequest (line 98) | async processRequest(
FILE: typescript/src/classifiers/bedrockClassifier.ts
type BedrockClassifierOptions (line 20) | interface BedrockClassifierOptions {
class BedrockClassifier (line 52) | class BedrockClassifier extends Classifier{
method constructor (line 97) | constructor(options: Partial<BedrockClassifierOptions> = {}) {
method processRequest (line 125) | async processRequest(
FILE: typescript/src/classifiers/classifier.ts
type ClassifierResult (line 8) | interface ClassifierResult {
class ClassifierCallbacks (line 17) | class ClassifierCallbacks {
method onClassifierStart (line 22) | async onClassifierStart(
method onClassifierStop (line 44) | async onClassifierStop(
method constructor (line 85) | constructor() {
method setAgents (line 173) | setAgents(agents: { [key: string]: Agent }) {
method setHistory (line 181) | setHistory(messages: ConversationMessage[]): void {
method setSystemPrompt (line 185) | setSystemPrompt(template?: string, variables?: TemplateVariables): void {
method formatMessages (line 197) | private formatMessages(messages: ConversationMessage[]): string {
method classify (line 219) | async classify(
method updateSystemPrompt (line 244) | private updateSystemPrompt(): void {
method replaceplaceholders (line 257) | private replaceplaceholders(
method getAgentById (line 273) | protected getAgentById(agentId: string): Agent | null {
FILE: typescript/src/classifiers/openAIClassifier.ts
type OpenAIClassifierOptions (line 10) | interface OpenAIClassifierOptions {
class OpenAIClassifier (line 36) | class OpenAIClassifier extends Classifier {
method constructor (line 74) | constructor(options: OpenAIClassifierOptions) {
method processRequest (line 104) | async processRequest(
FILE: typescript/src/common/src/awsSdkUtils.ts
constant EXEC_ENV (line 4) | const EXEC_ENV = process.env.AWS_EXECUTION_ENV || 'NA';
FILE: typescript/src/common/src/types/awsSdk.ts
type SdkClient (line 6) | interface SdkClient {
type MiddlewareArgsLike (line 22) | type MiddlewareArgsLike = { request: { headers: { [key: string]: string ...
FILE: typescript/src/common/src/version.ts
constant MAOTS_VERSION (line 2) | const MAOTS_VERSION = '1.0.0';
FILE: typescript/src/orchestrator.ts
type AgentSquadConfig (line 12) | interface AgentSquadConfig {
constant DEFAULT_CONFIG (line 90) | const DEFAULT_CONFIG: AgentSquadConfig = {
type DispatchToAgentsParams (line 126) | interface DispatchToAgentsParams {
type OrchestratorOptions (line 150) | interface OrchestratorOptions {
type RequestMetadata (line 158) | interface RequestMetadata {
type ThinkingResponse (line 183) | type ThinkingResponse = {
class AgentSquad (line 188) | class AgentSquad {
method constructor (line 197) | constructor(options: OrchestratorOptions = {}) {
method analyzeAgentOverlap (line 241) | analyzeAgentOverlap(): void {
method addAgent (line 247) | addAgent(agent: Agent): void {
method getDefaultAgent (line 255) | getDefaultAgent(): Agent {
method setDefaultAgent (line 259) | setDefaultAgent(agent: Agent): void {
method getAllAgents (line 263) | getAllAgents(): { [key: string]: { name: string; description: string }...
method isAsyncIterable (line 272) | private isAsyncIterable(obj: any): obj is AsyncIterable<any> {
method dispatchToAgent (line 276) | async dispatchToAgent(
method classifyRequest (line 353) | async classifyRequest(
method agentProcessRequest (line 385) | async agentProcessRequest(
method routeRequest (line 451) | async routeRequest(
method processStreamInBackground (line 504) | private async processStreamInBackground(
method measureExecutionTime (line 558) | private measureExecutionTime<T>(
method createMetadata (line 585) | private createMetadata(
method getFallbackResult (line 615) | private getFallbackResult(): ClassifierResult {
FILE: typescript/src/retrievers/AmazonKBRetriever.ts
type AmazonKnowledgeBasesRetrieverOptions (line 14) | interface AmazonKnowledgeBasesRetrieverOptions {
class AmazonKnowledgeBasesRetriever (line 24) | class AmazonKnowledgeBasesRetriever extends Retriever {
method constructor (line 33) | constructor(client: BedrockAgentRuntimeClient, options: AmazonKnowledg...
method send_command (line 50) | private async send_command(command: any): Promise<any> {
method retrieveAndGenerate (line 65) | public async retrieveAndGenerate(
method retrieve (line 87) | public async retrieve(
method retrieveAndCombineResults (line 112) | public async retrieveAndCombineResults(
method combineRetrievalResults (line 131) | private combineRetrievalResults(retrievalResults: KnowledgeBaseRetriev...
FILE: typescript/src/retrievers/retriever.ts
method constructor (line 14) | constructor(options: any) {
FILE: typescript/src/storage/chatStorage.ts
method isConsecutiveMessage (line 5) | public isConsecutiveMessage(conversation: ConversationMessage[], newMess...
method trimConversation (line 11) | protected trimConversation(conversation: ConversationMessage[], maxHisto...
FILE: typescript/src/storage/dynamoDbChatStorage.ts
class DynamoDbChatStorage (line 14) | class DynamoDbChatStorage extends ChatStorage {
method constructor (line 20) | constructor(tableName: string, region: string, ttlKey?: string, ttlDur...
method saveChatMessage (line 29) | async saveChatMessage(
method fetchChat (line 80) | async fetchChat(
method fetchAllChats (line 101) | async fetchAllChats(userId: string, sessionId: string): Promise<Conver...
method generateKey (line 143) | private generateKey(userId: string, sessionId: string, agentId: string...
method removeTimestamps (line 147) | private removeTimestamps(messages: TimestampedMessage[] | Conversation...
FILE: typescript/src/storage/memoryChatStorage.ts
class InMemoryChatStorage (line 5) | class InMemoryChatStorage extends ChatStorage {
method constructor (line 8) | constructor() {
method saveChatMessage (line 13) | async saveChatMessage(
method fetchChat (line 36) | async fetchChat(
method fetchAllChats (line 50) | async fetchAllChats(
method generateKey (line 72) | private generateKey(userId: string, sessionId: string, agentId: string...
method removeTimestamps (line 76) | private removeTimestamps(messages: TimestampedMessage[]): Conversation...
FILE: typescript/src/storage/sqlChatStorage.ts
class SqlChatStorage (line 6) | class SqlChatStorage extends ChatStorage {
method constructor (line 10) | constructor(url: string, authToken?: string) {
method initializeDatabase (line 19) | private async initializeDatabase() {
method saveChatMessage (line 46) | async saveChatMessage(
method fetchChat (line 132) | async fetchChat(
method fetchAllChats (line 166) | async fetchAllChats(
method waitForInitialization (line 195) | async waitForInitialization() {
method close (line 202) | close() {
FILE: typescript/src/types/index.ts
constant BEDROCK_MODEL_ID_CLAUDE_3_HAIKU (line 1) | const BEDROCK_MODEL_ID_CLAUDE_3_HAIKU = "anthropic.claude-3-haiku-202403...
constant BEDROCK_MODEL_ID_CLAUDE_3_SONNET (line 2) | const BEDROCK_MODEL_ID_CLAUDE_3_SONNET = "anthropic.claude-3-sonnet-2024...
constant BEDROCK_MODEL_ID_CLAUDE_3_5_SONNET (line 3) | const BEDROCK_MODEL_ID_CLAUDE_3_5_SONNET = "anthropic.claude-3-5-sonnet-...
constant BEDROCK_MODEL_ID_LLAMA_3_70B (line 4) | const BEDROCK_MODEL_ID_LLAMA_3_70B = "meta.llama3-70b-instruct-v1:0";
constant OPENAI_MODEL_ID_GPT_O_MINI (line 5) | const OPENAI_MODEL_ID_GPT_O_MINI = "gpt-4o-mini";
constant ANTHROPIC_MODEL_ID_CLAUDE_3_5_SONNET (line 6) | const ANTHROPIC_MODEL_ID_CLAUDE_3_5_SONNET = "claude-3-5-sonnet-20240620";
type AgentTypes (line 13) | type AgentTypes = typeof AgentTypes[keyof typeof AgentTypes];
type ToolInput (line 15) | interface ToolInput {
type StreamingResponse (line 25) | type StreamingResponse = {
type ParticipantRole (line 33) | enum ParticipantRole {
type ConversationMessage (line 41) | interface ConversationMessage {
type TimestampedMessage (line 50) | type TimestampedMessage = ConversationMessage & { timestamp: number };
type TemplateVariables (line 52) | interface TemplateVariables {
type AgentProviderType (line 57) | enum AgentProviderType {
FILE: typescript/src/utils/chatUtils.ts
function saveConversationExchange (line 5) | async function saveConversationExchange(
FILE: typescript/src/utils/helpers.ts
class AccumulatorTransform (line 5) | class AccumulatorTransform extends Transform {
method constructor (line 8) | constructor() {
method _transform (line 15) | _transform(chunk: any, encoding: string, callback: TransformCallback):...
method extractFromChunk (line 24) | extractFromChunk(chunk: any): string | null | any {
method getAccumulatedData (line 36) | getAccumulatedData(): string {
function extractXML (line 41) | function extractXML(text: string) {
function isClassifierToolInput (line 48) | function isClassifierToolInput(input: unknown): input is ToolInput {
function isConversationMessage (line 58) | function isConversationMessage(result: any): result is ConversationMessa...
FILE: typescript/src/utils/logger.ts
class Logger (line 6) | class Logger {
method constructor (line 10) | constructor(config: Partial<AgentSquadConfig>= {}, logger:any = consol...
method setLogger (line 15) | private setLogger(logger: any): void {
method info (line 19) | public info(message: string, ...params: any[]): void {
method warn (line 23) | public warn(message: string, ...params: any[]): void {
method error (line 27) | public error(message: string, ...params: any[]): void {
method debug (line 31) | public debug(message: string, ...params: any[]): void {
method log (line 35) | public log(message: string, ...params: any[]): void {
method logHeader (line 39) | private logHeader(title: string): void {
method printChatHistory (line 44) | printChatHistory(chatHistory: ConversationMessage[], agentId: string |...
method logClassifierOutput (line 69) | logClassifierOutput(output: any, isRaw: boolean = false): void {
method printIntent (line 78) | printIntent(userInput: string, intentClassifierResult: ClassifierResul...
method printExecutionTimes (line 96) | printExecutionTimes(executionTimes: Map<string, number>): void {
FILE: typescript/src/utils/tool.ts
class AgentToolResult (line 4) | class AgentToolResult {
method constructor (line 5) | constructor(
class AgentToolCallbacks (line 11) | class AgentToolCallbacks {
method onToolStart (line 16) | onToolStart(
method onToolEnd (line 38) | onToolEnd(
method onToolError (line 62) | onToolError(
type ToolFunction (line 87) | type ToolFunction = (...args: any[]) => Promise<any> | any;
class AgentTool (line 92) | class AgentTool {
method constructor (line 100) | constructor(options: {
method extractFunctionDescription (line 124) | private extractFunctionDescription(): string {
method extractProperties (line 128) | private extractProperties(func: ToolFunction): Record<string, any> {
method getParamNames (line 141) | private getParamNames(func: ToolFunction): string[] {
method wrapFunction (line 153) | private wrapFunction(func: ToolFunction): ToolFunction {
class AgentTools (line 164) | class AgentTools {
method constructor (line 168) | constructor(tools: AgentTool[], callbacks?: AgentToolCallbacks) {
method toolHandler (line 173) | async toolHandler(
method processTool (line 202) | private async processTool(toolName: string, inputData: any): Promise<a...
FILE: typescript/tests/Orchestrator.test.ts
class MockAgent (line 21) | class MockAgent extends Agent {
method constructor (line 22) | constructor(options: AgentOptions) {
method processRequest (line 26) | async processRequest(
FILE: typescript/tests/agents/OpenAi.test.ts
method [Symbol.asyncIterator] (line 92) | async *[Symbol.asyncIterator]() {
FILE: typescript/tests/classifiers/Classifier.test.ts
class MockBedrockLLMAgent (line 6) | class MockBedrockLLMAgent extends BedrockLLMAgent {
method constructor (line 7) | constructor(config: { name: string; streaming: boolean; description: s...
method processRequest (line 12) | async processRequest(
class MockClassifier (line 25) | class MockClassifier extends Classifier {
method processRequest (line 26) | async processRequest(
FILE: typescript/tests/mock/mockAgent.ts
class MockAgent (line 7) | class MockAgent extends Agent {
method constructor (line 10) | constructor(options: AgentOptions) {
method setAgentResponse (line 19) | public setAgentResponse(response:string){
method processRequest (line 32) | async processRequest(
FILE: typescript/tests/storage/ChatStorage.test.ts
function delay (line 6) | function delay(ms: number): Promise<void> {
Condensed preview — 347 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (1,837K chars).
[
{
"path": ".gitattributes",
"chars": 148,
"preview": "# Include TypeScript and Python as detectable languages\n*.py linguist-detectable=true\n*.ts linguist-detectable=true\n\n*.j"
},
{
"path": ".github/ISSUE_TEMPLATE/bug_report.yml",
"chars": 1380,
"preview": "name: Bug report\ndescription: Report a reproducible bug to help us improve\ntitle: \"Bug: TITLE\"\nlabels: [\"bug\"]\nbody:\n -"
},
{
"path": ".github/ISSUE_TEMPLATE/feature_request.yml",
"chars": 1033,
"preview": "name: Feature request\ndescription: Suggest an idea for Agent Squad\ntitle: \"Feature request: TITLE\"\nlabels: [\"feature-req"
},
{
"path": ".github/PULL_REQUEST_TEMPLATE.md",
"chars": 1146,
"preview": "<!-- markdownlint-disable MD041 MD043 -->\n## Issue Link (REQUIRED)\n<!-- This PR must be linked to an issue. PRs without "
},
{
"path": ".github/workflows/npm-publish.yml",
"chars": 865,
"preview": "# This workflow will run tests using node and then publish a package to GitHub Packages when a release is created\n# For "
},
{
"path": ".github/workflows/on-docs-update.yml",
"chars": 961,
"preview": "name: Build and Deploy Documentation\n\non:\n push:\n branches:\n - main\n paths:\n - 'docs/**'\n workflow_dis"
},
{
"path": ".github/workflows/on-issue-opened.yml",
"chars": 500,
"preview": "name: Label issues\n\non:\n issues:\n types:\n - reopened\n - opened\n\npermissions:\n issues: write\n\njobs:\n labe"
},
{
"path": ".github/workflows/on-push.yml",
"chars": 251,
"preview": "name: Push Workflow\n\non:\n push:\n branches:\n - main\n pull_request:\n types:\n - opened\n - edited\n\npe"
},
{
"path": ".github/workflows/pr-issue-link-checker.yml",
"chars": 3052,
"preview": "name: PR Issue Link Checker\n\non:\n pull_request:\n types: [opened, edited, reopened, synchronize]\n\njobs:\n check-issue"
},
{
"path": ".github/workflows/py-run-tests.yml",
"chars": 1051,
"preview": "name: Run Python tests\n\non:\n push:\n branches:\n - main\n paths:\n - \"python/**\"\n pull_request:\n paths:"
},
{
"path": ".github/workflows/pypi-publish.yml",
"chars": 915,
"preview": "name: Publish Python Package to PyPI\n\non:\n workflow_dispatch:\n\njobs:\n build-and-publish:\n runs-on: ubuntu-latest\n "
},
{
"path": ".github/workflows/ts-run-lint.yml",
"chars": 1041,
"preview": "name: Run lint checks on the project\n\non:\n push:\n paths:\n - 'typescript/**'\n pull_request:\n types:\n - "
},
{
"path": ".github/workflows/ts-run-security-checks.yml",
"chars": 778,
"preview": "name: Run security checks on the project\non:\n workflow_call:\n workflow_dispatch:\n\npermissions:\n contents: read\n\njobs:"
},
{
"path": ".github/workflows/ts-run-tests.yml",
"chars": 883,
"preview": "name: Run Typescript tests\n\non:\n push:\n branches:\n - main\n paths:\n - \"typescript/**\"\n pull_request:\n "
},
{
"path": ".gitignore",
"chars": 559,
"preview": "\n!typescript/jest.config.js\ntypescript/*.d.ts\nnode_modules\ntypescript/.package-lock.json\n\nexamples/chat-demo-app/cdk.out"
},
{
"path": "CODE_OF_CONDUCT.md",
"chars": 348,
"preview": "# Code of Conduct\n\nThis project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-condu"
},
{
"path": "CONTRIBUTING.md",
"chars": 3259,
"preview": "# Contributing Guidelines\n\nThank you for your interest in contributing to our project. Whether it's a bug report, new fe"
},
{
"path": "LICENSE",
"chars": 11358,
"preview": "\n Apache License\n Version 2.0, January 2004\n "
},
{
"path": "README.md",
"chars": 23171,
"preview": "<h2 align=\"center\">Agent Squad</h2>\n<p align=\"center\">Flexible, lightweight open-source framework for orchestrating mult"
},
{
"path": "docs/.gitignore",
"chars": 229,
"preview": "# build output\ndist/\n# generated types\n.astro/\n\n# dependencies\nnode_modules/\n\n# logs\nnpm-debug.log*\nyarn-debug.log*\nyarn"
},
{
"path": "docs/README.md",
"chars": 1182,
"preview": "<br>\n\n<p align=\"center\">\n <p align=\"center\">\n <img src=\"https://astro.badg.es/v2/built-with-starlight/tiny.svg\">\n <"
},
{
"path": "docs/astro.config.mjs",
"chars": 5751,
"preview": "import { defineConfig } from 'astro/config';\nimport starlight from '@astrojs/starlight';\n\n// https://astro.build/config\n"
},
{
"path": "docs/package.json",
"chars": 802,
"preview": "{\n \"name\": \"@agent-squad/docs\",\n \"description\": \"The official documentation for Agent Squad\",\n \"type\": \"module\",\n \"v"
},
{
"path": "docs/src/components/code.astro",
"chars": 1334,
"preview": "---\nimport { ExpressiveCode, ExpressiveCodeConfig } from 'expressive-code';\nimport { toHtml } from 'hast-util-to-html';\n"
},
{
"path": "docs/src/content/config.ts",
"chars": 892,
"preview": "/*\n * Copyright (C) 2023 Amazon.com, Inc. or its affiliates.\n *\n * Licensed under the Apache License, Version 2.0 (the \""
},
{
"path": "docs/src/content/docs/agents/built-in/amazon-bedrock-agent.mdx",
"chars": 7424,
"preview": "---\ntitle: AmazonBedrockAgent\ndescription: Documentation for the AmazonBedrockAgent in the Agent Squad\n---\n\nThe `AmazonB"
},
{
"path": "docs/src/content/docs/agents/built-in/anthropic-agent.mdx",
"chars": 18783,
"preview": "---\ntitle: Anthropic Agent\ndescription: Documentation for the AnthropicAgent in the Agent Squad\n---\n## Overview\n\nThe `An"
},
{
"path": "docs/src/content/docs/agents/built-in/bedrock-flows-agent.mdx",
"chars": 4274,
"preview": "---\ntitle: Amazon Bedrock Flows Agent\ndescription: Documentation for the BedrockFlowsAgent in the Agent Squad\n---\n\n## Ov"
},
{
"path": "docs/src/content/docs/agents/built-in/bedrock-inline-agent.mdx",
"chars": 8146,
"preview": "---\ntitle: Bedrock Inline Agent\ndescription: Documentation for the BedrockInlineAgent in the Agent Squad\n---\n\n## Overvie"
},
{
"path": "docs/src/content/docs/agents/built-in/bedrock-llm-agent.mdx",
"chars": 20051,
"preview": "---\ntitle: Bedrock LLM Agent\ndescription: Documentation for the BedrockLLMAgent in the Agent Squad\n---\n\n## Overview\n\nThe"
},
{
"path": "docs/src/content/docs/agents/built-in/bedrock-translator-agent.mdx",
"chars": 9139,
"preview": "---\ntitle: Bedrock Translator Agent\ndescription: Documentation for the Bedrock Translator Agent in the Agent Squad Syste"
},
{
"path": "docs/src/content/docs/agents/built-in/chain-agent.mdx",
"chars": 6628,
"preview": "---\ntitle: Chain Agent\ndescription: Documentation for the Chain Agent in the Agent Squad System\n---\nThe `ChainAgent` is "
},
{
"path": "docs/src/content/docs/agents/built-in/comprehend-filter-agent.mdx",
"chars": 15000,
"preview": "---\ntitle: Comprehend Filter Agent\ndescription: Documentation for the Comprehend Filter Agent in the Agent Squad System\n"
},
{
"path": "docs/src/content/docs/agents/built-in/lambda-agent.mdx",
"chars": 6385,
"preview": "---\ntitle: LambdaAgent\ndescription: Documentation for the LambdaAgent in the Agent Squad System\n---\n\nThe `LambdaAgent` i"
},
{
"path": "docs/src/content/docs/agents/built-in/lex-bot-agent.mdx",
"chars": 3749,
"preview": "---\ntitle: LexBotAgent\ndescription: Documentation for the LexBotAgent in the Agent Squad System\n---\n\nThe `LexBotAgent` i"
},
{
"path": "docs/src/content/docs/agents/built-in/openai-agent.mdx",
"chars": 13429,
"preview": "---\ntitle: Open AI Agent\ndescription: Documentation for the OpenAI Agent\n---\n\nThe `OpenAIAgent` is a powerful agent clas"
},
{
"path": "docs/src/content/docs/agents/built-in/supervisor-agent.mdx",
"chars": 22172,
"preview": "---\ntitle: Supervisor Agent\ndescription: Documentation for the SupervisorAgent in the Agent Squad System\n---\n\nimport { T"
},
{
"path": "docs/src/content/docs/agents/custom-agents.mdx",
"chars": 6704,
"preview": "---\ntitle: Custom Agents\ndescription: A guide to creating custom agents in the Agent Squad System, including an OpenAI a"
},
{
"path": "docs/src/content/docs/agents/overview.mdx",
"chars": 8460,
"preview": "---\ntitle: Agents overview\ndescription: An overview of agents\n---\n\nIn the Agent Squad, an agent is a fundamental buildin"
},
{
"path": "docs/src/content/docs/agents/tools.mdx",
"chars": 11292,
"preview": "---\ntitle: AgentTools System\ndescription: Documentation for the AgentTools system in the Agent Squad\n---\n\nThe AgentTools"
},
{
"path": "docs/src/content/docs/classifiers/built-in/anthropic-classifier.mdx",
"chars": 11668,
"preview": "---\ntitle: Anthropic Classifier\ndescription: How to configure the Anthropic classifier\n---\n\nThe Anthropic Classifier is "
},
{
"path": "docs/src/content/docs/classifiers/built-in/bedrock-classifier.mdx",
"chars": 11996,
"preview": "---\ntitle: Bedrock Classifier\ndescription: How to configure the Bedrock classifier\n---\n\nThe Bedrock Classifier is the de"
},
{
"path": "docs/src/content/docs/classifiers/built-in/openai-classifier.mdx",
"chars": 6209,
"preview": "---\ntitle: OpenAI Classifier\ndescription: How to configure the OpenAI classifier\n---\n\nThe OpenAI Classifier is a built-i"
},
{
"path": "docs/src/content/docs/classifiers/custom-classifier.mdx",
"chars": 7829,
"preview": "---\ntitle: Custom classifier\ndescription: How to configure and customize the Classifier in the Agent Squad System\n---\n\nT"
},
{
"path": "docs/src/content/docs/classifiers/overview.mdx",
"chars": 7770,
"preview": "---\ntitle: Classifier overview\ndescription: An introduction to the Classifier in the Agent Squad\n---\n\nThe Classifier is "
},
{
"path": "docs/src/content/docs/cookbook/examples/api-agent.mdx",
"chars": 14636,
"preview": "---\ntitle: Api Agent\ndescription: A guide to creating an API agent and integrating it into the Agent Squad System.\n---\n\n"
},
{
"path": "docs/src/content/docs/cookbook/examples/chat-chainlit-app.md",
"chars": 2134,
"preview": "---\ntitle: Chat Chainlit App with Agent Squad\ndescription: How to set up a Chainlit App using Agent Squad\n---\n\nThis exam"
},
{
"path": "docs/src/content/docs/cookbook/examples/chat-demo-app.md",
"chars": 6700,
"preview": "---\ntitle: Demo Web App Deployment\ndescription: How to deploy the demo chat web application for the Agent Squad System\n-"
},
{
"path": "docs/src/content/docs/cookbook/examples/ecommerce-support-simulator.md",
"chars": 8098,
"preview": "---\ntitle: AI-Powered E-commerce Support Simulator\ndescription: How to deploy the demo AI-Powered E-commerce Support Sim"
},
{
"path": "docs/src/content/docs/cookbook/examples/fast-api-streaming.md",
"chars": 1677,
"preview": "---\ntitle: FastAPI Streaming\ndescription: How to deploy use FastAPI Streaming with Agent Squad\n---\n\nThis example demonst"
},
{
"path": "docs/src/content/docs/cookbook/examples/ollama-agent.mdx",
"chars": 8504,
"preview": "---\ntitle: Ollama Agent\ndescription: A guide to creating an Ollama agent and integrating it into the Agent Squad System."
},
{
"path": "docs/src/content/docs/cookbook/examples/ollama-classifier.mdx",
"chars": 6792,
"preview": "---\ntitle: Ollama classifier with llama3.1\ndescription: Example of an Ollama classifier\n---\n\nWelcome to the Ollama Class"
},
{
"path": "docs/src/content/docs/cookbook/examples/python-local-demo.md",
"chars": 3419,
"preview": "---\ntitle: Python Local Demo\ndescription: How to run the Agent Squad System locally using Python\n---\n\n\n## Prerequisites\n"
},
{
"path": "docs/src/content/docs/cookbook/examples/typescript-local-demo.md",
"chars": 3015,
"preview": "---\ntitle: TypeScript Local Demo\ndescription: How to run the Agent Squad System locally using TypeScript\n---\n\n## Prerequ"
},
{
"path": "docs/src/content/docs/cookbook/lambda/aws-lambda-nodejs.md",
"chars": 2056,
"preview": "---\ntitle: AWS Lambda NodeJs with Agent Squad\ndescription: How to set up the Agent Squad System for AWS Lambda using Jav"
},
{
"path": "docs/src/content/docs/cookbook/lambda/aws-lambda-python.md",
"chars": 3965,
"preview": "---\ntitle: AWS Lambda Python with Agent Squad\ndescription: How to set up the Agent Squad System for AWS Lambda using Pyt"
},
{
"path": "docs/src/content/docs/cookbook/monitoring/agent-overlap.md",
"chars": 5349,
"preview": "---\ntitle: Agent Overlap Analysis\ndescription: Understanding and using the Agent Overlap Analysis feature in the Agent S"
},
{
"path": "docs/src/content/docs/cookbook/monitoring/logging.mdx",
"chars": 3986,
"preview": "---\ntitle: Logging in Agent Squad\ndescription: Understanding how to use a custom logger in Agent Squad\n---\n\n\nThe Agent S"
},
{
"path": "docs/src/content/docs/cookbook/monitoring/observability.mdx",
"chars": 15640,
"preview": "---\ntitle: Observability with Callbacks\ndescription: Learn how to implement comprehensive observability for Agent Squad "
},
{
"path": "docs/src/content/docs/cookbook/patterns/cost-efficient.md",
"chars": 1869,
"preview": "---\ntitle: Cost-Efficient Routing Pattern\ndescription: Cost-Efficient Routing Pattern using the Agent Squad framework\n--"
},
{
"path": "docs/src/content/docs/cookbook/patterns/multi-lingual.md",
"chars": 1931,
"preview": "---\ntitle: Multi-lingual Routing Pattern\ndescription: Multi-lingual Routing Pattern using the Agent Squad framework\n---"
},
{
"path": "docs/src/content/docs/cookbook/tools/math-operations.md",
"chars": 10977,
"preview": "---\ntitle: Creating a Math Agent with BedrockLLMAgent and Custom Tools\ndescription: Understanding Tool use in Bedrock LL"
},
{
"path": "docs/src/content/docs/cookbook/tools/weather-api.mdx",
"chars": 15080,
"preview": "---\ntitle: Creating a Weather Agent with BedrockLLMAgent and Custom Tools\ndescription: Understanding Tool use in Bedrock"
},
{
"path": "docs/src/content/docs/general/faq.md",
"chars": 8186,
"preview": "---\ntitle: FAQ\n---\n\n##### What is the Agent Squad framework?\n\nThe Agent Squad System is a flexible and powerful framewor"
},
{
"path": "docs/src/content/docs/general/how-it-works.md",
"chars": 9199,
"preview": "---\ntitle: How it works\n---\n\nThe Agent Squad framework is a powerful tool for implementing sophisticated AI systems comp"
},
{
"path": "docs/src/content/docs/general/introduction.md",
"chars": 3007,
"preview": "---\ntitle: Introduction\ndescription: Introduction to Agent Squad framework\n---\n\nThe emergence of both large and small la"
},
{
"path": "docs/src/content/docs/general/quickstart.mdx",
"chars": 11267,
"preview": "---\ntitle: Quickstart\n---\nimport { Tabs, TabItem } from '@astrojs/starlight/components';\n\n\n# Quickstart Guide for Agent "
},
{
"path": "docs/src/content/docs/index.mdx",
"chars": 4172,
"preview": "---\ntitle: Agent Squad framework\ndescription: Manage multiple AI agents and handle complex conversations\ntemplate: splas"
},
{
"path": "docs/src/content/docs/orchestrator/overview.mdx",
"chars": 19039,
"preview": "---\ntitle: Orchestrator overview\ndescription: An introduction to the Orchestrator\n---\n\nThe Agent Squad is the central co"
},
{
"path": "docs/src/content/docs/retrievers/built-in/bedrock-kb-retriever.mdx",
"chars": 3835,
"preview": "---\ntitle: Knowledge Bases for Amazon Bedrock retriever\ndescription: An overview of Knowledge Bases for Amazon Bedrock r"
},
{
"path": "docs/src/content/docs/retrievers/custom-retriever.mdx",
"chars": 14115,
"preview": "---\ntitle: Custom retriever\ndescription: An overview of retrievers and supported type in the Agent Squad System\n---\n\nThe"
},
{
"path": "docs/src/content/docs/retrievers/overview.md",
"chars": 1102,
"preview": "---\ntitle: Retrievers overview\ndescription: An overview of retrievers\n---\n\nA retriever is a component or mechanism used "
},
{
"path": "docs/src/content/docs/storage/custom.mdx",
"chars": 10846,
"preview": "---\ntitle: Custom storage\ndescription: Extending the ChatStorage class to create custom storage options in the Agent Squ"
},
{
"path": "docs/src/content/docs/storage/dynamodb.mdx",
"chars": 3228,
"preview": "---\ntitle: DynamoDB Storage\ndescription: Using Amazon DynamoDB for persistent conversation storage in the Agent Squad Sy"
},
{
"path": "docs/src/content/docs/storage/in-memory.mdx",
"chars": 2195,
"preview": "---\ntitle: In-Memory Storage\ndescription: Using in-memory storage for conversation history in the Agent Squad System\n---"
},
{
"path": "docs/src/content/docs/storage/overview.md",
"chars": 2370,
"preview": "---\ntitle: Storage overview\ndescription: An overview of conversation storage options in the Agent Squad System\n---\n\nThe "
},
{
"path": "docs/src/content/docs/storage/sql.mdx",
"chars": 6530,
"preview": "---\ntitle: SQL Storage\ndescription: Using SQL databases (SQLite/Turso) for persistent conversation storage in the Agent "
},
{
"path": "docs/src/env.d.ts",
"chars": 84,
"preview": "/// <reference path=\"../.astro/types.d.ts\" />\n/// <reference types=\"astro/client\" />"
},
{
"path": "docs/src/styles/custom.css",
"chars": 3204,
"preview": "/* Dark mode colors. */\n:root {\n --sl-color-accent-low: #2c230a;\n --sl-color-accent: #846500;\n --sl-color-accent-high"
},
{
"path": "docs/src/styles/font.css",
"chars": 888,
"preview": "@font-face {\n font-family: \"JetBrainsMono NF\";\n src: url(\"../assets/fonts/JetBrainsMonoNerdFont-Regular.ttf\")\n form"
},
{
"path": "docs/src/styles/landing.css",
"chars": 1220,
"preview": ":root {\n\t--sl-hue-accent: 255;\n\t--sl-color-accent-low: hsl(var(--sl-hue-accent), 14%, 20%);\n\t--sl-color-accent: hsl(var("
},
{
"path": "docs/src/styles/terminal.css",
"chars": 1108,
"preview": "/* Solarized color palette */\n:root {\n --sol-red: #dc322f;\n --sol-bright-red: #cb4b16;\n --sol-green: #859900;\n --sol"
},
{
"path": "docs/tsconfig.json",
"chars": 41,
"preview": "{\n \"extends\": \"astro/tsconfigs/strict\"\n}"
},
{
"path": "examples/bedrock-flows/python/main.py",
"chars": 2992,
"preview": "import asyncio\nimport uuid\nimport sys\nfrom typing import Any, List\nfrom agent_squad.orchestrator import AgentSquad, Agen"
},
{
"path": "examples/bedrock-flows/readme.md",
"chars": 1442,
"preview": "# BedrockFlowsAgent Example\n\nThis example demonstrates how to use the **[BedrockFlowsAgent](https://awslabs.github.io/ag"
},
{
"path": "examples/bedrock-flows/typescript/main.ts",
"chars": 4151,
"preview": "import readline from \"readline\";\nimport {\n AgentSquad,\n Logger,\n BedrockFlowsAgent,\n Agent,\n} from \"agent-squad\";\n\n\n"
},
{
"path": "examples/bedrock-inline-agents/python/main.py",
"chars": 2677,
"preview": "import asyncio\nimport uuid\nimport sys\nfrom agent_squad.agents import BedrockInlineAgent, BedrockInlineAgentOptions\nimpor"
},
{
"path": "examples/bedrock-inline-agents/typescript/main.ts",
"chars": 3440,
"preview": "//import { BedrockInlineAgent, BedrockInlineAgentOptions } from 'agent-squad';\nimport { BedrockInlineAgent, BedrockInlin"
},
{
"path": "examples/bedrock-prompt-routing/main.py",
"chars": 4012,
"preview": "\nimport uuid\nimport asyncio\nimport os\nfrom typing import Optional, Any\nimport json\nimport sys\nfrom agent_squad.orchestra"
},
{
"path": "examples/bedrock-prompt-routing/readme.md",
"chars": 980,
"preview": "# Bedrock Prompt Routing Example\n\nThis guide demonstrates how to implement and utilize [Amazon Bedrock Prompt Routing](h"
},
{
"path": "examples/chat-chainlit-app/.gitignore",
"chars": 39,
"preview": ".chainlit/*\n__pycache__/*\n.venv/*\n.env\n"
},
{
"path": "examples/chat-chainlit-app/README.md",
"chars": 2150,
"preview": "To set up and run the application first install dependencies from `requirements.txt` file, follow these steps:\n\n### Prer"
},
{
"path": "examples/chat-chainlit-app/agents.py",
"chars": 2128,
"preview": "from agent_squad.agents import BedrockLLMAgent, BedrockLLMAgentOptions, AgentCallbacks\nfrom ollamaAgent import OllamaAge"
},
{
"path": "examples/chat-chainlit-app/app.py",
"chars": 2231,
"preview": "import uuid\nimport chainlit as cl\nfrom agents import create_tech_agent, create_travel_agent, create_health_agent\nfrom ag"
},
{
"path": "examples/chat-chainlit-app/chainlit.md",
"chars": 737,
"preview": "# Welcome to Chainlit! 🚀🤖\n\nHi there, Developer! 👋 We're excited to have you on board. Chainlit is a powerful tool design"
},
{
"path": "examples/chat-chainlit-app/ollamaAgent.py",
"chars": 2238,
"preview": "from typing import List, Dict, Optional, AsyncIterable, Any\nfrom agent_squad.agents import Agent, AgentOptions\nfrom agen"
},
{
"path": "examples/chat-chainlit-app/requirements.txt",
"chars": 58,
"preview": "chainlit==1.3.2\nagent_squad\nollama==0.3.3\npydantic==2.10.1"
},
{
"path": "examples/chat-demo-app/.gitignore",
"chars": 145,
"preview": "*.js\n!jest.config.js\n*.d.ts\nnode_modules\ndist\n\n# CDK asset staging directory\n.cdk.staging\ncdk.out\n\n!postcss.config.js\n!v"
},
{
"path": "examples/chat-demo-app/.npmignore",
"chars": 65,
"preview": "*.ts\n!*.d.ts\n\n# CDK asset staging directory\n.cdk.staging\ncdk.out\n"
},
{
"path": "examples/chat-demo-app/README.md",
"chars": 5474,
"preview": "## 🎮 Demo Application\n\n### Overview\nThe demo showcases the versatility of the Agent Squad System through an interactive "
},
{
"path": "examples/chat-demo-app/bin/chat-demo-app.ts",
"chars": 828,
"preview": "#!/usr/bin/env node\nimport 'source-map-support/register';\nimport * as cdk from 'aws-cdk-lib';\nimport { ChatDemoStack } f"
},
{
"path": "examples/chat-demo-app/cdk.json",
"chars": 3514,
"preview": "{\n \"app\": \"npx ts-node --prefer-ts-exts bin/chat-demo-app.ts\",\n \"watch\": {\n \"include\": [\n \"**\"\n ],\n \"exc"
},
{
"path": "examples/chat-demo-app/jest.config.js",
"chars": 157,
"preview": "module.exports = {\n testEnvironment: 'node',\n roots: ['<rootDir>/test'],\n testMatch: ['**/*.test.ts'],\n transform: {"
},
{
"path": "examples/chat-demo-app/lambda/auth/index.mjs",
"chars": 5982,
"preview": "import {\n SecretsManagerClient,\n GetSecretValueCommand,\n} from \"@aws-sdk/client-secrets-manager\";\nimport { fromBase64 "
},
{
"path": "examples/chat-demo-app/lambda/auth/package.json",
"chars": 295,
"preview": "{\n \"name\": \"auth\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"tes"
},
{
"path": "examples/chat-demo-app/lambda/find-my-name/lambda.py",
"chars": 180,
"preview": "import json\n\ndef lambda_handler(event, context):\n print(event)\n return {\n 'statusCode': 200,\n 'body'"
},
{
"path": "examples/chat-demo-app/lambda/multi-agent/index.ts",
"chars": 10110,
"preview": "import { Logger } from \"@aws-lambda-powertools/logger\";\nimport {\n AgentSquad,\n BedrockLLMAgent,\n DynamoDbChatStorage,"
},
{
"path": "examples/chat-demo-app/lambda/multi-agent/math_tool.ts",
"chars": 11255,
"preview": "import { ConversationMessage, ParticipantRole, Logger } from \"agent-squad\";\n\n\nexport const mathAgentToolDefinition = [\n"
},
{
"path": "examples/chat-demo-app/lambda/multi-agent/prompts.ts",
"chars": 15688,
"preview": "import { Agent } from \"agent-squad\";\n\nexport const WEATHER_AGENT_PROMPT = `\nYou are a weather assistant that provides cu"
},
{
"path": "examples/chat-demo-app/lambda/multi-agent/weather_tool.ts",
"chars": 3184,
"preview": "// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Co"
},
{
"path": "examples/chat-demo-app/lambda/sync_bedrock_knowledgebase/lambda.py",
"chars": 260,
"preview": "import boto3\n\nclient = boto3.client('bedrock-agent')\n\n\ndef lambda_handler(event, context):\n response = client.start_i"
},
{
"path": "examples/chat-demo-app/lib/CustomResourcesLambda/aoss-index-create.ts",
"chars": 5210,
"preview": "import { defaultProvider } from '@aws-sdk/credential-provider-node';\nimport { Client } from '@opensearch-project/opensea"
},
{
"path": "examples/chat-demo-app/lib/CustomResourcesLambda/data-source-sync.ts",
"chars": 4825,
"preview": "import { BedrockAgentClient, StartIngestionJobCommand, DeleteDataSourceCommand, DeleteKnowledgeBaseCommand, GetDataSourc"
},
{
"path": "examples/chat-demo-app/lib/CustomResourcesLambda/permission-validation.ts",
"chars": 5156,
"preview": "import { defaultProvider } from '@aws-sdk/credential-provider-node';\nimport { Client } from '@opensearch-project/opensea"
},
{
"path": "examples/chat-demo-app/lib/airlines.yaml",
"chars": 12070,
"preview": "AWSTemplateFormatVersion: 2010-09-09\nDescription: >\n Amazon Lex for travel hospitality offers pre-built solutions\n so "
},
{
"path": "examples/chat-demo-app/lib/bedrock-agent-construct.ts",
"chars": 7155,
"preview": "import * as cdk from 'aws-cdk-lib';\nimport * as lambda from 'aws-cdk-lib/aws-lambda';\nimport * as iam from 'aws-cdk-lib/"
},
{
"path": "examples/chat-demo-app/lib/chat-demo-app-stack.ts",
"chars": 6826,
"preview": "import * as cdk from 'aws-cdk-lib';\nimport * as nodejs from 'aws-cdk-lib/aws-lambda-nodejs';\nimport * as lambda from 'aw"
},
{
"path": "examples/chat-demo-app/lib/constants.ts",
"chars": 1343,
"preview": "export const USER_INPUT_ACTION_NAME = \"UserInputAction\";\nexport const USER_INPUT_PARENT_SIGNATURE = \"AMAZON.UserInput\";\n"
},
{
"path": "examples/chat-demo-app/lib/knowledge-base-construct.ts",
"chars": 19395,
"preview": "import { Effect, ManagedPolicy, PolicyDocument, PolicyStatement, Role, ServicePrincipal } from \"aws-cdk-lib/aws-iam\";\nim"
},
{
"path": "examples/chat-demo-app/lib/lex-agent-construct.ts",
"chars": 1040,
"preview": "import * as cdk from 'aws-cdk-lib';\nimport * as cfn_include from 'aws-cdk-lib/cloudformation-include';\nimport { Construc"
},
{
"path": "examples/chat-demo-app/lib/user-interface-stack.ts",
"chars": 8809,
"preview": "import * as cdk from 'aws-cdk-lib';\nimport { Construct } from 'constructs';\nimport * as path from \"node:path\";\nimport {\n"
},
{
"path": "examples/chat-demo-app/lib/utils/OpensearchServerlessHelper.ts",
"chars": 11210,
"preview": "import { Effect, ManagedPolicy, PolicyDocument, PolicyStatement, Role, ServicePrincipal } from \"aws-cdk-lib/aws-iam\";\nim"
},
{
"path": "examples/chat-demo-app/lib/utils/utils.ts",
"chars": 2848,
"preview": "import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { writeFileSync } from 'fs';\nimport { resolve }"
},
{
"path": "examples/chat-demo-app/package.json",
"chars": 1248,
"preview": "{\n \"name\": \"chat-demo-app\",\n \"version\": \"0.1.0\",\n \"bin\": {\n \"chat-demo-app\": \"bin/chat-demo-app.js\"\n },\n \"script"
},
{
"path": "examples/chat-demo-app/scripts/download.js",
"chars": 860,
"preview": "const https = require('https');\nconst fs = require('fs');\nconst path = require('path');\n\nfunction downloadFile(url, outp"
},
{
"path": "examples/chat-demo-app/test/chat-demo-app.ts",
"chars": 592,
"preview": "// import * as cdk from 'aws-cdk-lib';\n// import { Template } from 'aws-cdk-lib/assertions';\n// import * as ChatDemoStac"
},
{
"path": "examples/chat-demo-app/tsconfig.json",
"chars": 663,
"preview": "{\n \"compilerOptions\": {\n \"target\": \"ES2020\",\n \"module\": \"commonjs\",\n \"lib\": [\n \"es2020\",\n \"dom\"\n "
},
{
"path": "examples/chat-demo-app/ui/.babelrc",
"chars": 106,
"preview": "{\n \"presets\": [\"@babel/preset-env\"],\n \"plugins\": [\"@babel/plugin-transform-modules-commonjs\"]\n }\n "
},
{
"path": "examples/chat-demo-app/ui/.gitignore",
"chars": 264,
"preview": "# build output\ndist/\n# generated types\n.astro/\n\n# dependencies\nnode_modules/\n\n# logs\nnpm-debug.log*\nyarn-debug.log*\nyarn"
},
{
"path": "examples/chat-demo-app/ui/.vscode/extensions.json",
"chars": 87,
"preview": "{\n \"recommendations\": [\"astro-build.astro-vscode\"],\n \"unwantedRecommendations\": []\n}\n"
},
{
"path": "examples/chat-demo-app/ui/.vscode/launch.json",
"chars": 207,
"preview": "{\n \"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"command\": \"./node_modules/.bin/astro dev\",\n \"name\": \"Dev"
},
{
"path": "examples/chat-demo-app/ui/README.md",
"chars": 2057,
"preview": "# Astro Starter Kit: Minimal\n\n```sh\nnpm create astro@latest -- --template minimal\n```\n\n[': '😊',\n ':-)': '😊',\n ':D': '😄',\n '"
},
{
"path": "examples/chat-demo-app/ui/src/components/loadingScreen.tsx",
"chars": 426,
"preview": "import { Loader2 } from 'lucide-react';\n\nconst LoadingScreen = ({ text = 'Loading...' }) => {\n return (\n <div classN"
},
{
"path": "examples/chat-demo-app/ui/src/pages/index.astro",
"chars": 476,
"preview": "---\nimport ChatWindow from '../components/ChatWindow';\n---\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\" />\n <link re"
},
{
"path": "examples/chat-demo-app/ui/src/utils/ApiClient.ts",
"chars": 1526,
"preview": "import { getAwsExports } from './amplifyConfig';\nimport { fetchAuthSession } from \"aws-amplify/auth\";\n\nclass ApiClientBa"
},
{
"path": "examples/chat-demo-app/ui/src/utils/amplifyConfig.ts",
"chars": 1403,
"preview": "import { Amplify, ResourcesConfig } from 'aws-amplify';\nimport { fetchAuthSession } from 'aws-amplify/auth';\n\ninterface "
},
{
"path": "examples/chat-demo-app/ui/tailwind.config.cjs",
"chars": 195,
"preview": "/** @type {import('tailwindcss').Config} */\nmodule.exports = {\n content: ['./src/**/*.{astro,html,js,jsx,md,mdx,svelt"
},
{
"path": "examples/chat-demo-app/ui/tsconfig.json",
"chars": 532,
"preview": "{\n \"compilerOptions\": {\n \"target\": \"ESNext\",\n \"module\": \"ESNext\",\n \"moduleResolution\": \"node\",\n \"resolveJso"
},
{
"path": "examples/ecommerce-support-simulator/.gitignore",
"chars": 88,
"preview": "!jest.config.js\n*.d.ts\nnode_modules\n\n# CDK asset staging directory\n.cdk.staging\ncdk.out\n"
},
{
"path": "examples/ecommerce-support-simulator/.npmignore",
"chars": 65,
"preview": "*.ts\n!*.d.ts\n\n# CDK asset staging directory\n.cdk.staging\ncdk.out\n"
},
{
"path": "examples/ecommerce-support-simulator/README.md",
"chars": 6986,
"preview": "# AI-Powered E-commerce Support Simulator\n\nA demonstration of how AI agents and human support can work together in an e-"
},
{
"path": "examples/ecommerce-support-simulator/bin/ai-ecommerce-support-simulator.ts",
"chars": 1033,
"preview": "#!/usr/bin/env node\nimport 'source-map-support/register';\nimport * as cdk from 'aws-cdk-lib';\nimport { AiEcommerceSuppor"
},
{
"path": "examples/ecommerce-support-simulator/cdk.json",
"chars": 3506,
"preview": "{\n \"app\": \"npx ts-node --prefer-ts-exts bin/ai-ecommerce-support-simulator.ts\",\n \"watch\": {\n \"include\": [\n \"**"
},
{
"path": "examples/ecommerce-support-simulator/graphql/Query.sendMessage.js",
"chars": 1656,
"preview": "import { util } from '@aws-appsync/utils'\n\nexport function request(ctx) {\n const { accountId, customerQueueUrl, custome"
},
{
"path": "examples/ecommerce-support-simulator/graphql/schema.graphql",
"chars": 862,
"preview": "# Directives for authentication\ndirective @aws_iam on FIELD_DEFINITION | OBJECT\ndirective @aws_cognito_user_pools(cognit"
},
{
"path": "examples/ecommerce-support-simulator/graphql/sendResponse.js",
"chars": 727,
"preview": "export function request(ctx) {\n return {\n payload: {\n destination: ctx.arguments.destination,\n message: ct"
},
{
"path": "examples/ecommerce-support-simulator/graphql/sendResponsePipeline.js",
"chars": 587,
"preview": "export function request(ctx) {\n return {};\n }\n \n export function response(ctx) {\n if (ctx.error) {\n util.e"
},
{
"path": "examples/ecommerce-support-simulator/jest.config.js",
"chars": 157,
"preview": "module.exports = {\n testEnvironment: 'node',\n roots: ['<rootDir>/test'],\n testMatch: ['**/*.test.ts'],\n transform: {"
},
{
"path": "examples/ecommerce-support-simulator/lambda/customerMessage/agents.ts",
"chars": 8616,
"preview": "import {\n AgentSquad,\n BedrockLLMAgent,\n BedrockLLMAgentOptions,\n AmazonBedrockAgent,\n AmazonBedrockAgentOptions,\n "
},
{
"path": "examples/ecommerce-support-simulator/lambda/customerMessage/index.ts",
"chars": 3578,
"preview": "import { SQSEvent, SQSHandler } from 'aws-lambda';\nimport { SQSClient, SendMessageCommand } from \"@aws-sdk/client-sqs\";\n"
},
{
"path": "examples/ecommerce-support-simulator/lambda/customerMessage/sqsLogger.ts",
"chars": 1462,
"preview": "import { SQSClient, SendMessageCommand } from \"@aws-sdk/client-sqs\";\n\ninterface LogMessage {\n destination: string;\n me"
},
{
"path": "examples/ecommerce-support-simulator/lambda/sendResponse/index.ts",
"chars": 3011,
"preview": "import { SQSEvent, SQSHandler } from 'aws-lambda';\nimport axios from 'axios';\nimport { SignatureV4 } from \"@aws-sdk/sign"
},
{
"path": "examples/ecommerce-support-simulator/lambda/supportMessage/index.ts",
"chars": 1383,
"preview": "import { SQSEvent, SQSHandler } from 'aws-lambda';\nimport { SQSClient, SendMessageCommand } from \"@aws-sdk/client-sqs\";\n"
},
{
"path": "examples/ecommerce-support-simulator/lib/ai-ecommerce-support-simulator-stack.ts",
"chars": 14317,
"preview": "import path from \"path\";\n\nimport {\n aws_lambda as lambda,\n aws_sqs as sqs,\n aws_lambda_nodejs as nodejs,\n aws_iam as"
},
{
"path": "examples/ecommerce-support-simulator/lib/utils/utils.ts",
"chars": 674,
"preview": "import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nexport abstract class Utils {\n static copyDirRecursi"
},
{
"path": "examples/ecommerce-support-simulator/package.json",
"chars": 1049,
"preview": "{\n \"name\": \"ai-ecommerce-support-simulator\",\n \"version\": \"0.1.0\",\n \"bin\": {\n \"ai-ecommerce-support-simulator\": \"bi"
},
{
"path": "examples/ecommerce-support-simulator/resources/ui/.gitignore",
"chars": 264,
"preview": "# build output\ndist/\n# generated types\n.astro/\n\n# dependencies\nnode_modules/\n\n# logs\nnpm-debug.log*\nyarn-debug.log*\nyarn"
},
{
"path": "examples/ecommerce-support-simulator/resources/ui/.vscode/extensions.json",
"chars": 111,
"preview": "{\n \"recommendations\": [\"astro-build.astro-vscode\", \"unifiedjs.vscode-mdx\"],\n \"unwantedRecommendations\": []\n}\n"
},
{
"path": "examples/ecommerce-support-simulator/resources/ui/.vscode/launch.json",
"chars": 207,
"preview": "{\n \"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"command\": \"./node_modules/.bin/astro dev\",\n \"name\": \"Dev"
},
{
"path": "examples/ecommerce-support-simulator/resources/ui/README.md",
"chars": 2857,
"preview": "# Astro Starter Kit: Blog\n\n```sh\nnpm create astro@latest -- --template blog\n```\n\n[.Config} */\nexport default {\n content: ['./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts"
},
{
"path": "examples/ecommerce-support-simulator/resources/ui/tsconfig.json",
"chars": 494,
"preview": "{\n \"extends\": \"astro/tsconfigs/base\",\n \"compilerOptions\": {\n \"strictNullChecks\": false,\n \"noUnusedParameters\": f"
},
{
"path": "examples/ecommerce-support-simulator/test/ai-ecommerce-support-simulator.test.ts",
"chars": 679,
"preview": "// import * as cdk from 'aws-cdk-lib';\n// import { Template } from 'aws-cdk-lib/assertions';\n// import * as AiEcommerceS"
},
{
"path": "examples/ecommerce-support-simulator/tsconfig.json",
"chars": 781,
"preview": "{\n \"compilerOptions\": {\n \"target\": \"ES2022\",\n \"module\": \"NodeNext\",\n \"lib\": [\n \"es2020\",\n \"dom\"\n "
},
{
"path": "examples/fast-api-streaming/README.MD",
"chars": 2057,
"preview": "# Agent Squad with Fast-api\n\nThis project implements a FastAPI-based web service that uses an Agent Squad to process and"
},
{
"path": "examples/fast-api-streaming/main.py",
"chars": 2230,
"preview": "from fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom fastapi.responses import StreamingRe"
},
{
"path": "examples/fast-api-streaming/requirements.txt",
"chars": 52,
"preview": "agent_squad>=0.0.17\nfastapi==0.115.2\nuvicorn==0.32.0"
},
{
"path": "examples/langfuse-demo/main.py",
"chars": 13049,
"preview": "\nimport uuid\nimport asyncio\nfrom typing import Optional, Any\nimport json\nimport sys\nimport os\nfrom tools import weather_"
},
{
"path": "examples/langfuse-demo/readme.md",
"chars": 3281,
"preview": "# Agent Squad with Langfuse\n\nA demonstration project for orchestrating multiple AI agents using AWS Bedrock with integra"
},
{
"path": "examples/langfuse-demo/requirements.txt",
"chars": 49,
"preview": "langfuse\npython-dotenv\nboto3\nagent-squad\nrequests"
},
{
"path": "examples/langfuse-demo/tools/weather_tool.py",
"chars": 4616,
"preview": "import requests\nfrom requests.exceptions import RequestException\nfrom typing import List, Dict, Any\nfrom agent_squad.typ"
},
{
"path": "examples/local-demo/local-orchestrator.ts",
"chars": 7106,
"preview": "import readline from \"readline\";\nimport {\n AgentSquad,\n BedrockLLMAgent,\n AmazonBedrockAgent,\n LexBotAgent,\n Lambda"
},
{
"path": "examples/local-demo/package.json",
"chars": 285,
"preview": "{\n \"name\": \"local-demo\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"main\": \"index.js\",\n \"scripts\": {\n \"test\": \"e"
},
{
"path": "examples/local-demo/tools/math_tool.ts",
"chars": 11755,
"preview": "import { ConversationMessage, ParticipantRole, Logger } from \"agent-squad\";\n\nexport const MATH_AGENT_PROMPT = `\nYou are "
},
{
"path": "examples/local-demo/tools/weather_tool.ts",
"chars": 4293,
"preview": "// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { Co"
},
{
"path": "examples/python/imports.py",
"chars": 194,
"preview": "# some_file.py\nimport sys\n# caution: path[0] is reserved for script path (or '' in REPL)\n\n# import your demo here\nsys.pa"
},
{
"path": "examples/python/main-app.py",
"chars": 427,
"preview": "import imports\nimport streamlit as st\n\nst.set_page_config(\n page_title=\"AWS Agent Squad Demos\",\n page_icon=\"👋\",\n)\n"
},
{
"path": "examples/python/movie-production/movie-production-demo.py",
"chars": 6381,
"preview": "import uuid\nimport asyncio\nimport streamlit as st\nimport boto3\nfrom search_web import search_web\nfrom agent_squad.orches"
},
{
"path": "examples/python/movie-production/readme.md",
"chars": 1501,
"preview": "## 🎬 AI Movie Production Agent\nThis Streamlit app is an AI-powered movie production assistant that helps bring your movi"
},
{
"path": "examples/python/movie-production/requirements.txt",
"chars": 39,
"preview": "agent-squad\nstreamlit\nduckduckgo-search"
},
{
"path": "examples/python/movie-production/search_web.py",
"chars": 740,
"preview": "from agent_squad.utils.logger import Logger\nfrom duckduckgo_search import DDGS\n\n\ndef search_web(query: str, num_results:"
},
{
"path": "examples/python/pages/home.py",
"chars": 2033,
"preview": "import streamlit as st\n\nst.title(\"AWS Agent Squad Demos\")\n\nst.markdown(\"\"\"\nWelcome to our comprehensive demo application"
}
]
// ... and 147 more files (download for full content)
About this extraction
This page contains the full source code of the awslabs/agent-squad GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 347 files (1.7 MB), approximately 390.7k tokens, and a symbol index with 1186 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.