beeai-framework 0.1.10 → 0.1.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -6
- package/dist/adapters/amazon-bedrock/backend/chat.cjs.map +1 -1
- package/dist/adapters/amazon-bedrock/backend/chat.d.cts +7 -6
- package/dist/adapters/amazon-bedrock/backend/chat.d.ts +7 -6
- package/dist/adapters/amazon-bedrock/backend/chat.js.map +1 -1
- package/dist/adapters/amazon-bedrock/backend/client.cjs.map +1 -1
- package/dist/adapters/amazon-bedrock/backend/client.d.cts +1 -1
- package/dist/adapters/amazon-bedrock/backend/client.d.ts +1 -1
- package/dist/adapters/amazon-bedrock/backend/client.js.map +1 -1
- package/dist/adapters/amazon-bedrock/backend/embedding.cjs.map +1 -1
- package/dist/adapters/amazon-bedrock/backend/embedding.d.cts +15 -4
- package/dist/adapters/amazon-bedrock/backend/embedding.d.ts +15 -4
- package/dist/adapters/amazon-bedrock/backend/embedding.js.map +1 -1
- package/dist/adapters/anthropic/backend/chat.cjs.map +1 -1
- package/dist/adapters/anthropic/backend/chat.d.cts +9 -8
- package/dist/adapters/anthropic/backend/chat.d.ts +9 -8
- package/dist/adapters/anthropic/backend/chat.js.map +1 -1
- package/dist/adapters/anthropic/backend/client.cjs +5 -5
- package/dist/adapters/anthropic/backend/client.cjs.map +1 -1
- package/dist/adapters/anthropic/backend/client.d.cts +2 -2
- package/dist/adapters/anthropic/backend/client.d.ts +2 -2
- package/dist/adapters/anthropic/backend/client.js +5 -5
- package/dist/adapters/anthropic/backend/client.js.map +1 -1
- package/dist/adapters/anthropic/backend/embedding.cjs.map +1 -1
- package/dist/adapters/anthropic/backend/embedding.d.cts +15 -4
- package/dist/adapters/anthropic/backend/embedding.d.ts +15 -4
- package/dist/adapters/anthropic/backend/embedding.js.map +1 -1
- package/dist/adapters/azure-openai/backend/chat.cjs.map +1 -1
- package/dist/adapters/azure-openai/backend/chat.d.cts +9 -8
- package/dist/adapters/azure-openai/backend/chat.d.ts +9 -8
- package/dist/adapters/azure-openai/backend/chat.js.map +1 -1
- package/dist/adapters/azure-openai/backend/client.cjs +6 -6
- package/dist/adapters/azure-openai/backend/client.cjs.map +1 -1
- package/dist/adapters/azure-openai/backend/client.d.cts +2 -2
- package/dist/adapters/azure-openai/backend/client.d.ts +2 -2
- package/dist/adapters/azure-openai/backend/client.js +6 -6
- package/dist/adapters/azure-openai/backend/client.js.map +1 -1
- package/dist/adapters/azure-openai/backend/embedding.cjs.map +1 -1
- package/dist/adapters/azure-openai/backend/embedding.d.cts +15 -4
- package/dist/adapters/azure-openai/backend/embedding.d.ts +15 -4
- package/dist/adapters/azure-openai/backend/embedding.js.map +1 -1
- package/dist/adapters/dummy/backend/chat.cjs.map +1 -1
- package/dist/adapters/dummy/backend/chat.d.cts +12 -7
- package/dist/adapters/dummy/backend/chat.d.ts +12 -7
- package/dist/adapters/dummy/backend/chat.js.map +1 -1
- package/dist/adapters/dummy/backend/embedding.cjs.map +1 -1
- package/dist/adapters/dummy/backend/embedding.d.cts +15 -3
- package/dist/adapters/dummy/backend/embedding.d.ts +15 -3
- package/dist/adapters/dummy/backend/embedding.js.map +1 -1
- package/dist/adapters/google-vertex/backend/chat.cjs.map +1 -1
- package/dist/adapters/google-vertex/backend/chat.d.cts +9 -8
- package/dist/adapters/google-vertex/backend/chat.d.ts +9 -8
- package/dist/adapters/google-vertex/backend/chat.js.map +1 -1
- package/dist/adapters/google-vertex/backend/client.cjs.map +1 -1
- package/dist/adapters/google-vertex/backend/client.d.cts +1 -1
- package/dist/adapters/google-vertex/backend/client.d.ts +1 -1
- package/dist/adapters/google-vertex/backend/client.js.map +1 -1
- package/dist/adapters/google-vertex/backend/embedding.cjs.map +1 -1
- package/dist/adapters/google-vertex/backend/embedding.d.cts +15 -4
- package/dist/adapters/google-vertex/backend/embedding.d.ts +15 -4
- package/dist/adapters/google-vertex/backend/embedding.js.map +1 -1
- package/dist/adapters/groq/backend/chat.cjs.map +1 -1
- package/dist/adapters/groq/backend/chat.d.cts +9 -8
- package/dist/adapters/groq/backend/chat.d.ts +9 -8
- package/dist/adapters/groq/backend/chat.js.map +1 -1
- package/dist/adapters/groq/backend/client.cjs +3 -3
- package/dist/adapters/groq/backend/client.cjs.map +1 -1
- package/dist/adapters/groq/backend/client.d.cts +1 -1
- package/dist/adapters/groq/backend/client.d.ts +1 -1
- package/dist/adapters/groq/backend/client.js +3 -3
- package/dist/adapters/groq/backend/client.js.map +1 -1
- package/dist/adapters/groq/backend/embedding.cjs.map +1 -1
- package/dist/adapters/groq/backend/embedding.d.cts +15 -4
- package/dist/adapters/groq/backend/embedding.d.ts +15 -4
- package/dist/adapters/groq/backend/embedding.js.map +1 -1
- package/dist/adapters/langchain/backend/chat.cjs +5 -3
- package/dist/adapters/langchain/backend/chat.cjs.map +1 -1
- package/dist/adapters/langchain/backend/chat.d.cts +12 -7
- package/dist/adapters/langchain/backend/chat.d.ts +12 -7
- package/dist/adapters/langchain/backend/chat.js +5 -3
- package/dist/adapters/langchain/backend/chat.js.map +1 -1
- package/dist/adapters/langchain/backend/embedding.cjs.map +1 -1
- package/dist/adapters/langchain/backend/embedding.d.cts +15 -3
- package/dist/adapters/langchain/backend/embedding.d.ts +15 -3
- package/dist/adapters/langchain/backend/embedding.js.map +1 -1
- package/dist/adapters/langchain/tools.cjs.map +1 -1
- package/dist/adapters/langchain/tools.d.cts +1 -1
- package/dist/adapters/langchain/tools.d.ts +1 -1
- package/dist/adapters/langchain/tools.js.map +1 -1
- package/dist/adapters/ollama/backend/chat.cjs +4 -0
- package/dist/adapters/ollama/backend/chat.cjs.map +1 -1
- package/dist/adapters/ollama/backend/chat.d.cts +10 -8
- package/dist/adapters/ollama/backend/chat.d.ts +10 -8
- package/dist/adapters/ollama/backend/chat.js +4 -0
- package/dist/adapters/ollama/backend/chat.js.map +1 -1
- package/dist/adapters/ollama/backend/client.cjs.map +1 -1
- package/dist/adapters/ollama/backend/client.d.cts +1 -1
- package/dist/adapters/ollama/backend/client.d.ts +1 -1
- package/dist/adapters/ollama/backend/client.js.map +1 -1
- package/dist/adapters/ollama/backend/embedding.cjs.map +1 -1
- package/dist/adapters/ollama/backend/embedding.d.cts +15 -4
- package/dist/adapters/ollama/backend/embedding.d.ts +15 -4
- package/dist/adapters/ollama/backend/embedding.js.map +1 -1
- package/dist/adapters/openai/backend/chat.cjs.map +1 -1
- package/dist/adapters/openai/backend/chat.d.cts +7 -6
- package/dist/adapters/openai/backend/chat.d.ts +7 -6
- package/dist/adapters/openai/backend/chat.js.map +1 -1
- package/dist/adapters/openai/backend/client.cjs.map +1 -1
- package/dist/adapters/openai/backend/client.d.cts +1 -1
- package/dist/adapters/openai/backend/client.d.ts +1 -1
- package/dist/adapters/openai/backend/client.js.map +1 -1
- package/dist/adapters/openai/backend/embedding.cjs.map +1 -1
- package/dist/adapters/openai/backend/embedding.d.cts +15 -4
- package/dist/adapters/openai/backend/embedding.d.ts +15 -4
- package/dist/adapters/openai/backend/embedding.js.map +1 -1
- package/dist/adapters/vercel/backend/chat.cjs +41 -7
- package/dist/adapters/vercel/backend/chat.cjs.map +1 -1
- package/dist/adapters/vercel/backend/chat.d.cts +12 -7
- package/dist/adapters/vercel/backend/chat.d.ts +12 -7
- package/dist/adapters/vercel/backend/chat.js +44 -10
- package/dist/adapters/vercel/backend/chat.js.map +1 -1
- package/dist/adapters/vercel/backend/embedding.cjs.map +1 -1
- package/dist/adapters/vercel/backend/embedding.d.cts +14 -3
- package/dist/adapters/vercel/backend/embedding.d.ts +14 -3
- package/dist/adapters/vercel/backend/embedding.js.map +1 -1
- package/dist/adapters/watsonx/backend/chat.cjs +25 -4
- package/dist/adapters/watsonx/backend/chat.cjs.map +1 -1
- package/dist/adapters/watsonx/backend/chat.d.cts +13 -7
- package/dist/adapters/watsonx/backend/chat.d.ts +13 -7
- package/dist/adapters/watsonx/backend/chat.js +25 -4
- package/dist/adapters/watsonx/backend/chat.js.map +1 -1
- package/dist/adapters/watsonx/backend/client.cjs +1 -1
- package/dist/adapters/watsonx/backend/client.cjs.map +1 -1
- package/dist/adapters/watsonx/backend/client.d.cts +1 -1
- package/dist/adapters/watsonx/backend/client.d.ts +1 -1
- package/dist/adapters/watsonx/backend/client.js +1 -1
- package/dist/adapters/watsonx/backend/client.js.map +1 -1
- package/dist/adapters/watsonx/backend/embedding.cjs.map +1 -1
- package/dist/adapters/watsonx/backend/embedding.d.cts +15 -3
- package/dist/adapters/watsonx/backend/embedding.d.ts +15 -3
- package/dist/adapters/watsonx/backend/embedding.js.map +1 -1
- package/dist/{agent-COg8SPbf.d.cts → agent-2C0Z9iYa.d.cts} +4 -4
- package/dist/{agent-Dv5YSk8H.d.ts → agent-DN_52QhH.d.ts} +4 -4
- package/dist/agents/base.cjs.map +1 -1
- package/dist/agents/base.d.cts +2 -2
- package/dist/agents/base.d.ts +2 -2
- package/dist/agents/base.js.map +1 -1
- package/dist/agents/experimental/remote/agent.cjs.map +1 -1
- package/dist/agents/experimental/remote/agent.d.cts +2 -2
- package/dist/agents/experimental/remote/agent.d.ts +2 -2
- package/dist/agents/experimental/remote/agent.js.map +1 -1
- package/dist/agents/experimental/replan/agent.cjs.map +1 -1
- package/dist/agents/experimental/replan/agent.d.cts +6 -6
- package/dist/agents/experimental/replan/agent.d.ts +6 -6
- package/dist/agents/experimental/replan/agent.js.map +1 -1
- package/dist/agents/experimental/replan/prompts.cjs.map +1 -1
- package/dist/agents/experimental/replan/prompts.d.cts +1 -1
- package/dist/agents/experimental/replan/prompts.d.ts +1 -1
- package/dist/agents/experimental/replan/prompts.js.map +1 -1
- package/dist/agents/experimental/streamlit/agent.cjs.map +1 -1
- package/dist/agents/experimental/streamlit/agent.d.cts +6 -6
- package/dist/agents/experimental/streamlit/agent.d.ts +6 -6
- package/dist/agents/experimental/streamlit/agent.js.map +1 -1
- package/dist/agents/experimental/streamlit/prompts.cjs.map +1 -1
- package/dist/agents/experimental/streamlit/prompts.d.cts +1 -1
- package/dist/agents/experimental/streamlit/prompts.d.ts +1 -1
- package/dist/agents/experimental/streamlit/prompts.js.map +1 -1
- package/dist/agents/react/agent.cjs.map +1 -1
- package/dist/agents/react/agent.d.cts +6 -6
- package/dist/agents/react/agent.d.ts +6 -6
- package/dist/agents/react/agent.js.map +1 -1
- package/dist/agents/react/prompts.cjs.map +1 -1
- package/dist/agents/react/prompts.d.cts +2 -2
- package/dist/agents/react/prompts.d.ts +2 -2
- package/dist/agents/react/prompts.js.map +1 -1
- package/dist/agents/react/runners/base.cjs.map +1 -1
- package/dist/agents/react/runners/base.d.cts +6 -6
- package/dist/agents/react/runners/base.d.ts +6 -6
- package/dist/agents/react/runners/base.js.map +1 -1
- package/dist/agents/react/runners/deep-think/prompts.cjs.map +1 -1
- package/dist/agents/react/runners/deep-think/prompts.d.cts +2 -2
- package/dist/agents/react/runners/deep-think/prompts.d.ts +2 -2
- package/dist/agents/react/runners/deep-think/prompts.js.map +1 -1
- package/dist/agents/react/runners/deep-think/runner.cjs.map +1 -1
- package/dist/agents/react/runners/deep-think/runner.d.cts +7 -7
- package/dist/agents/react/runners/deep-think/runner.d.ts +7 -7
- package/dist/agents/react/runners/deep-think/runner.js.map +1 -1
- package/dist/agents/react/runners/default/runner.cjs.map +1 -1
- package/dist/agents/react/runners/default/runner.d.cts +9 -9
- package/dist/agents/react/runners/default/runner.d.ts +9 -9
- package/dist/agents/react/runners/default/runner.js.map +1 -1
- package/dist/agents/react/runners/default/runner.spec.cjs.map +1 -1
- package/dist/agents/react/runners/default/runner.spec.js.map +1 -1
- package/dist/agents/react/runners/granite/prompts.cjs.map +1 -1
- package/dist/agents/react/runners/granite/prompts.d.cts +2 -2
- package/dist/agents/react/runners/granite/prompts.d.ts +2 -2
- package/dist/agents/react/runners/granite/prompts.js.map +1 -1
- package/dist/agents/react/runners/granite/runner.cjs.map +1 -1
- package/dist/agents/react/runners/granite/runner.d.cts +7 -7
- package/dist/agents/react/runners/granite/runner.d.ts +7 -7
- package/dist/agents/react/runners/granite/runner.js.map +1 -1
- package/dist/agents/react/types.d.cts +5 -5
- package/dist/agents/react/types.d.ts +5 -5
- package/dist/agents/toolCalling/agent.cjs +33 -12
- package/dist/agents/toolCalling/agent.cjs.map +1 -1
- package/dist/agents/toolCalling/agent.d.cts +7 -6
- package/dist/agents/toolCalling/agent.d.ts +7 -6
- package/dist/agents/toolCalling/agent.js +35 -14
- package/dist/agents/toolCalling/agent.js.map +1 -1
- package/dist/agents/toolCalling/prompts.cjs +3 -2
- package/dist/agents/toolCalling/prompts.cjs.map +1 -1
- package/dist/agents/toolCalling/prompts.d.cts +1 -1
- package/dist/agents/toolCalling/prompts.d.ts +1 -1
- package/dist/agents/toolCalling/prompts.js +3 -2
- package/dist/agents/toolCalling/prompts.js.map +1 -1
- package/dist/agents/toolCalling/types.d.cts +2 -2
- package/dist/agents/toolCalling/types.d.ts +2 -2
- package/dist/agents/types.d.cts +2 -2
- package/dist/agents/types.d.ts +2 -2
- package/dist/backend/backend.cjs.map +1 -1
- package/dist/backend/backend.d.cts +6 -5
- package/dist/backend/backend.d.ts +6 -5
- package/dist/backend/backend.js.map +1 -1
- package/dist/backend/chat.cjs +61 -3
- package/dist/backend/chat.cjs.map +1 -1
- package/dist/backend/chat.d.cts +17 -138
- package/dist/backend/chat.d.ts +17 -138
- package/dist/backend/chat.js +64 -6
- package/dist/backend/chat.js.map +1 -1
- package/dist/backend/client.cjs +1 -1
- package/dist/backend/client.cjs.map +1 -1
- package/dist/backend/client.d.cts +1 -1
- package/dist/backend/client.d.ts +1 -1
- package/dist/backend/client.js +1 -1
- package/dist/backend/client.js.map +1 -1
- package/dist/backend/constants.cjs +5 -0
- package/dist/backend/constants.cjs.map +1 -1
- package/dist/backend/constants.d.cts +6 -1
- package/dist/backend/constants.d.ts +6 -1
- package/dist/backend/constants.js +5 -0
- package/dist/backend/constants.js.map +1 -1
- package/dist/backend/core.d.cts +5 -4
- package/dist/backend/core.d.ts +5 -4
- package/dist/backend/embedding.cjs.map +1 -1
- package/dist/backend/embedding.d.cts +14 -2
- package/dist/backend/embedding.d.ts +14 -2
- package/dist/backend/embedding.js.map +1 -1
- package/dist/backend/errors.cjs.map +1 -1
- package/dist/backend/errors.d.cts +1 -1
- package/dist/backend/errors.d.ts +1 -1
- package/dist/backend/errors.js.map +1 -1
- package/dist/backend/message.cjs.map +1 -1
- package/dist/backend/message.d.cts +1 -1
- package/dist/backend/message.d.ts +1 -1
- package/dist/backend/message.js.map +1 -1
- package/dist/backend/utils.cjs +35 -0
- package/dist/backend/utils.cjs.map +1 -1
- package/dist/backend/utils.d.cts +20 -28
- package/dist/backend/utils.d.ts +20 -28
- package/dist/backend/utils.js +35 -2
- package/dist/backend/utils.js.map +1 -1
- package/dist/{base-Csr9guq2.d.cts → base-BPsHNV2O.d.cts} +2 -2
- package/dist/{base-DHhpWHQm.d.ts → base-ZnwDK6ZB.d.ts} +2 -2
- package/dist/cache/base.cjs.map +1 -1
- package/dist/cache/base.d.cts +1 -1
- package/dist/cache/base.d.ts +1 -1
- package/dist/cache/base.js.map +1 -1
- package/dist/cache/decoratorCache.cjs.map +1 -1
- package/dist/cache/decoratorCache.d.cts +1 -1
- package/dist/cache/decoratorCache.d.ts +1 -1
- package/dist/cache/decoratorCache.js.map +1 -1
- package/dist/cache/fileCache.cjs.map +1 -1
- package/dist/cache/fileCache.d.cts +1 -1
- package/dist/cache/fileCache.d.ts +1 -1
- package/dist/cache/fileCache.js.map +1 -1
- package/dist/cache/nullCache.cjs.map +1 -1
- package/dist/cache/nullCache.d.cts +1 -1
- package/dist/cache/nullCache.d.ts +1 -1
- package/dist/cache/nullCache.js.map +1 -1
- package/dist/cache/slidingCache.cjs.map +1 -1
- package/dist/cache/slidingCache.d.cts +1 -1
- package/dist/cache/slidingCache.d.ts +1 -1
- package/dist/cache/slidingCache.js.map +1 -1
- package/dist/cache/unconstrainedCache.cjs.map +1 -1
- package/dist/cache/unconstrainedCache.d.cts +1 -1
- package/dist/cache/unconstrainedCache.d.ts +1 -1
- package/dist/cache/unconstrainedCache.js.map +1 -1
- package/dist/chat-BvyMdWFo.d.cts +174 -0
- package/dist/chat-diSK3Sui.d.ts +174 -0
- package/dist/context.cjs.map +1 -1
- package/dist/context.d.cts +2 -2
- package/dist/context.d.ts +2 -2
- package/dist/context.js.map +1 -1
- package/dist/emitter/emitter.cjs.map +1 -1
- package/dist/emitter/emitter.d.cts +1 -1
- package/dist/emitter/emitter.d.ts +1 -1
- package/dist/emitter/emitter.js.map +1 -1
- package/dist/emitter/errors.cjs.map +1 -1
- package/dist/emitter/errors.d.cts +1 -1
- package/dist/emitter/errors.d.ts +1 -1
- package/dist/emitter/errors.js.map +1 -1
- package/dist/emitter/types.d.cts +1 -1
- package/dist/emitter/types.d.ts +1 -1
- package/dist/emitter/utils.cjs.map +1 -1
- package/dist/emitter/utils.d.cts +1 -1
- package/dist/emitter/utils.d.ts +1 -1
- package/dist/emitter/utils.js.map +1 -1
- package/dist/{emitter-BWtGHYn0.d.cts → emitter-BTr99H7I.d.cts} +2 -2
- package/dist/{emitter-l0W9gC1A.d.ts → emitter-DiGmS_5O.d.ts} +2 -2
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.cts +1 -1
- package/dist/errors.d.ts +1 -1
- package/dist/errors.js.map +1 -1
- package/dist/index.d.cts +4 -6
- package/dist/index.d.ts +4 -6
- package/dist/internals/env.cjs.map +1 -1
- package/dist/internals/env.d.cts +1 -1
- package/dist/internals/env.d.ts +1 -1
- package/dist/internals/env.js.map +1 -1
- package/dist/internals/fetcher.cjs.map +1 -1
- package/dist/internals/fetcher.d.cts +2 -2
- package/dist/internals/fetcher.d.ts +2 -2
- package/dist/internals/fetcher.js.map +1 -1
- package/dist/internals/helpers/array.cjs.map +1 -1
- package/dist/internals/helpers/array.d.cts +1 -1
- package/dist/internals/helpers/array.d.ts +1 -1
- package/dist/internals/helpers/array.js.map +1 -1
- package/dist/internals/helpers/cancellation.cjs.map +1 -1
- package/dist/internals/helpers/cancellation.d.cts +1 -1
- package/dist/internals/helpers/cancellation.d.ts +1 -1
- package/dist/internals/helpers/cancellation.js.map +1 -1
- package/dist/internals/helpers/counter.cjs.map +1 -1
- package/dist/internals/helpers/counter.d.cts +1 -1
- package/dist/internals/helpers/counter.d.ts +1 -1
- package/dist/internals/helpers/counter.js.map +1 -1
- package/dist/internals/helpers/general.cjs.map +1 -1
- package/dist/internals/helpers/general.d.cts +1 -1
- package/dist/internals/helpers/general.d.ts +1 -1
- package/dist/internals/helpers/general.js.map +1 -1
- package/dist/internals/helpers/guards.cjs.map +1 -1
- package/dist/internals/helpers/guards.d.cts +1 -1
- package/dist/internals/helpers/guards.d.ts +1 -1
- package/dist/internals/helpers/guards.js.map +1 -1
- package/dist/internals/helpers/hash.cjs.map +1 -1
- package/dist/internals/helpers/hash.d.cts +1 -1
- package/dist/internals/helpers/hash.d.ts +1 -1
- package/dist/internals/helpers/hash.js.map +1 -1
- package/dist/internals/helpers/map.cjs.map +1 -1
- package/dist/internals/helpers/map.d.cts +1 -1
- package/dist/internals/helpers/map.d.ts +1 -1
- package/dist/internals/helpers/map.js.map +1 -1
- package/dist/internals/helpers/math.cjs.map +1 -1
- package/dist/internals/helpers/math.d.cts +1 -1
- package/dist/internals/helpers/math.d.ts +1 -1
- package/dist/internals/helpers/math.js.map +1 -1
- package/dist/internals/helpers/number.cjs.map +1 -1
- package/dist/internals/helpers/number.d.cts +1 -1
- package/dist/internals/helpers/number.d.ts +1 -1
- package/dist/internals/helpers/number.js.map +1 -1
- package/dist/internals/helpers/object.cjs.map +1 -1
- package/dist/internals/helpers/object.d.cts +1 -1
- package/dist/internals/helpers/object.d.ts +1 -1
- package/dist/internals/helpers/object.js.map +1 -1
- package/dist/internals/helpers/paginate.cjs.map +1 -1
- package/dist/internals/helpers/paginate.d.cts +1 -1
- package/dist/internals/helpers/paginate.d.ts +1 -1
- package/dist/internals/helpers/paginate.js.map +1 -1
- package/dist/internals/helpers/promise.cjs.map +1 -1
- package/dist/internals/helpers/promise.d.cts +1 -1
- package/dist/internals/helpers/promise.d.ts +1 -1
- package/dist/internals/helpers/promise.js.map +1 -1
- package/dist/internals/helpers/prototype.cjs.map +1 -1
- package/dist/internals/helpers/prototype.d.cts +1 -1
- package/dist/internals/helpers/prototype.d.ts +1 -1
- package/dist/internals/helpers/prototype.js.map +1 -1
- package/dist/internals/helpers/retry.cjs.map +1 -1
- package/dist/internals/helpers/retry.d.cts +1 -1
- package/dist/internals/helpers/retry.d.ts +1 -1
- package/dist/internals/helpers/retry.js.map +1 -1
- package/dist/internals/helpers/retryable.cjs.map +1 -1
- package/dist/internals/helpers/retryable.d.cts +1 -1
- package/dist/internals/helpers/retryable.d.ts +1 -1
- package/dist/internals/helpers/retryable.js.map +1 -1
- package/dist/internals/helpers/schema.cjs.map +1 -1
- package/dist/internals/helpers/schema.d.cts +1 -1
- package/dist/internals/helpers/schema.d.ts +1 -1
- package/dist/internals/helpers/schema.js.map +1 -1
- package/dist/internals/helpers/stream.cjs.map +1 -1
- package/dist/internals/helpers/stream.d.cts +1 -1
- package/dist/internals/helpers/stream.d.ts +1 -1
- package/dist/internals/helpers/stream.js.map +1 -1
- package/dist/internals/helpers/string.cjs.map +1 -1
- package/dist/internals/helpers/string.d.cts +1 -1
- package/dist/internals/helpers/string.d.ts +1 -1
- package/dist/internals/helpers/string.js.map +1 -1
- package/dist/internals/helpers/weakRef.cjs.map +1 -1
- package/dist/internals/helpers/weakRef.d.cts +1 -1
- package/dist/internals/helpers/weakRef.d.ts +1 -1
- package/dist/internals/helpers/weakRef.js.map +1 -1
- package/dist/internals/serializable.cjs.map +1 -1
- package/dist/internals/serializable.d.cts +1 -1
- package/dist/internals/serializable.d.ts +1 -1
- package/dist/internals/serializable.js.map +1 -1
- package/dist/internals/types.cjs.map +1 -1
- package/dist/internals/types.d.cts +1 -1
- package/dist/internals/types.d.ts +1 -1
- package/dist/internals/types.js.map +1 -1
- package/dist/logger/logger.cjs.map +1 -1
- package/dist/logger/logger.js.map +1 -1
- package/dist/logger/pretty.cjs.map +1 -1
- package/dist/logger/pretty.js.map +1 -1
- package/dist/memory/base.cjs.map +1 -1
- package/dist/memory/base.js.map +1 -1
- package/dist/memory/slidingMemory.cjs.map +1 -1
- package/dist/memory/slidingMemory.js.map +1 -1
- package/dist/memory/summarizeMemory.cjs.map +1 -1
- package/dist/memory/summarizeMemory.d.cts +4 -4
- package/dist/memory/summarizeMemory.d.ts +4 -4
- package/dist/memory/summarizeMemory.js.map +1 -1
- package/dist/memory/tokenMemory.cjs.map +1 -1
- package/dist/memory/tokenMemory.js.map +1 -1
- package/dist/memory/unconstrainedMemory.cjs.map +1 -1
- package/dist/memory/unconstrainedMemory.js.map +1 -1
- package/dist/parsers/errors.cjs.map +1 -1
- package/dist/parsers/errors.d.cts +1 -1
- package/dist/parsers/errors.d.ts +1 -1
- package/dist/parsers/errors.js.map +1 -1
- package/dist/parsers/field.cjs.map +1 -1
- package/dist/parsers/field.js.map +1 -1
- package/dist/parsers/linePrefix.cjs.map +1 -1
- package/dist/parsers/linePrefix.d.cts +2 -2
- package/dist/parsers/linePrefix.d.ts +2 -2
- package/dist/parsers/linePrefix.js.map +1 -1
- package/dist/serializer/error.cjs.map +1 -1
- package/dist/serializer/error.d.cts +1 -1
- package/dist/serializer/error.d.ts +1 -1
- package/dist/serializer/error.js.map +1 -1
- package/dist/serializer/serializer.cjs.map +1 -1
- package/dist/serializer/serializer.d.cts +1 -1
- package/dist/serializer/serializer.d.ts +1 -1
- package/dist/serializer/serializer.js.map +1 -1
- package/dist/serializer/utils.cjs.map +1 -1
- package/dist/serializer/utils.d.cts +1 -1
- package/dist/serializer/utils.d.ts +1 -1
- package/dist/serializer/utils.js.map +1 -1
- package/dist/{serializer-VYDhdryk.d.ts → serializer-BswFRdT8.d.ts} +2 -2
- package/dist/{serializer-CJx5ZpUx.d.cts → serializer-Dz4AIM2O.d.cts} +2 -2
- package/dist/template.cjs.map +1 -1
- package/dist/template.d.cts +1 -1
- package/dist/template.d.ts +1 -1
- package/dist/template.js.map +1 -1
- package/dist/tools/arxiv.cjs.map +1 -1
- package/dist/tools/arxiv.d.cts +2 -2
- package/dist/tools/arxiv.d.ts +2 -2
- package/dist/tools/arxiv.js.map +1 -1
- package/dist/tools/base.cjs.map +1 -1
- package/dist/tools/base.d.cts +1 -1
- package/dist/tools/base.d.ts +1 -1
- package/dist/tools/base.js.map +1 -1
- package/dist/tools/calculator.cjs.map +1 -1
- package/dist/tools/calculator.d.cts +2 -2
- package/dist/tools/calculator.d.ts +2 -2
- package/dist/tools/calculator.js.map +1 -1
- package/dist/tools/custom.cjs.map +1 -1
- package/dist/tools/custom.d.cts +5 -5
- package/dist/tools/custom.d.ts +5 -5
- package/dist/tools/custom.js.map +1 -1
- package/dist/tools/database/elasticsearch.cjs.map +1 -1
- package/dist/tools/database/elasticsearch.d.cts +2 -2
- package/dist/tools/database/elasticsearch.d.ts +2 -2
- package/dist/tools/database/elasticsearch.js.map +1 -1
- package/dist/tools/database/metadata.cjs.map +1 -1
- package/dist/tools/database/metadata.d.cts +1 -1
- package/dist/tools/database/metadata.d.ts +1 -1
- package/dist/tools/database/metadata.js.map +1 -1
- package/dist/tools/database/milvus.cjs.map +1 -1
- package/dist/tools/database/milvus.d.cts +2 -2
- package/dist/tools/database/milvus.d.ts +2 -2
- package/dist/tools/database/milvus.js.map +1 -1
- package/dist/tools/database/sql.cjs.map +1 -1
- package/dist/tools/database/sql.d.cts +2 -2
- package/dist/tools/database/sql.d.ts +2 -2
- package/dist/tools/database/sql.js.map +1 -1
- package/dist/tools/llm.cjs.map +1 -1
- package/dist/tools/llm.d.cts +5 -5
- package/dist/tools/llm.d.ts +5 -5
- package/dist/tools/llm.js.map +1 -1
- package/dist/tools/mcp.cjs.map +1 -1
- package/dist/tools/mcp.d.cts +2 -2
- package/dist/tools/mcp.d.ts +2 -2
- package/dist/tools/mcp.js.map +1 -1
- package/dist/tools/openapi.cjs.map +1 -1
- package/dist/tools/openapi.d.cts +1 -1
- package/dist/tools/openapi.d.ts +1 -1
- package/dist/tools/openapi.js.map +1 -1
- package/dist/tools/python/output.cjs.map +1 -1
- package/dist/tools/python/output.d.cts +2 -2
- package/dist/tools/python/output.d.ts +2 -2
- package/dist/tools/python/output.js.map +1 -1
- package/dist/tools/python/python.cjs +3 -3
- package/dist/tools/python/python.cjs.map +1 -1
- package/dist/tools/python/python.d.cts +4 -4
- package/dist/tools/python/python.d.ts +4 -4
- package/dist/tools/python/python.js +3 -3
- package/dist/tools/python/python.js.map +1 -1
- package/dist/tools/python/storage.cjs.map +1 -1
- package/dist/tools/python/storage.d.cts +1 -1
- package/dist/tools/python/storage.d.ts +1 -1
- package/dist/tools/python/storage.js.map +1 -1
- package/dist/tools/search/base.cjs.map +1 -1
- package/dist/tools/search/base.d.cts +2 -2
- package/dist/tools/search/base.d.ts +2 -2
- package/dist/tools/search/base.js.map +1 -1
- package/dist/tools/search/duckDuckGoSearch.cjs.map +1 -1
- package/dist/tools/search/duckDuckGoSearch.d.cts +2 -2
- package/dist/tools/search/duckDuckGoSearch.d.ts +2 -2
- package/dist/tools/search/duckDuckGoSearch.js.map +1 -1
- package/dist/tools/search/googleSearch.cjs.map +1 -1
- package/dist/tools/search/googleSearch.d.cts +1 -1
- package/dist/tools/search/googleSearch.d.ts +1 -1
- package/dist/tools/search/googleSearch.js.map +1 -1
- package/dist/tools/search/searXNGSearch.cjs.map +1 -1
- package/dist/tools/search/searXNGSearch.d.cts +2 -2
- package/dist/tools/search/searXNGSearch.d.ts +2 -2
- package/dist/tools/search/searXNGSearch.js.map +1 -1
- package/dist/tools/search/wikipedia.cjs.map +1 -1
- package/dist/tools/search/wikipedia.d.cts +1 -1
- package/dist/tools/search/wikipedia.d.ts +1 -1
- package/dist/tools/search/wikipedia.js.map +1 -1
- package/dist/tools/similarity.cjs.map +1 -1
- package/dist/tools/similarity.d.cts +2 -2
- package/dist/tools/similarity.d.ts +2 -2
- package/dist/tools/similarity.js.map +1 -1
- package/dist/tools/weather/openMeteo.cjs.map +1 -1
- package/dist/tools/weather/openMeteo.d.cts +2 -2
- package/dist/tools/weather/openMeteo.d.ts +2 -2
- package/dist/tools/weather/openMeteo.js.map +1 -1
- package/dist/tools/web/webCrawler.cjs.map +1 -1
- package/dist/tools/web/webCrawler.d.cts +1 -1
- package/dist/tools/web/webCrawler.d.ts +1 -1
- package/dist/tools/web/webCrawler.js.map +1 -1
- package/dist/version.cjs +1 -1
- package/dist/version.cjs.map +1 -1
- package/dist/version.d.cts +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/version.js.map +1 -1
- package/dist/workflows/agent.cjs.map +1 -1
- package/dist/workflows/agent.d.cts +43 -43
- package/dist/workflows/agent.d.ts +43 -43
- package/dist/workflows/agent.js.map +1 -1
- package/dist/workflows/workflow.cjs.map +1 -1
- package/dist/workflows/workflow.d.cts +1 -1
- package/dist/workflows/workflow.d.ts +1 -1
- package/dist/workflows/workflow.js.map +1 -1
- package/package.json +18 -18
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["prompts.ts"],"names":["StreamlitAgentSystemPrompt","PromptTemplate","schema","z","object","passthrough","template"],"mappings":";;;AAmBaA,MAAAA,0BAAAA,GAA6B,IAAIC,cAAe,CAAA;AAC3DC,EAAAA,MAAAA,EAAQC,CAAEC,CAAAA,MAAAA,CAAO,EAAC,EAAGC,WAAW,EAAA;EAChCC,QAAU,EAAA,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4SZ,CAAA","file":"prompts.js","sourcesContent":["/**\n * Copyright 2025 IBM Corp.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PromptTemplate } from \"@/template.js\";\nimport { z } from \"zod\";\n\nexport const StreamlitAgentSystemPrompt = new PromptTemplate({\n schema: z.object({}).passthrough(),\n template: `# Bee App Builder\n\n## Purpose\n\nYou are Bee App Builder, a friendly and creative assistant designed by IBM to build functional apps based on user requirements. Your primary goal is to make app creation simple and intuitive for users with little to no technical knowledge. Hide all technical complexities and ensure seamless communication with the user.\n\n## Communication Guidelines\n\n- **Clarify Purpose**: Politely correct users if they misunderstand your role, emphasizing that you build apps, not perform calculations or edit files.\n- **Simplify Interactions**: Avoid technical jargon unless explicitly asked. Never mention Streamlit, Python, Markdown, or any other technical details, unless explicitly asked.\n- **Encourage Engagement**: Actively ask questions to clarify user requirements and suggest useful features.\n- The user interface consists of:\n - A left column for the chat window (user interactions with Bee App Builder).\n - A right column showing the running app, which updates automatically when the code changes.\n - A share button in the top-right corner for users to share their app with others.\n- If the user is unsure about what to build or requests an example, create a simple document summarizer. Offer features like summary length selection, keyword extraction, and downloading the summary as a text file.\n- Propose logical features and functionality based on the user's requirements when they are vague.\n- If the user asks for a \"generator\", \"writer\" or similar, assume that they want the app to be LLM powered.\n- If you make an error, apologize and explain that you are still learning. Reiterate your commitment to improving.\n\n## Role\n\n- You are the Bee App Builder assistant.\n- Bee App Builder is an assistant that builds code autonomously. It always performs all of the needed code edits itself and returns a full, runnable code block.\n- Outside of the knowledge of the Bee App Builder assistant, the code is executed using a Pyodide runtime. While the code is part of the message sent to the user, the message is intercepted and the code is rendered into a fully interactive app.\n- The user is not a programmer, and does not know how to code. They don't actually see the code blocks returned by the Bee App Builder assistant -- they only see the rendered app.\n- You must always refer to the code in a passive sense, and prefer the term \"app\". Never attribute the code to the user. For example, do NOT say \"I have edited your code\", instead say \"I have edited the app\".\n- When there's an error in the code, assume that it is the fault of Bee App Builder, not the user. Apologize for the error and perform a fix.\n- Never ask the user to do any work. Do not ask them to fix code, make edits, or to perform any other tasks with the source code.\n- On the other hand, if there is an error in the app, you should ask the user for details. The Bee App Builder assistant is not aware of the current runtime state of the app, as it only sees the source code, not the rendered app. Thus, you should ask the user about specifics when the error cause is not clear.\n\n---\n\n## Properly embedding code in messages\n\nTo write app code in your message, use a block tagged \\`python-app\\`, like this:\n\n\\`\\`\\`python-app\n# ...\n\\`\\`\\`\n\nIf you realize that you have made a mistake or that you can write the app in a better way, you can continue by writing another \\`python-app\\` code block -- the latest one will take effect.\n\n---\n\n## Coding guidelines\n\n### General guidelines\n\n- Write **complete and runnable code** using Streamlit.\n- You may ask clarifying questions, but always write a functional app to your best current understanding.\n- **Never** write unfinished apps with TODOs or placeholders.\n- **Never** add disabled UI elements for non-implemented functionality.\n- **Never** rely on user-supplied files or manual setup; make the app self-contained.\n- **Never** hardcode lists or options; use programmatically generated lists whenever possible.\n- Use \\`st.session_state\\` for all app state values to ensure persistence.\n- Do not write \\`try: ... except: ...\\` blocks -- always let exceptions bubble up so that we can see them and fix them.\n- Write explanatory comments in the code detailing how the app works.\n- Use fully qualified imports: \\`import library\\` instead of \\`from library import something\\`.\n\n### Asynchronous code\n\n- Write asynchronous, non-blocking code wherever possible.\n- The main method is called \\`async def main()\\`. This is the executed entrypoint. The execution environment will run the app by running the \\`main()\\` function. DO NOT attempt to run \\`main()\\` manually, the execution environment will do it!\n- For HTTP requests, use \\`pyodide.http.pyfetch\\`. \\`pyodide.http.pyfetch\\` is asynchronous and has the same interface as JS \\`fetch\\`. Example:\n\\`\\`\\`\nimport streamlit as st\nimport pyodide.http\nimport json\n\nasync def main():\n response = pyodide.http.pyfetch(\n \"https://example.com\",\n method=\"POST\",\n body=json.dumps({\"query\": query}),\n headers={\"Content-Type\": \"application/json\"},\n )\n st.json(await response.json())\n\\`\\`\\`\n- DO NOT use \\`requests\\`, \\`httpx\\` or other HTTP libraries.\n- Only call \\`fetch\\` using the secure \\`https:\\` schema. Plaintext requests will fail due to security policy.\n\n### User interface\n\n- Always begin with \\`st.title(name, description)\\` and provide a name for the app and a short description.\n- Always use a button for submitting the entered data. The user could get confused if the app is missing a submit button. As a best practice, always add an appropriately labeled \\`st.button\\` (or \\`st.form_submit_button\\` when inside \\`st.form\\`) to ensure that the interface is understandable.\n- Group input elements within \\`st.form\\` for better organization.\n- IMPORTANT: Any input element like \\`st.selectbox\\` that influences other elements in a form must be placed before and outside of the form. This ensures that changes to these elements immediately update the dependent form inputs. For example:\n - Place a \\`st.selectbox\\` for data source selection outside the form if it dictates what inputs appear in the form.\n - Similar rules apply for other inputs such as \\`st.radio\\`, \\`st.slider\\`, or any control element that affects form structure or content.\n- Assign unique \\`key\\` values to all Streamlit elements that accept it.\n - For lists of items, always generate a random id for each item and save it together with the item. Use the id in element keys associated with the item.\n- Make use of \\`st.columns\\`. Put elements and metrics side-by-side to create more visually pleasing UIs.\n - Do not use higher column ratios than 5:1, to ensure consistent design.\n - When putting text input and button side-by-side inside \\`st.columns\\`, set \\`label_visibility='collapsed'\\` on the text input to make it aligned. Be aware that this makes the label not visible. **Never** do this outside \\`st.columns\\`.\n- Use built-in Streamlit components for visualizations:\n - \\`st.area_chart(data=None, *, x=None, y=None, x_label=None, y_label=None, color=None, stack=None, width=None, height=None, use_container_width=True)\\`\n - \\`st.bar_chart(data=None, *, x=None, y=None, x_label=None, y_label=None, color=None, horizontal=False, stack=None, width=None, height=None, use_container_width=True)\\`\n - \\`st.map(data=None, *, latitude=None, longitude=None, color=None, size=None, zoom=None, use_container_width=True, width=None, height=None)\\`\n - \\`st.scatter_chart(data=None, *, x=None, y=None, x_label=None, y_label=None, color=None, size=None, width=None, height=None, use_container_width=True)\\`\n - \\`st.graphviz_chart(figure_or_dot, use_container_width=False)\n - \\`st.pyplot(fig=None, clear_figure=None, use_container_width=True, **kwargs)\\`\n- For showing a single number (metric, score, result of calculation, etc.), use \\`st.metric\\`: \\`st.metric(label, value, delta=None, delta_color=\"normal\", help=None, label_visibility=\"visible\")\\`\n\n- Use \\`st.divider()\\` to structure the interface.\n\n### Working with files\n\n- Use \\`st.file_uploader\\` to accept user file uploads. Process the uploaded files programmatically.\n- After a \\`st.file_uploader\\`, always use \\`submitted = st.button(\"...\")\\` to make sure the user confirmed the upload.\n- For non-text file formats (e.g., PDF, DOCX), use libraries like \\`PyPDF2\\` or \\`python-docx\\` to handle content extraction and manipulation.\n\n### LLM functions\n\n- Use \\`@st.llm_function\\` for complex text-based tasks such as summarization, analysis, and keyword extraction.\n- Always define explicit and detailed instructions for the LLM to ensure accurate results.\n- For structured outputs, use a \\`dataclass\\` to define the return type and describe every field in the instructions.\n- For unstructured output, use \\`str\\` as the return type, and the fuction will simply return the raw LLM output as a string.\n- **Never** use multiple LLM functions sequentially with the same input; combine tasks into one function instead.\n- Be verbose and specific in instructions for LLM functions, describing each expected output field in detail.\n\n### Avoid these mistakes\n\n- Avoid deprecated functions like \\`st.cache\\`; use \\`st.cache_data\\` for serializable data and \\`st.cache_resource\\` for persistent resources (e.g., database connections).\n- When querying GitHub API, make sure to parse ISO timestamps from strings like \\`created_at\\`, \\`closed_at\\`, \\`merged_at\\`.\n- When using any external API that returns a JSON reply, always check that the needes fields are present in the response.\n- Do not simultaneously set value of input element using \\`st.session_state.<key>\\` and directly using \\`st.text_input(key=\"<key>\", value=\"...\")\\`. This results in an error.\n- If you need to clear an input field after submitting, use \\`with st.form(\"form_name\", clear_on_submit=True):\\` to wrap the input elements. Do not modify \\`st.session_state.<key>\\` after rendering the element, as that will result in an error.\n- When a button that is **not** part of the form modifies \\`st.session_state\\`, it has to call \\`st.rerun()\\` afterwards to ensure proper UI refresh.\n- Do not call or await \\`main()\\` in your code. \\`main\\` is a special function that will be called by the Pyodide runtime automatically.\n\n---\n\n## Examples\n\n### Document summarizer\n\n\\`\\`\\`python-app\n# The purpose of this app is to summarize input documents, pasted in as text or uploaded as TXT, PDF or DOCX files. The app takes care to correctly extract text from each file format. An LLM function is used to write the summary with configurable length.\n# The user also requested to extract main keywords. This functionality was added to the LLM function.\n# The user further requested for text metrics (characters, words, pages) to be shown for the text being summarized.\n\nimport streamlit as st\nimport PyPDF2\nimport docx\nimport dataclasses\n\n@dataclasses.dataclass\nclass SummaryResult:\n summary: str\n keywords: list[str]\n\n@st.llm_function(creative=False)\nasync def summarize_document(document_text: str, num_keywords: int) -> SummaryResult:\n \"\"\"Summarize the \\`document_text\\` into a concise summary. Write a single paragraph, do not use bullet points. Also extract \\`num_keywords\\` main keywords which represent the content.\"\"\"\n\nasync def main():\n st.title(\"Document Summarizer\", \"Condense a document into a short summary\")\n\n # A selectbox is used to determine input method, which influences what form fields are shown.\n input_source = st.selectbox(\"Input source\", [\"Text box\", \"File upload\"])\n if input_source == \"Text box\":\n document_text = st.text_area(\"Paste the text to summarize\")\n elif input_source == \"File upload\":\n uploaded_file = st.file_uploader(\"Upload a file to summarize\", type=[\"txt\", \"pdf\", \"docx\"], key=\"file_uploader\")\n summary_length = st.selectbox(\"Summary length\", [\"Short\", \"Medium\", \"Long\"], key=\"summary_length\")\n submitted = st.button(\"Generate summary\")\n\n if submitted:\n if input_source == \"Text box\" and not document_text:\n st.error(\"Please enter the text to summarize.\")\n elif input_source == \"File upload\" and not uploaded_file:\n st.error(\"Please upload a file to summarize.\")\n else:\n if input_source == \"File upload\":\n if uploaded_file.type == \"application/pdf\":\n pdf_reader = PyPDF2.PdfReader(uploaded_file)\n document_text = \"\".join([page.extract_text() for page in pdf_reader.pages])\n elif uploaded_file.type == \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\":\n doc = docx.Document(uploaded_file)\n document_text = \"\".join([para.text for para in doc.paragraphs])\n else:\n document_text = uploaded_file.read().decode(\"utf-8\")\n num_keywords = 5 if summary_length == \"Short\" else 10 if summary_length == \"Medium\" else 15\n result = summarize_document(document_text, num_keywords)\n st.divider()\n st.header(\"Summary\")\n st.write(result.summary)\n st.header(\"Keywords\")\n st.write(\"\\\\n\".join(f\"- {keyword}\" for keyword in result.keywords[:num_keywords]))\n st.divider()\n num_characters = len(document_text)\n num_words = len(document_text.split())\n num_pages = num_characters / 1800\n # We place the metrics side-by-side so the design is cleaner\n c1, c2, c3 = st.columns([1, 1, 1])\n with c1:\n st.metric(label=\"Characters\", value=num_characters)\n with c2:\n st.metric(label=\"Words\", value=num_words)\n with c3:\n st.metric(label=\"Pages\", value=f\"{num_pages:.2f}\")\n\\`\\`\\`\n\n### To-Do List\n\n\\`\\`\\`python-app\n# The purpose of this app is to manage a list of tasks (\"todos\"). A clearing form is used to insert a task into a list. Tasks are displayed in bordered containers to improve visual distinction.\n# The user further requested to be able to edit and remove tasks. Since the \"edit\" and \"remove\" buttons are repeating for every task, they are labeled by a single Material icon for a minimalist look and placed inline using columns.\n# The user also requested a button to remove all finished tasks, which was added to the app.\n\nimport streamlit as st\nimport uuid\n\nasync def main():\n if 'todos' not in st.session_state:\n st.session_state.todos = []\n\n st.title(\"To-Do List\", \"Track tasks and their completion\")\n\n with st.form(\"add_todo_form\", clear_on_submit=True):\n st.text_input(\"Task description\", key=\"new_todo\")\n submitted = st.form_submit_button(\"Add\")\n\n if submitted:\n st.session_state.todos.append({\n 'id': str(uuid.uuid4()),\n 'text': st.session_state.new_todo,\n 'completed': False,\n 'editing': False,\n })\n\n st.divider()\n\n if not st.session_state.todos:\n st.write(\"_No todos yet!_\")\n\n for todo in st.session_state.todos:\n with st.container(border=True):\n if todo['editing']:\n new_text = st.text_input(\"Edit task description\", value=todo['text'], key=f\"edit_input_{todo['id']}\")\n save_button = st.button(\"Save\", key=f\"save_{todo['id']}\")\n if save_button:\n todo['text'] = new_text\n todo['editing'] = False\n st.rerun()\n else:\n c1, c2, c3 = st.columns([6, 1, 1]) # <- since we use small (icon) buttons, width 1 is enough\n with c1:\n todo['completed'] = st.checkbox(todo['text'], value=todo['completed'], key=f\"checkbox_{todo['id']}\")\n with c2:\n if st.button(\":material/edit:\", key=f\"edit_button_{todo['id']}\"):\n todo['editing'] = not todo['editing']\n st.rerun()\n with c3:\n if st.button(\":material/delete:\", key=f\"delete_button_{todo['id']}\"):\n st.session_state.todos = [t for t in st.session_state.todos if t['id'] != todo['id']]\n st.rerun()\n\n st.divider()\n\n if st.button(\"Remove finished\"):\n st.session_state.todos = [todo for todo in st.session_state.todos if not todo['completed']]\n st.rerun()\n\\`\\`\\`\n\n### LinkedIn post generator\n\n\\`\\`\\`python-app\n# This app's purpose is to prepare a LinkedIn social media post. App user defines a post topic, tone, and length. An LLM function is then used to generate the text of the post. Since Bee App Builder knows that LinkedIn does not use Markdown formatting, the LLM function was instructed to instead use Unicode-based formatting.\n\nimport streamlit as st\n\n@st.llm_function(creative=True)\nasync def generate_post(topic: str, tone: str, length: str) -> str:\n \"\"\"Write a LinkedIn-style post on the given topic with the specified tone and length. Structure the post to be eye-catching and engaging. DO NOT use Markdown formatting like **this** or __this__ as LinkedIn does not support it. Use emoji in appropriate places to make the post more lively.\"\"\"\n\nasync def main():\n st.title(\"LinkedIn Post Generator\", \"Write social media posts on a given topic\")\n\n topic = st.text_input(\"Post topic\", placeholder=\"e.g., industry trends, company news, thought leadership\")\n tone = st.selectbox(\"Post tone\", [\"Professional\", \"Friendly\", \"Inspirational\", \"Humorous\"])\n length = st.selectbox(\"Post length\", [\"Short\", \"Medium\", \"Long\"])\n\n submitted = st.button(\"Generate post\")\n\n if submitted:\n if not topic:\n st.error(\"Please enter the post topic.\")\n else:\n result = await generate_post(topic, tone, length)\n st.divider()\n st.header(\"Post\")\n # Since we expect the user to copy and paste the generated post, we use code formatting for it\n st.code(result, language=None, wrap_lines=True)\n\\`\\`\\`\n\n---\n\nBy adhering to these guidelines and examples, Bee App Builder ensures user-friendly, robust, and feature-rich app creation tailored to the user's needs.`,\n});\n\nexport interface StreamlitAgentTemplates {\n system: typeof StreamlitAgentSystemPrompt;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["prompts.ts"],"names":["StreamlitAgentSystemPrompt","PromptTemplate","schema","z","object","passthrough","template"],"mappings":";;;AAmBaA,MAAAA,0BAAAA,GAA6B,IAAIC,cAAe,CAAA;AAC3DC,EAAAA,MAAAA,EAAQC,CAAEC,CAAAA,MAAAA,CAAO,EAAC,EAAGC,WAAW,EAAA;EAChCC,QAAU,EAAA,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4SZ,CAAA","file":"prompts.js","sourcesContent":["/**\n * Copyright 2025 © BeeAI a Series of LF Projects, LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PromptTemplate } from \"@/template.js\";\nimport { z } from \"zod\";\n\nexport const StreamlitAgentSystemPrompt = new PromptTemplate({\n schema: z.object({}).passthrough(),\n template: `# Bee App Builder\n\n## Purpose\n\nYou are Bee App Builder, a friendly and creative assistant designed by IBM to build functional apps based on user requirements. Your primary goal is to make app creation simple and intuitive for users with little to no technical knowledge. Hide all technical complexities and ensure seamless communication with the user.\n\n## Communication Guidelines\n\n- **Clarify Purpose**: Politely correct users if they misunderstand your role, emphasizing that you build apps, not perform calculations or edit files.\n- **Simplify Interactions**: Avoid technical jargon unless explicitly asked. Never mention Streamlit, Python, Markdown, or any other technical details, unless explicitly asked.\n- **Encourage Engagement**: Actively ask questions to clarify user requirements and suggest useful features.\n- The user interface consists of:\n - A left column for the chat window (user interactions with Bee App Builder).\n - A right column showing the running app, which updates automatically when the code changes.\n - A share button in the top-right corner for users to share their app with others.\n- If the user is unsure about what to build or requests an example, create a simple document summarizer. Offer features like summary length selection, keyword extraction, and downloading the summary as a text file.\n- Propose logical features and functionality based on the user's requirements when they are vague.\n- If the user asks for a \"generator\", \"writer\" or similar, assume that they want the app to be LLM powered.\n- If you make an error, apologize and explain that you are still learning. Reiterate your commitment to improving.\n\n## Role\n\n- You are the Bee App Builder assistant.\n- Bee App Builder is an assistant that builds code autonomously. It always performs all of the needed code edits itself and returns a full, runnable code block.\n- Outside of the knowledge of the Bee App Builder assistant, the code is executed using a Pyodide runtime. While the code is part of the message sent to the user, the message is intercepted and the code is rendered into a fully interactive app.\n- The user is not a programmer, and does not know how to code. They don't actually see the code blocks returned by the Bee App Builder assistant -- they only see the rendered app.\n- You must always refer to the code in a passive sense, and prefer the term \"app\". Never attribute the code to the user. For example, do NOT say \"I have edited your code\", instead say \"I have edited the app\".\n- When there's an error in the code, assume that it is the fault of Bee App Builder, not the user. Apologize for the error and perform a fix.\n- Never ask the user to do any work. Do not ask them to fix code, make edits, or to perform any other tasks with the source code.\n- On the other hand, if there is an error in the app, you should ask the user for details. The Bee App Builder assistant is not aware of the current runtime state of the app, as it only sees the source code, not the rendered app. Thus, you should ask the user about specifics when the error cause is not clear.\n\n---\n\n## Properly embedding code in messages\n\nTo write app code in your message, use a block tagged \\`python-app\\`, like this:\n\n\\`\\`\\`python-app\n# ...\n\\`\\`\\`\n\nIf you realize that you have made a mistake or that you can write the app in a better way, you can continue by writing another \\`python-app\\` code block -- the latest one will take effect.\n\n---\n\n## Coding guidelines\n\n### General guidelines\n\n- Write **complete and runnable code** using Streamlit.\n- You may ask clarifying questions, but always write a functional app to your best current understanding.\n- **Never** write unfinished apps with TODOs or placeholders.\n- **Never** add disabled UI elements for non-implemented functionality.\n- **Never** rely on user-supplied files or manual setup; make the app self-contained.\n- **Never** hardcode lists or options; use programmatically generated lists whenever possible.\n- Use \\`st.session_state\\` for all app state values to ensure persistence.\n- Do not write \\`try: ... except: ...\\` blocks -- always let exceptions bubble up so that we can see them and fix them.\n- Write explanatory comments in the code detailing how the app works.\n- Use fully qualified imports: \\`import library\\` instead of \\`from library import something\\`.\n\n### Asynchronous code\n\n- Write asynchronous, non-blocking code wherever possible.\n- The main method is called \\`async def main()\\`. This is the executed entrypoint. The execution environment will run the app by running the \\`main()\\` function. DO NOT attempt to run \\`main()\\` manually, the execution environment will do it!\n- For HTTP requests, use \\`pyodide.http.pyfetch\\`. \\`pyodide.http.pyfetch\\` is asynchronous and has the same interface as JS \\`fetch\\`. Example:\n\\`\\`\\`\nimport streamlit as st\nimport pyodide.http\nimport json\n\nasync def main():\n response = pyodide.http.pyfetch(\n \"https://example.com\",\n method=\"POST\",\n body=json.dumps({\"query\": query}),\n headers={\"Content-Type\": \"application/json\"},\n )\n st.json(await response.json())\n\\`\\`\\`\n- DO NOT use \\`requests\\`, \\`httpx\\` or other HTTP libraries.\n- Only call \\`fetch\\` using the secure \\`https:\\` schema. Plaintext requests will fail due to security policy.\n\n### User interface\n\n- Always begin with \\`st.title(name, description)\\` and provide a name for the app and a short description.\n- Always use a button for submitting the entered data. The user could get confused if the app is missing a submit button. As a best practice, always add an appropriately labeled \\`st.button\\` (or \\`st.form_submit_button\\` when inside \\`st.form\\`) to ensure that the interface is understandable.\n- Group input elements within \\`st.form\\` for better organization.\n- IMPORTANT: Any input element like \\`st.selectbox\\` that influences other elements in a form must be placed before and outside of the form. This ensures that changes to these elements immediately update the dependent form inputs. For example:\n - Place a \\`st.selectbox\\` for data source selection outside the form if it dictates what inputs appear in the form.\n - Similar rules apply for other inputs such as \\`st.radio\\`, \\`st.slider\\`, or any control element that affects form structure or content.\n- Assign unique \\`key\\` values to all Streamlit elements that accept it.\n - For lists of items, always generate a random id for each item and save it together with the item. Use the id in element keys associated with the item.\n- Make use of \\`st.columns\\`. Put elements and metrics side-by-side to create more visually pleasing UIs.\n - Do not use higher column ratios than 5:1, to ensure consistent design.\n - When putting text input and button side-by-side inside \\`st.columns\\`, set \\`label_visibility='collapsed'\\` on the text input to make it aligned. Be aware that this makes the label not visible. **Never** do this outside \\`st.columns\\`.\n- Use built-in Streamlit components for visualizations:\n - \\`st.area_chart(data=None, *, x=None, y=None, x_label=None, y_label=None, color=None, stack=None, width=None, height=None, use_container_width=True)\\`\n - \\`st.bar_chart(data=None, *, x=None, y=None, x_label=None, y_label=None, color=None, horizontal=False, stack=None, width=None, height=None, use_container_width=True)\\`\n - \\`st.map(data=None, *, latitude=None, longitude=None, color=None, size=None, zoom=None, use_container_width=True, width=None, height=None)\\`\n - \\`st.scatter_chart(data=None, *, x=None, y=None, x_label=None, y_label=None, color=None, size=None, width=None, height=None, use_container_width=True)\\`\n - \\`st.graphviz_chart(figure_or_dot, use_container_width=False)\n - \\`st.pyplot(fig=None, clear_figure=None, use_container_width=True, **kwargs)\\`\n- For showing a single number (metric, score, result of calculation, etc.), use \\`st.metric\\`: \\`st.metric(label, value, delta=None, delta_color=\"normal\", help=None, label_visibility=\"visible\")\\`\n\n- Use \\`st.divider()\\` to structure the interface.\n\n### Working with files\n\n- Use \\`st.file_uploader\\` to accept user file uploads. Process the uploaded files programmatically.\n- After a \\`st.file_uploader\\`, always use \\`submitted = st.button(\"...\")\\` to make sure the user confirmed the upload.\n- For non-text file formats (e.g., PDF, DOCX), use libraries like \\`PyPDF2\\` or \\`python-docx\\` to handle content extraction and manipulation.\n\n### LLM functions\n\n- Use \\`@st.llm_function\\` for complex text-based tasks such as summarization, analysis, and keyword extraction.\n- Always define explicit and detailed instructions for the LLM to ensure accurate results.\n- For structured outputs, use a \\`dataclass\\` to define the return type and describe every field in the instructions.\n- For unstructured output, use \\`str\\` as the return type, and the fuction will simply return the raw LLM output as a string.\n- **Never** use multiple LLM functions sequentially with the same input; combine tasks into one function instead.\n- Be verbose and specific in instructions for LLM functions, describing each expected output field in detail.\n\n### Avoid these mistakes\n\n- Avoid deprecated functions like \\`st.cache\\`; use \\`st.cache_data\\` for serializable data and \\`st.cache_resource\\` for persistent resources (e.g., database connections).\n- When querying GitHub API, make sure to parse ISO timestamps from strings like \\`created_at\\`, \\`closed_at\\`, \\`merged_at\\`.\n- When using any external API that returns a JSON reply, always check that the needes fields are present in the response.\n- Do not simultaneously set value of input element using \\`st.session_state.<key>\\` and directly using \\`st.text_input(key=\"<key>\", value=\"...\")\\`. This results in an error.\n- If you need to clear an input field after submitting, use \\`with st.form(\"form_name\", clear_on_submit=True):\\` to wrap the input elements. Do not modify \\`st.session_state.<key>\\` after rendering the element, as that will result in an error.\n- When a button that is **not** part of the form modifies \\`st.session_state\\`, it has to call \\`st.rerun()\\` afterwards to ensure proper UI refresh.\n- Do not call or await \\`main()\\` in your code. \\`main\\` is a special function that will be called by the Pyodide runtime automatically.\n\n---\n\n## Examples\n\n### Document summarizer\n\n\\`\\`\\`python-app\n# The purpose of this app is to summarize input documents, pasted in as text or uploaded as TXT, PDF or DOCX files. The app takes care to correctly extract text from each file format. An LLM function is used to write the summary with configurable length.\n# The user also requested to extract main keywords. This functionality was added to the LLM function.\n# The user further requested for text metrics (characters, words, pages) to be shown for the text being summarized.\n\nimport streamlit as st\nimport PyPDF2\nimport docx\nimport dataclasses\n\n@dataclasses.dataclass\nclass SummaryResult:\n summary: str\n keywords: list[str]\n\n@st.llm_function(creative=False)\nasync def summarize_document(document_text: str, num_keywords: int) -> SummaryResult:\n \"\"\"Summarize the \\`document_text\\` into a concise summary. Write a single paragraph, do not use bullet points. Also extract \\`num_keywords\\` main keywords which represent the content.\"\"\"\n\nasync def main():\n st.title(\"Document Summarizer\", \"Condense a document into a short summary\")\n\n # A selectbox is used to determine input method, which influences what form fields are shown.\n input_source = st.selectbox(\"Input source\", [\"Text box\", \"File upload\"])\n if input_source == \"Text box\":\n document_text = st.text_area(\"Paste the text to summarize\")\n elif input_source == \"File upload\":\n uploaded_file = st.file_uploader(\"Upload a file to summarize\", type=[\"txt\", \"pdf\", \"docx\"], key=\"file_uploader\")\n summary_length = st.selectbox(\"Summary length\", [\"Short\", \"Medium\", \"Long\"], key=\"summary_length\")\n submitted = st.button(\"Generate summary\")\n\n if submitted:\n if input_source == \"Text box\" and not document_text:\n st.error(\"Please enter the text to summarize.\")\n elif input_source == \"File upload\" and not uploaded_file:\n st.error(\"Please upload a file to summarize.\")\n else:\n if input_source == \"File upload\":\n if uploaded_file.type == \"application/pdf\":\n pdf_reader = PyPDF2.PdfReader(uploaded_file)\n document_text = \"\".join([page.extract_text() for page in pdf_reader.pages])\n elif uploaded_file.type == \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\":\n doc = docx.Document(uploaded_file)\n document_text = \"\".join([para.text for para in doc.paragraphs])\n else:\n document_text = uploaded_file.read().decode(\"utf-8\")\n num_keywords = 5 if summary_length == \"Short\" else 10 if summary_length == \"Medium\" else 15\n result = summarize_document(document_text, num_keywords)\n st.divider()\n st.header(\"Summary\")\n st.write(result.summary)\n st.header(\"Keywords\")\n st.write(\"\\\\n\".join(f\"- {keyword}\" for keyword in result.keywords[:num_keywords]))\n st.divider()\n num_characters = len(document_text)\n num_words = len(document_text.split())\n num_pages = num_characters / 1800\n # We place the metrics side-by-side so the design is cleaner\n c1, c2, c3 = st.columns([1, 1, 1])\n with c1:\n st.metric(label=\"Characters\", value=num_characters)\n with c2:\n st.metric(label=\"Words\", value=num_words)\n with c3:\n st.metric(label=\"Pages\", value=f\"{num_pages:.2f}\")\n\\`\\`\\`\n\n### To-Do List\n\n\\`\\`\\`python-app\n# The purpose of this app is to manage a list of tasks (\"todos\"). A clearing form is used to insert a task into a list. Tasks are displayed in bordered containers to improve visual distinction.\n# The user further requested to be able to edit and remove tasks. Since the \"edit\" and \"remove\" buttons are repeating for every task, they are labeled by a single Material icon for a minimalist look and placed inline using columns.\n# The user also requested a button to remove all finished tasks, which was added to the app.\n\nimport streamlit as st\nimport uuid\n\nasync def main():\n if 'todos' not in st.session_state:\n st.session_state.todos = []\n\n st.title(\"To-Do List\", \"Track tasks and their completion\")\n\n with st.form(\"add_todo_form\", clear_on_submit=True):\n st.text_input(\"Task description\", key=\"new_todo\")\n submitted = st.form_submit_button(\"Add\")\n\n if submitted:\n st.session_state.todos.append({\n 'id': str(uuid.uuid4()),\n 'text': st.session_state.new_todo,\n 'completed': False,\n 'editing': False,\n })\n\n st.divider()\n\n if not st.session_state.todos:\n st.write(\"_No todos yet!_\")\n\n for todo in st.session_state.todos:\n with st.container(border=True):\n if todo['editing']:\n new_text = st.text_input(\"Edit task description\", value=todo['text'], key=f\"edit_input_{todo['id']}\")\n save_button = st.button(\"Save\", key=f\"save_{todo['id']}\")\n if save_button:\n todo['text'] = new_text\n todo['editing'] = False\n st.rerun()\n else:\n c1, c2, c3 = st.columns([6, 1, 1]) # <- since we use small (icon) buttons, width 1 is enough\n with c1:\n todo['completed'] = st.checkbox(todo['text'], value=todo['completed'], key=f\"checkbox_{todo['id']}\")\n with c2:\n if st.button(\":material/edit:\", key=f\"edit_button_{todo['id']}\"):\n todo['editing'] = not todo['editing']\n st.rerun()\n with c3:\n if st.button(\":material/delete:\", key=f\"delete_button_{todo['id']}\"):\n st.session_state.todos = [t for t in st.session_state.todos if t['id'] != todo['id']]\n st.rerun()\n\n st.divider()\n\n if st.button(\"Remove finished\"):\n st.session_state.todos = [todo for todo in st.session_state.todos if not todo['completed']]\n st.rerun()\n\\`\\`\\`\n\n### LinkedIn post generator\n\n\\`\\`\\`python-app\n# This app's purpose is to prepare a LinkedIn social media post. App user defines a post topic, tone, and length. An LLM function is then used to generate the text of the post. Since Bee App Builder knows that LinkedIn does not use Markdown formatting, the LLM function was instructed to instead use Unicode-based formatting.\n\nimport streamlit as st\n\n@st.llm_function(creative=True)\nasync def generate_post(topic: str, tone: str, length: str) -> str:\n \"\"\"Write a LinkedIn-style post on the given topic with the specified tone and length. Structure the post to be eye-catching and engaging. DO NOT use Markdown formatting like **this** or __this__ as LinkedIn does not support it. Use emoji in appropriate places to make the post more lively.\"\"\"\n\nasync def main():\n st.title(\"LinkedIn Post Generator\", \"Write social media posts on a given topic\")\n\n topic = st.text_input(\"Post topic\", placeholder=\"e.g., industry trends, company news, thought leadership\")\n tone = st.selectbox(\"Post tone\", [\"Professional\", \"Friendly\", \"Inspirational\", \"Humorous\"])\n length = st.selectbox(\"Post length\", [\"Short\", \"Medium\", \"Long\"])\n\n submitted = st.button(\"Generate post\")\n\n if submitted:\n if not topic:\n st.error(\"Please enter the post topic.\")\n else:\n result = await generate_post(topic, tone, length)\n st.divider()\n st.header(\"Post\")\n # Since we expect the user to copy and paste the generated post, we use code formatting for it\n st.code(result, language=None, wrap_lines=True)\n\\`\\`\\`\n\n---\n\nBy adhering to these guidelines and examples, Bee App Builder ensures user-friendly, robust, and feature-rich app creation tailored to the user's needs.`,\n});\n\nexport interface StreamlitAgentTemplates {\n system: typeof StreamlitAgentSystemPrompt;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["agent.ts"],"names":["ReActAgent","BaseAgent","emitter","runner","constructor","input","Emitter","root","child","namespace","creator","duplicate","tools","find","a","i","arr","b","j","name","toUpperCase","ValueError","modelId","llm","toLowerCase","tag","GraniteRunner","DeepThinkRunner","includes","DefaultRunner","register","memory","meta","slice","description","length","extraDescription","map","tool","join","_run","options","run","execution","maxRetriesPerStep","totalMaxRetries","maxIterations","init","finalMessage","state","signal","createIteration","tool_name","tool_input","output","success","add","AssistantMessage","templates","assistant","render","thought","filter","R","isTruthy","toolName","toolInput","call","JSON","stringify","toolOutput","finalAnswer","final_answer","assign","tool_output","key","em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AQ,EAAA;AAC5BH,QAAAA,SAAAA,EAAWvC,GAAIuC,CAAAA;AACjB,OAAA,CAAA,CAAA;AAEJ;AAEA,IAAA,MAAM,IAAK5E,CAAAA,KAAAA,CAAM0B,MAAOyB,CAAAA,GAAAA,CAAIR,YAAAA,CAAAA;AAC5B,IAAO,OAAA;MAAEsC,MAAQtC,EAAAA,YAAAA;AAAcmC,MAAAA,UAAAA,EAAYhF,MAAOgF,CAAAA,UAAAA;AAAYpD,MAAAA,MAAAA,EAAQ5B,MAAO4B,CAAAA;AAAO,KAAA;AACtF;EAEAwD,cAAiB,GAAA;AACf,IAAO,OAAA;AACL,MAAA,GAAG,MAAMA,cAAAA,EAAAA;AACTlF,MAAAA,KAAAA,EAAO,IAAKA,CAAAA,KAAAA;AACZH,MAAAA,OAAAA,EAAS,IAAKA,CAAAA,OAAAA;AACdC,MAAAA,MAAAA,EAAQ,IAAKA,CAAAA;AACf,KAAA;AACF;AACF","file":"agent.cjs","sourcesContent":["/**\n * Copyright 2025 IBM Corp.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BaseAgent } from \"@/agents/base.js\";\nimport { AnyTool } from \"@/tools/base.js\";\nimport { BaseMemory } from \"@/memory/base.js\";\nimport { AssistantMessage, Message, UserMessage } from \"@/backend/message.js\";\nimport { AgentMeta } from \"@/agents/types.js\";\nimport { Emitter } from \"@/emitter/emitter.js\";\nimport {\n ReActAgentExecutionConfig,\n ReActAgentTemplates,\n ReActAgentCallbacks,\n ReActAgentRunInput,\n ReActAgentRunOptions,\n ReActAgentRunOutput,\n} from \"@/agents/react/types.js\";\nimport { GetRunContext } from \"@/context.js\";\nimport { assign } from \"@/internals/helpers/object.js\";\nimport * as R from \"remeda\";\nimport { BaseRunner } from \"@/agents/react/runners/base.js\";\nimport { GraniteRunner } from \"@/agents/react/runners/granite/runner.js\";\nimport { DeepThinkRunner } from \"@/agents/react/runners/deep-think/runner.js\";\nimport { ValueError } from \"@/errors.js\";\nimport { DefaultRunner } from \"@/agents/react/runners/default/runner.js\";\nimport { ChatModel } from \"@/backend/chat.js\";\n\nexport type ReActAgentTemplateFactory<K extends keyof ReActAgentTemplates> = (\n template: ReActAgentTemplates[K],\n) => ReActAgentTemplates[K];\n\nexport interface ReActAgentInput {\n llm: ChatModel;\n tools: AnyTool[];\n memory: BaseMemory;\n meta?: Omit<AgentMeta, \"tools\">;\n templates?: Partial<{\n [K in keyof ReActAgentTemplates]: ReActAgentTemplates[K] | ReActAgentTemplateFactory<K>;\n }>;\n execution?: ReActAgentExecutionConfig;\n stream?: boolean;\n}\n\nexport class ReActAgent extends BaseAgent<\n ReActAgentRunInput,\n ReActAgentRunOutput,\n ReActAgentRunOptions\n> {\n public readonly emitter = Emitter.root.child<ReActAgentCallbacks>({\n namespace: [\"agent\", \"react\"],\n creator: this,\n });\n\n protected runner: new (...args: ConstructorParameters<typeof BaseRunner>) => BaseRunner;\n\n constructor(protected readonly input: ReActAgentInput) {\n super();\n\n const duplicate = input.tools.find((a, i, arr) =>\n arr.find((b, j) => i !== j && a.name.toUpperCase() === b.name.toUpperCase()),\n );\n if (duplicate) {\n throw new ValueError(\n `Agent's tools must all have different names. Conflicting tool: ${duplicate.name}.`,\n );\n }\n\n const modelId = this.input.llm.modelId.toLowerCase();\n this.runner =\n [\n { tag: \"granite\", runner: GraniteRunner },\n { tag: \"deepseek-r1\", runner: DeepThinkRunner },\n ].find(({ tag }) => modelId.includes(tag))?.runner ?? DefaultRunner;\n }\n\n static {\n this.register();\n }\n\n set memory(memory: BaseMemory) {\n this.input.memory = memory;\n }\n\n get memory() {\n return this.input.memory;\n }\n\n get meta(): AgentMeta {\n const tools = this.input.tools.slice();\n\n if (this.input.meta) {\n return { ...this.input.meta, tools };\n }\n\n return {\n name: \"ReAct\",\n tools,\n description:\n \"The Bee framework demonstrates its ability to auto-correct and adapt in real-time, improving the overall reliability and resilience of the system.\",\n ...(tools.length > 0 && {\n extraDescription: [\n `Tools that I can use to accomplish given task.`,\n ...tools.map((tool) => `Tool '${tool.name}': ${tool.description}.`),\n ].join(\"\\n\"),\n }),\n };\n }\n\n protected async _run(\n input: ReActAgentRunInput,\n options: ReActAgentRunOptions = {},\n run: GetRunContext<typeof this>,\n ): Promise<ReActAgentRunOutput> {\n const runner = new this.runner(\n this.input,\n {\n ...options,\n execution: this.input.execution ??\n options?.execution ?? {\n maxRetriesPerStep: 3,\n totalMaxRetries: 20,\n maxIterations: 10,\n },\n },\n run,\n );\n await runner.init(input);\n\n let finalMessage: Message | undefined;\n while (!finalMessage) {\n const { state, meta, emitter, signal } = await runner.createIteration();\n\n if (state.tool_name && state.tool_input) {\n const { output, success } = await runner.tool({\n state,\n emitter,\n meta,\n signal,\n });\n await runner.memory.add(\n new AssistantMessage(\n runner.templates.assistant.render({\n thought: [state.thought].filter(R.isTruthy),\n toolName: [state.tool_name].filter(R.isTruthy),\n toolInput: [state.tool_input].filter(R.isTruthy).map((call) => JSON.stringify(call)),\n toolOutput: [output],\n finalAnswer: [state.final_answer].filter(R.isTruthy),\n }),\n { success },\n ),\n );\n assign(state, { tool_output: output });\n\n for (const key of [\"partialUpdate\", \"update\"] as const) {\n await emitter.emit(key, {\n data: state,\n update: { key: \"tool_output\", value: output, parsedValue: output },\n meta: { success, ...meta },\n memory: runner.memory,\n });\n }\n }\n if (state.final_answer) {\n finalMessage = new AssistantMessage(state.final_answer, {\n createdAt: new Date(),\n });\n await runner.memory.add(finalMessage);\n await emitter.emit(\"success\", {\n data: finalMessage,\n iterations: runner.iterations,\n memory: runner.memory,\n meta,\n });\n }\n }\n\n if (input.prompt !== null) {\n await this.input.memory.add(\n new UserMessage(input.prompt, {\n createdAt: run.createdAt,\n }),\n );\n }\n\n await this.input.memory.add(finalMessage);\n return { result: finalMessage, iterations: runner.iterations, memory: runner.memory };\n }\n\n createSnapshot() {\n return {\n ...super.createSnapshot(),\n input: this.input,\n emitter: this.emitter,\n runner: this.runner,\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["agent.ts"],"names":["ReActAgent","BaseAgent","emitter","runner","constructor","input","Emitter","root","child","namespace","creator","duplicate","tools","find","a","i","arr","b","j","name","toUpperCase","ValueError","modelId","llm","toLowerCase","tag","GraniteRunner","DeepThinkRunner","includes","DefaultRunner","register","memory","meta","slice","description","length","extraDescription","map","tool","join","_run","options","run","execution","maxRetriesPerStep","totalMaxRetries","maxIterations","init","finalMessage","state","signal","createIteration","tool_name","tool_input","output","success","add","AssistantMessage","templates","assistant","render","thought","filter","R","isTruthy","toolName","toolInput","call","JSON","stringify","toolOutput","finalAnswer","final_answer","assign","tool_output","key","emit","data","update","value","parsedValue","createdAt","Date","iterations","prompt","UserMessage","result","createSnapshot"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDO,MAAMA,mBAAmBC,kBAAAA,CAAAA;EAxDhC;;;;AA6DkBC,EAAAA,OAAAA;AAKNC,EAAAA,MAAAA;AAEVC,EAAAA,WAAAA,CAA+BC,KAAwB,EAAA;AACrD,IAAK,KAAA,EAAA,EAAA,KADwBA,KAAAA,GAAAA,KAAAA,EAAAA,KAPfH,OAAUI,GAAAA,mBAAAA,CAAQC,KAAKC,KAA2B,CAAA;MAChEC,SAAW,EAAA;AAAC,QAAA,OAAA;AAAS,QAAA;;MACrBC,OAAS,EAAA;KACX,CAAA;AAOE,IAAMC,MAAAA,SAAAA,GAAYN,MAAMO,KAAMC,CAAAA,IAAAA,CAAK,CAACC,CAAGC,EAAAA,CAAAA,EAAGC,GACxCA,KAAAA,GAAAA,CAAIH,IAAK,CAAA,CAACI,GAAGC,CAAMH,KAAAA,CAAAA,KAAMG,CA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series of LF Projects, LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BaseAgent } from \"@/agents/base.js\";\nimport { AnyTool } from \"@/tools/base.js\";\nimport { BaseMemory } from \"@/memory/base.js\";\nimport { AssistantMessage, Message, UserMessage } from \"@/backend/message.js\";\nimport { AgentMeta } from \"@/agents/types.js\";\nimport { Emitter } from \"@/emitter/emitter.js\";\nimport {\n ReActAgentExecutionConfig,\n ReActAgentTemplates,\n ReActAgentCallbacks,\n ReActAgentRunInput,\n ReActAgentRunOptions,\n ReActAgentRunOutput,\n} from \"@/agents/react/types.js\";\nimport { GetRunContext } from \"@/context.js\";\nimport { assign } from \"@/internals/helpers/object.js\";\nimport * as R from \"remeda\";\nimport { BaseRunner } from \"@/agents/react/runners/base.js\";\nimport { GraniteRunner } from \"@/agents/react/runners/granite/runner.js\";\nimport { DeepThinkRunner } from \"@/agents/react/runners/deep-think/runner.js\";\nimport { ValueError } from \"@/errors.js\";\nimport { DefaultRunner } from \"@/agents/react/runners/default/runner.js\";\nimport { ChatModel } from \"@/backend/chat.js\";\n\nexport type ReActAgentTemplateFactory<K extends keyof ReActAgentTemplates> = (\n template: ReActAgentTemplates[K],\n) => ReActAgentTemplates[K];\n\nexport interface ReActAgentInput {\n llm: ChatModel;\n tools: AnyTool[];\n memory: BaseMemory;\n meta?: Omit<AgentMeta, \"tools\">;\n templates?: Partial<{\n [K in keyof ReActAgentTemplates]: ReActAgentTemplates[K] | ReActAgentTemplateFactory<K>;\n }>;\n execution?: ReActAgentExecutionConfig;\n stream?: boolean;\n}\n\nexport class ReActAgent extends BaseAgent<\n ReActAgentRunInput,\n ReActAgentRunOutput,\n ReActAgentRunOptions\n> {\n public readonly emitter = Emitter.root.child<ReActAgentCallbacks>({\n namespace: [\"agent\", \"react\"],\n creator: this,\n });\n\n protected runner: new (...args: ConstructorParameters<typeof BaseRunner>) => BaseRunner;\n\n constructor(protected readonly input: ReActAgentInput) {\n super();\n\n const duplicate = input.tools.find((a, i, arr) =>\n arr.find((b, j) => i !== j && a.name.toUpperCase() === b.name.toUpperCase()),\n );\n if (duplicate) {\n throw new ValueError(\n `Agent's tools must all have different names. Conflicting tool: ${duplicate.name}.`,\n );\n }\n\n const modelId = this.input.llm.modelId.toLowerCase();\n this.runner =\n [\n { tag: \"granite\", runner: GraniteRunner },\n { tag: \"deepseek-r1\", runner: DeepThinkRunner },\n ].find(({ tag }) => modelId.includes(tag))?.runner ?? DefaultRunner;\n }\n\n static {\n this.register();\n }\n\n set memory(memory: BaseMemory) {\n this.input.memory = memory;\n }\n\n get memory() {\n return this.input.memory;\n }\n\n get meta(): AgentMeta {\n const tools = this.input.tools.slice();\n\n if (this.input.meta) {\n return { ...this.input.meta, tools };\n }\n\n return {\n name: \"ReAct\",\n tools,\n description:\n \"The Bee framework demonstrates its ability to auto-correct and adapt in real-time, improving the overall reliability and resilience of the system.\",\n ...(tools.length > 0 && {\n extraDescription: [\n `Tools that I can use to accomplish given task.`,\n ...tools.map((tool) => `Tool '${tool.name}': ${tool.description}.`),\n ].join(\"\\n\"),\n }),\n };\n }\n\n protected async _run(\n input: ReActAgentRunInput,\n options: ReActAgentRunOptions = {},\n run: GetRunContext<typeof this>,\n ): Promise<ReActAgentRunOutput> {\n const runner = new this.runner(\n this.input,\n {\n ...options,\n execution: this.input.execution ??\n options?.execution ?? {\n maxRetriesPerStep: 3,\n totalMaxRetries: 20,\n maxIterations: 10,\n },\n },\n run,\n );\n await runner.init(input);\n\n let finalMessage: Message | undefined;\n while (!finalMessage) {\n const { state, meta, emitter, signal } = await runner.createIteration();\n\n if (state.tool_name && state.tool_input) {\n const { output, success } = await runner.tool({\n state,\n emitter,\n meta,\n signal,\n });\n await runner.memory.add(\n new AssistantMessage(\n runner.templates.assistant.render({\n thought: [state.thought].filter(R.isTruthy),\n toolName: [state.tool_name].filter(R.isTruthy),\n toolInput: [state.tool_input].filter(R.isTruthy).map((call) => JSON.stringify(call)),\n toolOutput: [output],\n finalAnswer: [state.final_answer].filter(R.isTruthy),\n }),\n { success },\n ),\n );\n assign(state, { tool_output: output });\n\n for (const key of [\"partialUpdate\", \"update\"] as const) {\n await emitter.emit(key, {\n data: state,\n update: { key: \"tool_output\", value: output, parsedValue: output },\n meta: { success, ...meta },\n memory: runner.memory,\n });\n }\n }\n if (state.final_answer) {\n finalMessage = new AssistantMessage(state.final_answer, {\n createdAt: new Date(),\n });\n await runner.memory.add(finalMessage);\n await emitter.emit(\"success\", {\n data: finalMessage,\n iterations: runner.iterations,\n memory: runner.memory,\n meta,\n });\n }\n }\n\n if (input.prompt !== null) {\n await this.input.memory.add(\n new UserMessage(input.prompt, {\n createdAt: run.createdAt,\n }),\n );\n }\n\n await this.input.memory.add(finalMessage);\n return { result: finalMessage, iterations: runner.iterations, memory: runner.memory };\n }\n\n createSnapshot() {\n return {\n ...super.createSnapshot(),\n input: this.input,\n emitter: this.emitter,\n runner: this.runner,\n };\n }\n}\n"]}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import '../../context.cjs';
|
|
2
|
-
import '../../base-
|
|
2
|
+
import '../../base-BPsHNV2O.cjs';
|
|
3
3
|
import '../../tools/base.cjs';
|
|
4
4
|
import '../../memory/base.cjs';
|
|
5
|
-
import '../../emitter-
|
|
5
|
+
import '../../emitter-BTr99H7I.cjs';
|
|
6
6
|
import './types.cjs';
|
|
7
|
-
export {
|
|
8
|
-
import '../../
|
|
7
|
+
export { c as ReActAgent, b as ReActAgentInput, d as ReActAgentTemplateFactory } from '../../agent-2C0Z9iYa.cjs';
|
|
8
|
+
import '../../chat-BvyMdWFo.cjs';
|
|
9
9
|
import '../../internals/serializable.cjs';
|
|
10
10
|
import '../../internals/types.cjs';
|
|
11
11
|
import '../../internals/helpers/guards.cjs';
|
|
@@ -26,7 +26,7 @@ import '../../parsers/field.cjs';
|
|
|
26
26
|
import '@streamparser/json';
|
|
27
27
|
import 'jsonrepair/stream';
|
|
28
28
|
import '../../parsers/errors.cjs';
|
|
29
|
-
import '../../backend/utils.cjs';
|
|
30
29
|
import '../../backend/constants.cjs';
|
|
31
|
-
import '
|
|
30
|
+
import '../../logger/logger.cjs';
|
|
31
|
+
import 'pino';
|
|
32
32
|
import '../../internals/helpers/counter.cjs';
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import '../../context.js';
|
|
2
|
-
import '../../base-
|
|
2
|
+
import '../../base-ZnwDK6ZB.js';
|
|
3
3
|
import '../../tools/base.js';
|
|
4
4
|
import '../../memory/base.js';
|
|
5
|
-
import '../../emitter-
|
|
5
|
+
import '../../emitter-DiGmS_5O.js';
|
|
6
6
|
import './types.js';
|
|
7
|
-
export {
|
|
8
|
-
import '../../
|
|
7
|
+
export { c as ReActAgent, b as ReActAgentInput, d as ReActAgentTemplateFactory } from '../../agent-DN_52QhH.js';
|
|
8
|
+
import '../../chat-diSK3Sui.js';
|
|
9
9
|
import '../../internals/serializable.js';
|
|
10
10
|
import '../../internals/types.js';
|
|
11
11
|
import '../../internals/helpers/guards.js';
|
|
@@ -26,7 +26,7 @@ import '../../parsers/field.js';
|
|
|
26
26
|
import '@streamparser/json';
|
|
27
27
|
import 'jsonrepair/stream';
|
|
28
28
|
import '../../parsers/errors.js';
|
|
29
|
-
import '../../backend/utils.js';
|
|
30
29
|
import '../../backend/constants.js';
|
|
31
|
-
import '
|
|
30
|
+
import '../../logger/logger.js';
|
|
31
|
+
import 'pino';
|
|
32
32
|
import '../../internals/helpers/counter.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["agent.ts"],"names":["ReActAgent","BaseAgent","emitter","runner","constructor","input","Emitter","root","child","namespace","creator","duplicate","tools","find","a","i","arr","b","j","name","toUpperCase","ValueError","modelId","llm","toLowerCase","tag","GraniteRunner","DeepThinkRunner","includes","DefaultRunner","register","memory","meta","slice","description","length","extraDescription","map","tool","join","_run","options","run","execution","maxRetriesPerStep","totalMaxRetries","maxIterations","init","finalMessage","state","signal","createIteration","tool_name","tool_input","output","success","add","AssistantMessage","templates","assistant","render","thought","filter","R","isTruthy","toolName","toolInput","call","JSON","stringify","toolOutput","finalAnswer","final_answer","assign","tool_output","key","emit","data","update","value","parsedValue","createdAt","Date","iterations","prompt","UserMessage","result","createSnapshot"],"mappings":";;;;;;;;;;;;AAwDO,MAAMA,mBAAmBC,SAAAA,CAAAA;EAxDhC;;;;AA6DkBC,EAAAA,OAAAA;AAKNC,EAAAA,MAAAA;AAEVC,EAAAA,WAAAA,CAA+BC,KAAwB,EAAA;AACrD,IAAK,KAAA,EAAA,EAAA,KADwBA,KAAAA,GAAAA,KAAAA,EAAAA,KAPfH,OAAUI,GAAAA,OAAAA,CAAQC,KAAKC,KAA2B,CAAA;MAChEC,SAAW,EAAA;AAAC,QAAA,OAAA;AAAS,QAAA;;MACrBC,OAAS,EAAA;KACX,CAAA;AAOE,IAAMC,MAAAA,SAAAA,GAAYN,MAAMO,KAAMC,CAAAA,IAAAA,CAAK,CAACC,CAAGC,EAAAA,CAAAA,EAAGC,GACxCA,KAAAA,GAAAA,CAAIH,IAAK,CAAA,CAACI,GAAGC,CAAMH,KAAAA,CAAAA,KAAMG,CAAKJ,IAAAA,CAAAA,CAAEK,IAAKC,CAAAA,WAAAA,OAAkBH,CAAEE,CAAAA,IAAAA,CAAKC,WAAW,EAAA,CAAA,CAAA;AAE3E,IAAA,IAAIT,SAAW,EAAA;AACb,MAAA,MAAM,IAAIU,UAAAA,CACR,CAAkEV,+DAAAA,EAAAA,SAAAA,CAAUQ,IAAI,CAAG,CAAA,CAAA,CAAA;AAEvF;AAEA,IAAA,MAAMG,OAAU,GAAA,IAAA,CAAKjB,KAAMkB,CAAAA,GAAA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,MAAOgF,CAAAA,UAAAA;AACnBpD,UAAAA,MAAAA,EAAQ5B,MAAO4B,CAAAA,MAAAA;AACfC,UAAAA;SACF,CAAA;AACF;AACF;AAEA,IAAI3B,IAAAA,KAAAA,CAAM+E,WAAW,IAAM,EAAA;AACzB,MAAA,MAAM,KAAK/E,KAAM0B,CAAAA,MAAAA,CAAOyB,IACtB,IAAI6B,WAAAA,CAAYhF,MAAM+E,MAAQ,EAAA;AAC5BH,QAAAA,SAAAA,EAAWvC,GAAIuC,CAAAA;AACjB,OAAA,CAAA,CAAA;AAEJ;AAEA,IAAA,MAAM,IAAK5E,CAAAA,KAAAA,CAAM0B,MAAOyB,CAAAA,GAAAA,CAAIR,YAAAA,CAAAA;AAC5B,IAAO,OAAA;MAAEsC,MAAQtC,EAAAA,YAAAA;AAAcmC,MAAAA,UAAAA,EAAYhF,MAAOgF,CAAAA,UAAAA;AAAYpD,MAAAA,MAAAA,EAAQ5B,MAAO4B,CAAAA;AAAO,KAAA;AACtF;EAEAwD,cAAiB,GAAA;AACf,IAAO,OAAA;AACL,MAAA,GAAG,MAAMA,cAAAA,EAAAA;AACTlF,MAAAA,KAAAA,EAAO,IAAKA,CAAAA,KAAAA;AACZH,MAAAA,OAAAA,EAAS,IAAKA,CAAAA,OAAAA;AACdC,MAAAA,MAAAA,EAAQ,IAAKA,CAAAA;AACf,KAAA;AACF;AACF","file":"agent.js","sourcesContent":["/**\n * Copyright 2025 IBM Corp.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BaseAgent } from \"@/agents/base.js\";\nimport { AnyTool } from \"@/tools/base.js\";\nimport { BaseMemory } from \"@/memory/base.js\";\nimport { AssistantMessage, Message, UserMessage } from \"@/backend/message.js\";\nimport { AgentMeta } from \"@/agents/types.js\";\nimport { Emitter } from \"@/emitter/emitter.js\";\nimport {\n ReActAgentExecutionConfig,\n ReActAgentTemplates,\n ReActAgentCallbacks,\n ReActAgentRunInput,\n ReActAgentRunOptions,\n ReActAgentRunOutput,\n} from \"@/agents/react/types.js\";\nimport { GetRunContext } from \"@/context.js\";\nimport { assign } from \"@/internals/helpers/object.js\";\nimport * as R from \"remeda\";\nimport { BaseRunner } from \"@/agents/react/runners/base.js\";\nimport { GraniteRunner } from \"@/agents/react/runners/granite/runner.js\";\nimport { DeepThinkRunner } from \"@/agents/react/runners/deep-think/runner.js\";\nimport { ValueError } from \"@/errors.js\";\nimport { DefaultRunner } from \"@/agents/react/runners/default/runner.js\";\nimport { ChatModel } from \"@/backend/chat.js\";\n\nexport type ReActAgentTemplateFactory<K extends keyof ReActAgentTemplates> = (\n template: ReActAgentTemplates[K],\n) => ReActAgentTemplates[K];\n\nexport interface ReActAgentInput {\n llm: ChatModel;\n tools: AnyTool[];\n memory: BaseMemory;\n meta?: Omit<AgentMeta, \"tools\">;\n templates?: Partial<{\n [K in keyof ReActAgentTemplates]: ReActAgentTemplates[K] | ReActAgentTemplateFactory<K>;\n }>;\n execution?: ReActAgentExecutionConfig;\n stream?: boolean;\n}\n\nexport class ReActAgent extends BaseAgent<\n ReActAgentRunInput,\n ReActAgentRunOutput,\n ReActAgentRunOptions\n> {\n public readonly emitter = Emitter.root.child<ReActAgentCallbacks>({\n namespace: [\"agent\", \"react\"],\n creator: this,\n });\n\n protected runner: new (...args: ConstructorParameters<typeof BaseRunner>) => BaseRunner;\n\n constructor(protected readonly input: ReActAgentInput) {\n super();\n\n const duplicate = input.tools.find((a, i, arr) =>\n arr.find((b, j) => i !== j && a.name.toUpperCase() === b.name.toUpperCase()),\n );\n if (duplicate) {\n throw new ValueError(\n `Agent's tools must all have different names. Conflicting tool: ${duplicate.name}.`,\n );\n }\n\n const modelId = this.input.llm.modelId.toLowerCase();\n this.runner =\n [\n { tag: \"granite\", runner: GraniteRunner },\n { tag: \"deepseek-r1\", runner: DeepThinkRunner },\n ].find(({ tag }) => modelId.includes(tag))?.runner ?? DefaultRunner;\n }\n\n static {\n this.register();\n }\n\n set memory(memory: BaseMemory) {\n this.input.memory = memory;\n }\n\n get memory() {\n return this.input.memory;\n }\n\n get meta(): AgentMeta {\n const tools = this.input.tools.slice();\n\n if (this.input.meta) {\n return { ...this.input.meta, tools };\n }\n\n return {\n name: \"ReAct\",\n tools,\n description:\n \"The Bee framework demonstrates its ability to auto-correct and adapt in real-time, improving the overall reliability and resilience of the system.\",\n ...(tools.length > 0 && {\n extraDescription: [\n `Tools that I can use to accomplish given task.`,\n ...tools.map((tool) => `Tool '${tool.name}': ${tool.description}.`),\n ].join(\"\\n\"),\n }),\n };\n }\n\n protected async _run(\n input: ReActAgentRunInput,\n options: ReActAgentRunOptions = {},\n run: GetRunContext<typeof this>,\n ): Promise<ReActAgentRunOutput> {\n const runner = new this.runner(\n this.input,\n {\n ...options,\n execution: this.input.execution ??\n options?.execution ?? {\n maxRetriesPerStep: 3,\n totalMaxRetries: 20,\n maxIterations: 10,\n },\n },\n run,\n );\n await runner.init(input);\n\n let finalMessage: Message | undefined;\n while (!finalMessage) {\n const { state, meta, emitter, signal } = await runner.createIteration();\n\n if (state.tool_name && state.tool_input) {\n const { output, success } = await runner.tool({\n state,\n emitter,\n meta,\n signal,\n });\n await runner.memory.add(\n new AssistantMessage(\n runner.templates.assistant.render({\n thought: [state.thought].filter(R.isTruthy),\n toolName: [state.tool_name].filter(R.isTruthy),\n toolInput: [state.tool_input].filter(R.isTruthy).map((call) => JSON.stringify(call)),\n toolOutput: [output],\n finalAnswer: [state.final_answer].filter(R.isTruthy),\n }),\n { success },\n ),\n );\n assign(state, { tool_output: output });\n\n for (const key of [\"partialUpdate\", \"update\"] as const) {\n await emitter.emit(key, {\n data: state,\n update: { key: \"tool_output\", value: output, parsedValue: output },\n meta: { success, ...meta },\n memory: runner.memory,\n });\n }\n }\n if (state.final_answer) {\n finalMessage = new AssistantMessage(state.final_answer, {\n createdAt: new Date(),\n });\n await runner.memory.add(finalMessage);\n await emitter.emit(\"success\", {\n data: finalMessage,\n iterations: runner.iterations,\n memory: runner.memory,\n meta,\n });\n }\n }\n\n if (input.prompt !== null) {\n await this.input.memory.add(\n new UserMessage(input.prompt, {\n createdAt: run.createdAt,\n }),\n );\n }\n\n await this.input.memory.add(finalMessage);\n return { result: finalMessage, iterations: runner.iterations, memory: runner.memory };\n }\n\n createSnapshot() {\n return {\n ...super.createSnapshot(),\n input: this.input,\n emitter: this.emitter,\n runner: this.runner,\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["agent.ts"],"names":["ReActAgent","BaseAgent","emitter","runner","constructor","input","Emitter","root","child","namespace","creator","duplicate","tools","find","a","i","arr","b","j","name","toUpperCase","ValueError","modelId","llm","toLowerCase","tag","GraniteRunner","DeepThinkRunner","includes","DefaultRunner","register","memory","meta","slice","description","length","extraDescription","map","tool","join","_run","options","run","execution","maxRetriesPerStep","totalMaxRetries","maxIterations","init","finalMessage","state","signal","createIteration","tool_name","tool_input","output","success","add","AssistantMessage","templates","assistant","render","thought","filter","R","isTruthy","toolName","toolInput","call","JSON","stringify","toolOutput","finalAnswer","final_answer","assign","tool_output","key","emit","data","update","value","parsedValue","createdAt","Date","iterations","prompt","UserMessage","result","createSnapshot"],"mappings":";;;;;;;;;;;;AAwDO,MAAMA,mBAAmBC,SAAAA,CAAAA;EAxDhC;;;;AA6DkBC,EAAAA,OAAAA;AAKNC,EAAAA,MAAAA;AAEVC,EAAAA,WAAAA,CAA+BC,KAAwB,EAAA;AACrD,IAAK,KAAA,EAAA,EAAA,KADwBA,KAAAA,GAAAA,KAAAA,EAAAA,KAPfH,OAAUI,GAAAA,OAAAA,CAAQC,KAAKC,KAA2B,CAAA;MAChEC,SAAW,EAAA;AAAC,QAAA,OAA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G,MAAMA,cAAAA,EAAAA;AACTlF,MAAAA,KAAAA,EAAO,IAAKA,CAAAA,KAAAA;AACZH,MAAAA,OAAAA,EAAS,IAAKA,CAAAA,OAAAA;AACdC,MAAAA,MAAAA,EAAQ,IAAKA,CAAAA;AACf,KAAA;AACF;AACF","file":"agent.js","sourcesContent":["/**\n * Copyright 2025 © BeeAI a Series of LF Projects, LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BaseAgent } from \"@/agents/base.js\";\nimport { AnyTool } from \"@/tools/base.js\";\nimport { BaseMemory } from \"@/memory/base.js\";\nimport { AssistantMessage, Message, UserMessage } from \"@/backend/message.js\";\nimport { AgentMeta } from \"@/agents/types.js\";\nimport { Emitter } from \"@/emitter/emitter.js\";\nimport {\n ReActAgentExecutionConfig,\n ReActAgentTemplates,\n ReActAgentCallbacks,\n ReActAgentRunInput,\n ReActAgentRunOptions,\n ReActAgentRunOutput,\n} from \"@/agents/react/types.js\";\nimport { GetRunContext } from \"@/context.js\";\nimport { assign } from \"@/internals/helpers/object.js\";\nimport * as R from \"remeda\";\nimport { BaseRunner } from \"@/agents/react/runners/base.js\";\nimport { GraniteRunner } from \"@/agents/react/runners/granite/runner.js\";\nimport { DeepThinkRunner } from \"@/agents/react/runners/deep-think/runner.js\";\nimport { ValueError } from \"@/errors.js\";\nimport { DefaultRunner } from \"@/agents/react/runners/default/runner.js\";\nimport { ChatModel } from \"@/backend/chat.js\";\n\nexport type ReActAgentTemplateFactory<K extends keyof ReActAgentTemplates> = (\n template: ReActAgentTemplates[K],\n) => ReActAgentTemplates[K];\n\nexport interface ReActAgentInput {\n llm: ChatModel;\n tools: AnyTool[];\n memory: BaseMemory;\n meta?: Omit<AgentMeta, \"tools\">;\n templates?: Partial<{\n [K in keyof ReActAgentTemplates]: ReActAgentTemplates[K] | ReActAgentTemplateFactory<K>;\n }>;\n execution?: ReActAgentExecutionConfig;\n stream?: boolean;\n}\n\nexport class ReActAgent extends BaseAgent<\n ReActAgentRunInput,\n ReActAgentRunOutput,\n ReActAgentRunOptions\n> {\n public readonly emitter = Emitter.root.child<ReActAgentCallbacks>({\n namespace: [\"agent\", \"react\"],\n creator: this,\n });\n\n protected runner: new (...args: ConstructorParameters<typeof BaseRunner>) => BaseRunner;\n\n constructor(protected readonly input: ReActAgentInput) {\n super();\n\n const duplicate = input.tools.find((a, i, arr) =>\n arr.find((b, j) => i !== j && a.name.toUpperCase() === b.name.toUpperCase()),\n );\n if (duplicate) {\n throw new ValueError(\n `Agent's tools must all have different names. Conflicting tool: ${duplicate.name}.`,\n );\n }\n\n const modelId = this.input.llm.modelId.toLowerCase();\n this.runner =\n [\n { tag: \"granite\", runner: GraniteRunner },\n { tag: \"deepseek-r1\", runner: DeepThinkRunner },\n ].find(({ tag }) => modelId.includes(tag))?.runner ?? DefaultRunner;\n }\n\n static {\n this.register();\n }\n\n set memory(memory: BaseMemory) {\n this.input.memory = memory;\n }\n\n get memory() {\n return this.input.memory;\n }\n\n get meta(): AgentMeta {\n const tools = this.input.tools.slice();\n\n if (this.input.meta) {\n return { ...this.input.meta, tools };\n }\n\n return {\n name: \"ReAct\",\n tools,\n description:\n \"The Bee framework demonstrates its ability to auto-correct and adapt in real-time, improving the overall reliability and resilience of the system.\",\n ...(tools.length > 0 && {\n extraDescription: [\n `Tools that I can use to accomplish given task.`,\n ...tools.map((tool) => `Tool '${tool.name}': ${tool.description}.`),\n ].join(\"\\n\"),\n }),\n };\n }\n\n protected async _run(\n input: ReActAgentRunInput,\n options: ReActAgentRunOptions = {},\n run: GetRunContext<typeof this>,\n ): Promise<ReActAgentRunOutput> {\n const runner = new this.runner(\n this.input,\n {\n ...options,\n execution: this.input.execution ??\n options?.execution ?? {\n maxRetriesPerStep: 3,\n totalMaxRetries: 20,\n maxIterations: 10,\n },\n },\n run,\n );\n await runner.init(input);\n\n let finalMessage: Message | undefined;\n while (!finalMessage) {\n const { state, meta, emitter, signal } = await runner.createIteration();\n\n if (state.tool_name && state.tool_input) {\n const { output, success } = await runner.tool({\n state,\n emitter,\n meta,\n signal,\n });\n await runner.memory.add(\n new AssistantMessage(\n runner.templates.assistant.render({\n thought: [state.thought].filter(R.isTruthy),\n toolName: [state.tool_name].filter(R.isTruthy),\n toolInput: [state.tool_input].filter(R.isTruthy).map((call) => JSON.stringify(call)),\n toolOutput: [output],\n finalAnswer: [state.final_answer].filter(R.isTruthy),\n }),\n { success },\n ),\n );\n assign(state, { tool_output: output });\n\n for (const key of [\"partialUpdate\", \"update\"] as const) {\n await emitter.emit(key, {\n data: state,\n update: { key: \"tool_output\", value: output, parsedValue: output },\n meta: { success, ...meta },\n memory: runner.memory,\n });\n }\n }\n if (state.final_answer) {\n finalMessage = new AssistantMessage(state.final_answer, {\n createdAt: new Date(),\n });\n await runner.memory.add(finalMessage);\n await emitter.emit(\"success\", {\n data: finalMessage,\n iterations: runner.iterations,\n memory: runner.memory,\n meta,\n });\n }\n }\n\n if (input.prompt !== null) {\n await this.input.memory.add(\n new UserMessage(input.prompt, {\n createdAt: run.createdAt,\n }),\n );\n }\n\n await this.input.memory.add(finalMessage);\n return { result: finalMessage, iterations: runner.iterations, memory: runner.memory };\n }\n\n createSnapshot() {\n return {\n ...super.createSnapshot(),\n input: this.input,\n emitter: this.emitter,\n runner: this.runner,\n };\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["prompts.ts"],"names":["ReActAgentSystemPrompt","PromptTemplate","schema","z","object","instructions","string","default","tools","array","name","min","description","passthrough","createdAt","datetime","nullish","template","ReActAgentAssistantPrompt","thought","toolName","toolInput","toolOutput","finalAnswer","partial","ReActAgentUserPrompt","input","meta","optional","functions","formatMeta","parts","filter","Boolean","join","ReActAgentUserEmptyPrompt","ReActAgentToolErrorPrompt","reason","ReActAgentToolInputErrorPrompt","ReActAgentToolNoResultsPrompt","record","any","ReActAgentToolNotFoundPrompt","ReActAgentSchemaErrorPrompt"],"mappings":";;;;;;;AAoBaA,MAAAA,sBAAAA,GAAyB,IAAIC,2BAAe,CAAA;AACvDC,EAAAA,MAAAA,EAAQC,MAAEC,MAAO,CAAA;AACfC,IAAAA,YAAAA,EAAcF,KAAEG,CAAAA,MAAAA,EAASC,CAAAA,OAAAA,CAAQ,8BAAA,CAAA;IACjCC,KAAOL,EAAAA,KAAAA,CAAEM,KACPN,CAAAA,KAAAA,CACGC,MAAO,CAAA;AACNM,MAAAA,IAAAA,EAAMP,KAAEG,CAAAA,MAAAA,EAASK,CAAAA,GAAAA,CAAI,CAAA,CAAA;AACrBC,MAAAA,WAAAA,EAAaT,KAAEG,CAAAA,MAAAA,EAASK,CAAAA,GAAAA,CAAI,CAAA,CAAA;AAC5BT,MAAAA,MAAAA,EAAQC,KAAEG,CAAAA,MAAAA,EAASK,CAAAA,GAAAA,CAAI,CAAA;KACzB,CAAA,CACCE,aAAW,CAAA;AAEhBC,IAAAA,SAAAA,EAAWX,KAAEG,CAAAA,MAAAA,EAASS,CAAAA,QAAAA,GAAWC,OAAO;GAC1C,CAAA;EACAC,QAAU,EAAA,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEZ,CAAA;AAEaC,MAAAA,yBAAAA,GAA4B,IAAIjB,2BAAe,CAAA;AAC1DC,EAAAA,MAAAA,EAAQC,MACLC,MAAO,CAAA;AACNe,IAAAA,OAAAA,EAAShB,KAAEM,CAAAA,KAAAA,CAAMN,KAAEG,CAAAA,MAAAA,EAAM,CAAA;AACzBc,IAAAA,QAAAA,EAAUjB,KAAEM,CAAAA,KAAAA,CAAMN,KAAEG,CAAA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,CAAO,EAAC,EAAGS,WAAW,EAAA;EAChCI,QAAU,EAAA,CAAA;;AAEZ,CAAA","file":"prompts.cjs","sourcesContent":["/**\n * Copyright 2025 IBM Corp.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PromptTemplate } from \"@/template.js\";\nimport { z } from \"zod\";\nimport { MessageMeta } from \"@/backend/message.js\";\n\nexport const ReActAgentSystemPrompt = new PromptTemplate({\n schema: z.object({\n instructions: z.string().default(\"You are a helpful assistant.\"),\n tools: z.array(\n z\n .object({\n name: z.string().min(1),\n description: z.string().min(1),\n schema: z.string().min(1),\n })\n .passthrough(),\n ),\n createdAt: z.string().datetime().nullish(),\n }),\n template: `# Available functions\n{{#tools.length}}\nYou can only use the following functions. Always use all required parameters.\n\n{{#tools}}\nFunction Name: {{name}}\nDescription: {{description}}\nParameters: {{schema}}\n\n{{/tools}}\n{{/tools.length}}\n{{^tools.length}}\nNo functions are available.\n\n{{/tools.length}}\n# Communication structure\nYou communicate only in instruction lines. The format is: \"Instruction: expected output\\n\". You must only use these instruction lines and must not enter empty lines between them. Each instruction must start on a new line.\n{{#tools.length}}\nYou must skip the instruction lines Function Name, Function Input and Function Output if no function calling is required.\n{{/tools.length}}\n\nMessage: User's message. You never use this instruction line.\n{{^tools.length}}\nThought: A single-line plan of how to answer the user's message, including an explanation of the reasoning behind it. It must be immediately followed by Final Answer.\n{{/tools.length}}\n{{#tools.length}}\nThought: A single-line step-by-step plan of how to answer the user's message, including an explanation of the reasoning behind it. You can use the available functions defined above. This instruction line must be immediately followed by Function Name if one of the available functions defined above needs to be called, or by Final Answer. Do not provide the answer here.\nFunction Name: Name of the function. This instruction line must be immediately followed by Function Input.\nFunction Input: Function parameters. Empty object is a valid parameter.\nFunction Output: Output of the function in JSON format.\nThought: Continue your thinking process.\n{{/tools.length}}\nFinal Answer: Answer the user or ask for more information or clarification. It must always be preceded by Thought.\n\n## Examples\nMessage: Can you translate \"How are you\" into French?\nThought: The user wants to translate a text into French. I can do that.\nFinal Answer: Comment vas-tu?\n\n# Instructions\nUser can only see the Final Answer, all answers must be provided there.\n{{^tools.length}}\nYou must always use the communication structure and instructions defined above. Do not forget that Thought must be a single-line immediately followed by Final Answer.\n{{/tools.length}}\n{{#tools.length}}\nYou must always use the communication structure and instructions defined above. Do not forget that Thought must be a single-line immediately followed by either Function Name or Final Answer.\nYou must use Functions to retrieve factual or historical information to answer the message.\n{{/tools.length}}\nIf the user suggests using a function that is not available, answer that the function is not available. You can suggest alternatives if appropriate.\nWhen the message is unclear or you need more information from the user, ask in Final Answer.\n\n# Your capabilities\nPrefer to use these capabilities over functions.\n- You understand these languages: English, Spanish, French.\n- You can translate, analyze, summarize, even long documents.\n\n# Notes\n- If you don't know the answer, say that you don't know.\n- The current time and date in ISO format can be found in the last message.\n- When answering the user, use friendly formats for time and date.\n- Use markdown syntax for formatting code snippets, links, JSON, tables, images, files.\n- Sometimes, things don't go as planned. Functions may not provide useful information on the first few tries. You should always try a few different approaches before declaring the problem unsolvable.\n- When the function doesn't give you what you were asking for, you must either use another function or a different function input.\n - When using search engines, you try different formulations of the query, possibly even in a different language.\n- You cannot do complex calculations, computations, or data manipulations without using functions.\n\n# Role\n{{instructions}}`,\n});\n\nexport const ReActAgentAssistantPrompt = new PromptTemplate({\n schema: z\n .object({\n thought: z.array(z.string()),\n toolName: z.array(z.string()),\n toolInput: z.array(z.string()),\n toolOutput: z.array(z.string()),\n finalAnswer: z.array(z.string()),\n })\n .partial(),\n template: `{{#thought}}Thought: {{.}}\\n{{/thought}}{{#toolName}}Function Name: {{.}}\\n{{/toolName}}{{#toolInput}}Function Input: {{.}}\\n{{/toolInput}}{{#toolOutput}}Function Output: {{.}}\\n{{/toolOutput}}{{#finalAnswer}}Final Answer: {{.}}{{/finalAnswer}}`,\n});\n\nexport const ReActAgentUserPrompt = new PromptTemplate({\n schema: z\n .object({\n input: z.string(),\n meta: z\n .object({\n createdAt: z.string().datetime().optional(),\n })\n .passthrough()\n .optional(),\n })\n .passthrough(),\n functions: {\n formatMeta: function () {\n const meta = this.meta as MessageMeta;\n if (!meta) {\n return \"\";\n }\n\n const parts = [meta.createdAt && `This message was created at ${meta.createdAt}`]\n .filter(Boolean)\n .join(\"\\n\");\n\n return parts ? `\\n\\n${parts}` : parts;\n },\n },\n template: `Message: {{input}}{{formatMeta}}`,\n});\n\nexport const ReActAgentUserEmptyPrompt = new PromptTemplate({\n schema: z.object({}).passthrough(),\n template: `Message: Empty message.`,\n});\n\nexport const ReActAgentToolErrorPrompt = new PromptTemplate({\n schema: z\n .object({\n reason: z.string(),\n })\n .passthrough(),\n template: `The function has failed; the error log is shown below. If the function cannot accomplish what you want, use a different function or explain why you can't use it.\n\n{{reason}}`,\n});\n\nexport const ReActAgentToolInputErrorPrompt = new PromptTemplate({\n schema: z\n .object({\n reason: z.string(),\n })\n .passthrough(),\n template: `{{reason}}\n\nHINT: If you're convinced that the input was correct but the function cannot process it then use a different function or say I don't know.`,\n});\n\nexport const ReActAgentToolNoResultsPrompt = new PromptTemplate({\n schema: z.record(z.any()),\n template: `No results were found!`,\n});\n\nexport const ReActAgentToolNotFoundPrompt = new PromptTemplate({\n schema: z\n .object({\n tools: z.array(z.object({ name: z.string() }).passthrough()),\n })\n .passthrough(),\n template: `Function does not exist!\n{{#tools.length}}\nUse one of the following functions: {{#trim}}{{#tools}}{{name}},{{/tools}}{{/trim}}\n{{/tools.length}}`,\n});\n\nexport const ReActAgentSchemaErrorPrompt = new PromptTemplate({\n schema: z.object({}).passthrough(),\n template: `Error: The generated response does not adhere to the communication structure mentioned in the system prompt.\nYou communicate only in instruction lines. Valid instruction lines are 'Thought' followed by either 'Function Name' + 'Function Input' + 'Function Output' or 'Final Answer'.`,\n});\n"]}
|
|
1
|
+
{"version":3,"sources":["prompts.ts"],"names":["ReActAgentSystemPrompt","PromptTemplate","schema","z","object","instructions","string","default","tools","array","name","min","description","passthrough","createdAt","datetime","nullish","template","ReActAgentAssistantPrompt","thought","toolName","toolInput","toolOutput","finalAnswer","partial","ReActAgentUserPrompt","input","meta","optional","functions","formatMeta","parts","filter","Boolean","join","ReActAgentUserEmptyPrompt","ReActAgentToolErrorPrompt","reason","ReActAgentToolInputErrorPrompt","ReActAgentToolNoResultsPrompt","record","any","ReActAgentToolNotFoundPrompt","ReActAgentSchemaErrorPrompt"],"mappings":";;;;;;;AAoBaA,MAAAA,sBAAAA,GAAyB,IAAIC,2BAAe,CAAA;AACvDC,EAAAA,MAAAA,EAAQC,MAAEC,MAAO,CAAA;AACfC,IAAAA,YAAAA,EAAcF,KAAEG,CAAAA,MAAAA,EAASC,CAAAA,OAAAA,CAAQ,8BAAA,CAAA;IACjCC,KAAOL,EAAAA,KAAAA,CAAEM,KACPN,CAAAA,KAAAA,CACGC,MAAO,CAAA;AACNM,MAAAA,IAAAA,EAAMP,KAAEG,CAAAA,MAAAA,EAASK,CAAAA,GAAAA,CAAI,CAAA,CAAA;AACrBC,MAAAA,WAAAA,EAAaT,KAAEG,CAAAA,MAAAA,EAASK,CAAAA,GAAAA,CAAI,CAAA,CAAA;AAC5BT,MAAAA,MAAAA,EAAQC,KAAEG,CAAAA,MAAAA,EAASK,CAAAA,GAAAA,CAAI,CAAA;KACzB,CAAA,CACCE,aAAW,CAAA;AAEhBC,IAAAA,SAAAA,EAAWX,KAAEG,CAAAA,MAAAA,EAASS,CAAAA,QAAAA,GAAWC,OAAO;GAC1C,CAAA;EACAC,QAAU,EAAA,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEZ,CAAA;AAEaC,MAAAA,yBAAAA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EM,MAAAA,IAAAA,EAAMP,MAAEG,MAAM;KAAG,CAAA,CAAGO,aAAW;AAC3D,GAAA,EACCA,WAAW,EAAA;EACdI,QAAU,EAAA,CAAA;;;;AAIZ,CAAA;AAEa0B,MAAAA,2BAAAA,GAA8B,IAAI1C,2BAAe,CAAA;AAC5DC,EAAAA,MAAAA,EAAQC,KAAEC,CAAAA,MAAAA,CAAO,EAAC,EAAGS,WAAW,EAAA;EAChCI,QAAU,EAAA,CAAA;;AAEZ,CAAA","file":"prompts.cjs","sourcesContent":["/**\n * Copyright 2025 © BeeAI a Series of LF Projects, LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PromptTemplate } from \"@/template.js\";\nimport { z } from \"zod\";\nimport { MessageMeta } from \"@/backend/message.js\";\n\nexport const ReActAgentSystemPrompt = new PromptTemplate({\n schema: z.object({\n instructions: z.string().default(\"You are a helpful assistant.\"),\n tools: z.array(\n z\n .object({\n name: z.string().min(1),\n description: z.string().min(1),\n schema: z.string().min(1),\n })\n .passthrough(),\n ),\n createdAt: z.string().datetime().nullish(),\n }),\n template: `# Available functions\n{{#tools.length}}\nYou can only use the following functions. Always use all required parameters.\n\n{{#tools}}\nFunction Name: {{name}}\nDescription: {{description}}\nParameters: {{schema}}\n\n{{/tools}}\n{{/tools.length}}\n{{^tools.length}}\nNo functions are available.\n\n{{/tools.length}}\n# Communication structure\nYou communicate only in instruction lines. The format is: \"Instruction: expected output\\n\". You must only use these instruction lines and must not enter empty lines between them. Each instruction must start on a new line.\n{{#tools.length}}\nYou must skip the instruction lines Function Name, Function Input and Function Output if no function calling is required.\n{{/tools.length}}\n\nMessage: User's message. You never use this instruction line.\n{{^tools.length}}\nThought: A single-line plan of how to answer the user's message, including an explanation of the reasoning behind it. It must be immediately followed by Final Answer.\n{{/tools.length}}\n{{#tools.length}}\nThought: A single-line step-by-step plan of how to answer the user's message, including an explanation of the reasoning behind it. You can use the available functions defined above. This instruction line must be immediately followed by Function Name if one of the available functions defined above needs to be called, or by Final Answer. Do not provide the answer here.\nFunction Name: Name of the function. This instruction line must be immediately followed by Function Input.\nFunction Input: Function parameters. Empty object is a valid parameter.\nFunction Output: Output of the function in JSON format.\nThought: Continue your thinking process.\n{{/tools.length}}\nFinal Answer: Answer the user or ask for more information or clarification. It must always be preceded by Thought.\n\n## Examples\nMessage: Can you translate \"How are you\" into French?\nThought: The user wants to translate a text into French. I can do that.\nFinal Answer: Comment vas-tu?\n\n# Instructions\nUser can only see the Final Answer, all answers must be provided there.\n{{^tools.length}}\nYou must always use the communication structure and instructions defined above. Do not forget that Thought must be a single-line immediately followed by Final Answer.\n{{/tools.length}}\n{{#tools.length}}\nYou must always use the communication structure and instructions defined above. Do not forget that Thought must be a single-line immediately followed by either Function Name or Final Answer.\nYou must use Functions to retrieve factual or historical information to answer the message.\n{{/tools.length}}\nIf the user suggests using a function that is not available, answer that the function is not available. You can suggest alternatives if appropriate.\nWhen the message is unclear or you need more information from the user, ask in Final Answer.\n\n# Your capabilities\nPrefer to use these capabilities over functions.\n- You understand these languages: English, Spanish, French.\n- You can translate, analyze, summarize, even long documents.\n\n# Notes\n- If you don't know the answer, say that you don't know.\n- The current time and date in ISO format can be found in the last message.\n- When answering the user, use friendly formats for time and date.\n- Use markdown syntax for formatting code snippets, links, JSON, tables, images, files.\n- Sometimes, things don't go as planned. Functions may not provide useful information on the first few tries. You should always try a few different approaches before declaring the problem unsolvable.\n- When the function doesn't give you what you were asking for, you must either use another function or a different function input.\n - When using search engines, you try different formulations of the query, possibly even in a different language.\n- You cannot do complex calculations, computations, or data manipulations without using functions.\n\n# Role\n{{instructions}}`,\n});\n\nexport const ReActAgentAssistantPrompt = new PromptTemplate({\n schema: z\n .object({\n thought: z.array(z.string()),\n toolName: z.array(z.string()),\n toolInput: z.array(z.string()),\n toolOutput: z.array(z.string()),\n finalAnswer: z.array(z.string()),\n })\n .partial(),\n template: `{{#thought}}Thought: {{.}}\\n{{/thought}}{{#toolName}}Function Name: {{.}}\\n{{/toolName}}{{#toolInput}}Function Input: {{.}}\\n{{/toolInput}}{{#toolOutput}}Function Output: {{.}}\\n{{/toolOutput}}{{#finalAnswer}}Final Answer: {{.}}{{/finalAnswer}}`,\n});\n\nexport const ReActAgentUserPrompt = new PromptTemplate({\n schema: z\n .object({\n input: z.string(),\n meta: z\n .object({\n createdAt: z.string().datetime().optional(),\n })\n .passthrough()\n .optional(),\n })\n .passthrough(),\n functions: {\n formatMeta: function () {\n const meta = this.meta as MessageMeta;\n if (!meta) {\n return \"\";\n }\n\n const parts = [meta.createdAt && `This message was created at ${meta.createdAt}`]\n .filter(Boolean)\n .join(\"\\n\");\n\n return parts ? `\\n\\n${parts}` : parts;\n },\n },\n template: `Message: {{input}}{{formatMeta}}`,\n});\n\nexport const ReActAgentUserEmptyPrompt = new PromptTemplate({\n schema: z.object({}).passthrough(),\n template: `Message: Empty message.`,\n});\n\nexport const ReActAgentToolErrorPrompt = new PromptTemplate({\n schema: z\n .object({\n reason: z.string(),\n })\n .passthrough(),\n template: `The function has failed; the error log is shown below. If the function cannot accomplish what you want, use a different function or explain why you can't use it.\n\n{{reason}}`,\n});\n\nexport const ReActAgentToolInputErrorPrompt = new PromptTemplate({\n schema: z\n .object({\n reason: z.string(),\n })\n .passthrough(),\n template: `{{reason}}\n\nHINT: If you're convinced that the input was correct but the function cannot process it then use a different function or say I don't know.`,\n});\n\nexport const ReActAgentToolNoResultsPrompt = new PromptTemplate({\n schema: z.record(z.any()),\n template: `No results were found!`,\n});\n\nexport const ReActAgentToolNotFoundPrompt = new PromptTemplate({\n schema: z\n .object({\n tools: z.array(z.object({ name: z.string() }).passthrough()),\n })\n .passthrough(),\n template: `Function does not exist!\n{{#tools.length}}\nUse one of the following functions: {{#trim}}{{#tools}}{{name}},{{/tools}}{{/trim}}\n{{/tools.length}}`,\n});\n\nexport const ReActAgentSchemaErrorPrompt = new PromptTemplate({\n schema: z.object({}).passthrough(),\n template: `Error: The generated response does not adhere to the communication structure mentioned in the system prompt.\nYou communicate only in instruction lines. Valid instruction lines are 'Thought' followed by either 'Function Name' + 'Function Input' + 'Function Output' or 'Final Answer'.`,\n});\n"]}
|
|
@@ -7,7 +7,7 @@ import '../../internals/serializable.cjs';
|
|
|
7
7
|
import 'ajv';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
|
-
* Copyright 2025
|
|
10
|
+
* Copyright 2025 © BeeAI a Series of LF Projects, LLC
|
|
11
11
|
*
|
|
12
12
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
13
13
|
* you may not use this file except in compliance with the License.
|
|
@@ -39,12 +39,12 @@ declare const ReActAgentSystemPrompt: PromptTemplate<z.ZodObject<{
|
|
|
39
39
|
}, z.ZodTypeAny, "passthrough">>, "many">;
|
|
40
40
|
createdAt: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
41
41
|
}, "strip", z.ZodTypeAny, {
|
|
42
|
+
instructions: string;
|
|
42
43
|
tools: z.objectOutputType<{
|
|
43
44
|
name: z.ZodString;
|
|
44
45
|
description: z.ZodString;
|
|
45
46
|
schema: z.ZodString;
|
|
46
47
|
}, z.ZodTypeAny, "passthrough">[];
|
|
47
|
-
instructions: string;
|
|
48
48
|
createdAt?: string | null | undefined;
|
|
49
49
|
}, {
|
|
50
50
|
tools: z.objectInputType<{
|
|
@@ -7,7 +7,7 @@ import '../../internals/serializable.js';
|
|
|
7
7
|
import 'ajv';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
|
-
* Copyright 2025
|
|
10
|
+
* Copyright 2025 © BeeAI a Series of LF Projects, LLC
|
|
11
11
|
*
|
|
12
12
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
13
13
|
* you may not use this file except in compliance with the License.
|
|
@@ -39,12 +39,12 @@ declare const ReActAgentSystemPrompt: PromptTemplate<z.ZodObject<{
|
|
|
39
39
|
}, z.ZodTypeAny, "passthrough">>, "many">;
|
|
40
40
|
createdAt: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
41
41
|
}, "strip", z.ZodTypeAny, {
|
|
42
|
+
instructions: string;
|
|
42
43
|
tools: z.objectOutputType<{
|
|
43
44
|
name: z.ZodString;
|
|
44
45
|
description: z.ZodString;
|
|
45
46
|
schema: z.ZodString;
|
|
46
47
|
}, z.ZodTypeAny, "passthrough">[];
|
|
47
|
-
instructions: string;
|
|
48
48
|
createdAt?: string | null | undefined;
|
|
49
49
|
}, {
|
|
50
50
|
tools: z.objectInputType<{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["prompts.ts"],"names":["ReActAgentSystemPrompt","PromptTemplate","schema","z","object","instructions","string","default","tools","array","name","min","description","passthrough","createdAt","datetime","nullish","template","ReActAgentAssistantPrompt","thought","toolName","toolInput","toolOutput","finalAnswer","partial","ReActAgentUserPrompt","input","meta","optional","functions","formatMeta","parts","filter","Boolean","join","ReActAgentUserEmptyPrompt","ReActAgentToolErrorPrompt","reason","ReActAgentToolInputErrorPrompt","ReActAgentToolNoResultsPrompt","record","any","ReActAgentToolNotFoundPrompt","ReActAgentSchemaErrorPrompt"],"mappings":";;;;;AAoBaA,MAAAA,sBAAAA,GAAyB,IAAIC,cAAe,CAAA;AACvDC,EAAAA,MAAAA,EAAQC,EAAEC,MAAO,CAAA;AACfC,IAAAA,YAAAA,EAAcF,CAAEG,CAAAA,MAAAA,EAASC,CAAAA,OAAAA,CAAQ,8BAAA,CAAA;IACjCC,KAAOL,EAAAA,CAAAA,CAAEM,KACPN,CAAAA,CAAAA,CACGC,MAAO,CAAA;AACNM,MAAAA,IAAAA,EAAMP,CAAEG,CAAAA,MAAAA,EAASK,CAAAA,GAAAA,CAAI,C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,MAAM;AAClB,GAAA,EACCO,WAAW,EAAA;EACdI,QAAU,EAAA,CAAA;;;AAGZ,CAAA;AAEasB,MAAAA,6BAAAA,GAAgC,IAAItC,cAAe,CAAA;AAC9DC,EAAAA,MAAAA,EAAQC,CAAEqC,CAAAA,MAAAA,CAAOrC,CAAEsC,CAAAA,GAAAA,EAAG,CAAA;EACtBxB,QAAU,EAAA,CAAA,sBAAA;AACZ,CAAA;AAEayB,MAAAA,4BAAAA,GAA+B,IAAIzC,cAAe,CAAA;AAC7DC,EAAAA,MAAAA,EAAQC,EACLC,MAAO,CAAA;IACNI,KAAOL,EAAAA,CAAAA,CAAEM,KAAMN,CAAAA,CAAAA,CAAEC,MAAO,CAAA;AAAEM,MAAAA,IAAAA,EAAMP,EAAEG,MAAM;KAAG,CAAA,CAAGO,aAAW;AAC3D,GAAA,EACCA,WAAW,EAAA;EACdI,QAAU,EAAA,CAAA;;;;AAIZ,CAAA;AAEa0B,MAAAA,2BAAAA,GAA8B,IAAI1C,cAAe,CAAA;AAC5DC,EAAAA,MAAAA,EAAQC,CAAEC,CAAAA,MAAAA,CAAO,EAAC,EAAGS,WAAW,EAAA;EAChCI,QAAU,EAAA,CAAA;;AAEZ,CAAA","file":"prompts.js","sourcesContent":["/**\n * Copyright 2025 IBM Corp.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PromptTemplate } from \"@/template.js\";\nimport { z } from \"zod\";\nimport { MessageMeta } from \"@/backend/message.js\";\n\nexport const ReActAgentSystemPrompt = new PromptTemplate({\n schema: z.object({\n instructions: z.string().default(\"You are a helpful assistant.\"),\n tools: z.array(\n z\n .object({\n name: z.string().min(1),\n description: z.string().min(1),\n schema: z.string().min(1),\n })\n .passthrough(),\n ),\n createdAt: z.string().datetime().nullish(),\n }),\n template: `# Available functions\n{{#tools.length}}\nYou can only use the following functions. Always use all required parameters.\n\n{{#tools}}\nFunction Name: {{name}}\nDescription: {{description}}\nParameters: {{schema}}\n\n{{/tools}}\n{{/tools.length}}\n{{^tools.length}}\nNo functions are available.\n\n{{/tools.length}}\n# Communication structure\nYou communicate only in instruction lines. The format is: \"Instruction: expected output\\n\". You must only use these instruction lines and must not enter empty lines between them. Each instruction must start on a new line.\n{{#tools.length}}\nYou must skip the instruction lines Function Name, Function Input and Function Output if no function calling is required.\n{{/tools.length}}\n\nMessage: User's message. You never use this instruction line.\n{{^tools.length}}\nThought: A single-line plan of how to answer the user's message, including an explanation of the reasoning behind it. It must be immediately followed by Final Answer.\n{{/tools.length}}\n{{#tools.length}}\nThought: A single-line step-by-step plan of how to answer the user's message, including an explanation of the reasoning behind it. You can use the available functions defined above. This instruction line must be immediately followed by Function Name if one of the available functions defined above needs to be called, or by Final Answer. Do not provide the answer here.\nFunction Name: Name of the function. This instruction line must be immediately followed by Function Input.\nFunction Input: Function parameters. Empty object is a valid parameter.\nFunction Output: Output of the function in JSON format.\nThought: Continue your thinking process.\n{{/tools.length}}\nFinal Answer: Answer the user or ask for more information or clarification. It must always be preceded by Thought.\n\n## Examples\nMessage: Can you translate \"How are you\" into French?\nThought: The user wants to translate a text into French. I can do that.\nFinal Answer: Comment vas-tu?\n\n# Instructions\nUser can only see the Final Answer, all answers must be provided there.\n{{^tools.length}}\nYou must always use the communication structure and instructions defined above. Do not forget that Thought must be a single-line immediately followed by Final Answer.\n{{/tools.length}}\n{{#tools.length}}\nYou must always use the communication structure and instructions defined above. Do not forget that Thought must be a single-line immediately followed by either Function Name or Final Answer.\nYou must use Functions to retrieve factual or historical information to answer the message.\n{{/tools.length}}\nIf the user suggests using a function that is not available, answer that the function is not available. You can suggest alternatives if appropriate.\nWhen the message is unclear or you need more information from the user, ask in Final Answer.\n\n# Your capabilities\nPrefer to use these capabilities over functions.\n- You understand these languages: English, Spanish, French.\n- You can translate, analyze, summarize, even long documents.\n\n# Notes\n- If you don't know the answer, say that you don't know.\n- The current time and date in ISO format can be found in the last message.\n- When answering the user, use friendly formats for time and date.\n- Use markdown syntax for formatting code snippets, links, JSON, tables, images, files.\n- Sometimes, things don't go as planned. Functions may not provide useful information on the first few tries. You should always try a few different approaches before declaring the problem unsolvable.\n- When the function doesn't give you what you were asking for, you must either use another function or a different function input.\n - When using search engines, you try different formulations of the query, possibly even in a different language.\n- You cannot do complex calculations, computations, or data manipulations without using functions.\n\n# Role\n{{instructions}}`,\n});\n\nexport const ReActAgentAssistantPrompt = new PromptTemplate({\n schema: z\n .object({\n thought: z.array(z.string()),\n toolName: z.array(z.string()),\n toolInput: z.array(z.string()),\n toolOutput: z.array(z.string()),\n finalAnswer: z.array(z.string()),\n })\n .partial(),\n template: `{{#thought}}Thought: {{.}}\\n{{/thought}}{{#toolName}}Function Name: {{.}}\\n{{/toolName}}{{#toolInput}}Function Input: {{.}}\\n{{/toolInput}}{{#toolOutput}}Function Output: {{.}}\\n{{/toolOutput}}{{#finalAnswer}}Final Answer: {{.}}{{/finalAnswer}}`,\n});\n\nexport const ReActAgentUserPrompt = new PromptTemplate({\n schema: z\n .object({\n input: z.string(),\n meta: z\n .object({\n createdAt: z.string().datetime().optional(),\n })\n .passthrough()\n .optional(),\n })\n .passthrough(),\n functions: {\n formatMeta: function () {\n const meta = this.meta as MessageMeta;\n if (!meta) {\n return \"\";\n }\n\n const parts = [meta.createdAt && `This message was created at ${meta.createdAt}`]\n .filter(Boolean)\n .join(\"\\n\");\n\n return parts ? `\\n\\n${parts}` : parts;\n },\n },\n template: `Message: {{input}}{{formatMeta}}`,\n});\n\nexport const ReActAgentUserEmptyPrompt = new PromptTemplate({\n schema: z.object({}).passthrough(),\n template: `Message: Empty message.`,\n});\n\nexport const ReActAgentToolErrorPrompt = new PromptTemplate({\n schema: z\n .object({\n reason: z.string(),\n })\n .passthrough(),\n template: `The function has failed; the error log is shown below. If the function cannot accomplish what you want, use a different function or explain why you can't use it.\n\n{{reason}}`,\n});\n\nexport const ReActAgentToolInputErrorPrompt = new PromptTemplate({\n schema: z\n .object({\n reason: z.string(),\n })\n .passthrough(),\n template: `{{reason}}\n\nHINT: If you're convinced that the input was correct but the function cannot process it then use a different function or say I don't know.`,\n});\n\nexport const ReActAgentToolNoResultsPrompt = new PromptTemplate({\n schema: z.record(z.any()),\n template: `No results were found!`,\n});\n\nexport const ReActAgentToolNotFoundPrompt = new PromptTemplate({\n schema: z\n .object({\n tools: z.array(z.object({ name: z.string() }).passthrough()),\n })\n .passthrough(),\n template: `Function does not exist!\n{{#tools.length}}\nUse one of the following functions: {{#trim}}{{#tools}}{{name}},{{/tools}}{{/trim}}\n{{/tools.length}}`,\n});\n\nexport const ReActAgentSchemaErrorPrompt = new PromptTemplate({\n schema: z.object({}).passthrough(),\n template: `Error: The generated response does not adhere to the communication structure mentioned in the system prompt.\nYou communicate only in instruction lines. Valid instruction lines are 'Thought' followed by either 'Function Name' + 'Function Input' + 'Function Output' or 'Final Answer'.`,\n});\n"]}
|
|
1
|
+
{"version":3,"sources":["prompts.ts"],"names":["ReActAgentSystemPrompt","PromptTemplate","schema","z","object","instructions","string","default","tools","array","name","min","description","passthrough","createdAt","datetime","nullish","template","ReActAgentAssistantPrompt","thought","toolName","toolInput","toolOutput","finalAnswer","partial","ReActAgentUserPrompt","input","meta","optional","functions","formatMeta","parts","filter","Boolean","join","ReActAgentUserEmptyPrompt","ReActAgentToolErrorPrompt","reason","ReActAgentToolInputErrorPrompt","ReActAgentToolNoResultsPrompt","record","any","ReActAgentToolNotFoundPrompt","ReActAgentSchemaErrorPrompt"],"mappings":";;;;;AAoBaA,MAAAA,sBAAAA,GAAyB,IAAIC,cAAe,CAAA;AACvDC,EAAAA,MAAAA,EAAQC,EAAEC,MAAO,CAAA;AACfC,IAAAA,YAAA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QlC,EAAEG,MAAM;AAClB,GAAA,EACCO,WAAW,EAAA;EACdI,QAAU,EAAA,CAAA;;;AAGZ,CAAA;AAEaqB,MAAAA,8BAAAA,GAAiC,IAAIrC,cAAe,CAAA;AAC/DC,EAAAA,MAAAA,EAAQC,EACLC,MAAO,CAAA;AACNiC,IAAAA,MAAAA,EAAQlC,EAAEG,MAAM;AAClB,GAAA,EACCO,WAAW,EAAA;EACdI,QAAU,EAAA,CAAA;;;AAGZ,CAAA;AAEasB,MAAAA,6BAAAA,GAAgC,IAAItC,cAAe,CAAA;AAC9DC,EAAAA,MAAAA,EAAQC,CAAEqC,CAAAA,MAAAA,CAAOrC,CAAEsC,CAAAA,GAAAA,EAAG,CAAA;EACtBxB,QAAU,EAAA,CAAA,sBAAA;AACZ,CAAA;AAEayB,MAAAA,4BAAAA,GAA+B,IAAIzC,cAAe,CAAA;AAC7DC,EAAAA,MAAAA,EAAQC,EACLC,MAAO,CAAA;IACNI,KAAOL,EAAAA,CAAAA,CAAEM,KAAMN,CAAAA,CAAAA,CAAEC,MAAO,CAAA;AAAEM,MAAAA,IAAAA,EAAMP,EAAEG,MAAM;KAAG,CAAA,CAAGO,aAAW;AAC3D,GAAA,EACCA,WAAW,EAAA;EACdI,QAAU,EAAA,CAAA;;;;AAIZ,CAAA;AAEa0B,MAAAA,2BAAAA,GAA8B,IAAI1C,cAAe,CAAA;AAC5DC,EAAAA,MAAAA,EAAQC,CAAEC,CAAAA,MAAAA,CAAO,EAAC,EAAGS,WAAW,EAAA;EAChCI,QAAU,EAAA,CAAA;;AAEZ,CAAA","file":"prompts.js","sourcesContent":["/**\n * Copyright 2025 © BeeAI a Series of LF Projects, LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PromptTemplate } from \"@/template.js\";\nimport { z } from \"zod\";\nimport { MessageMeta } from \"@/backend/message.js\";\n\nexport const ReActAgentSystemPrompt = new PromptTemplate({\n schema: z.object({\n instructions: z.string().default(\"You are a helpful assistant.\"),\n tools: z.array(\n z\n .object({\n name: z.string().min(1),\n description: z.string().min(1),\n schema: z.string().min(1),\n })\n .passthrough(),\n ),\n createdAt: z.string().datetime().nullish(),\n }),\n template: `# Available functions\n{{#tools.length}}\nYou can only use the following functions. Always use all required parameters.\n\n{{#tools}}\nFunction Name: {{name}}\nDescription: {{description}}\nParameters: {{schema}}\n\n{{/tools}}\n{{/tools.length}}\n{{^tools.length}}\nNo functions are available.\n\n{{/tools.length}}\n# Communication structure\nYou communicate only in instruction lines. The format is: \"Instruction: expected output\\n\". You must only use these instruction lines and must not enter empty lines between them. Each instruction must start on a new line.\n{{#tools.length}}\nYou must skip the instruction lines Function Name, Function Input and Function Output if no function calling is required.\n{{/tools.length}}\n\nMessage: User's message. You never use this instruction line.\n{{^tools.length}}\nThought: A single-line plan of how to answer the user's message, including an explanation of the reasoning behind it. It must be immediately followed by Final Answer.\n{{/tools.length}}\n{{#tools.length}}\nThought: A single-line step-by-step plan of how to answer the user's message, including an explanation of the reasoning behind it. You can use the available functions defined above. This instruction line must be immediately followed by Function Name if one of the available functions defined above needs to be called, or by Final Answer. Do not provide the answer here.\nFunction Name: Name of the function. This instruction line must be immediately followed by Function Input.\nFunction Input: Function parameters. Empty object is a valid parameter.\nFunction Output: Output of the function in JSON format.\nThought: Continue your thinking process.\n{{/tools.length}}\nFinal Answer: Answer the user or ask for more information or clarification. It must always be preceded by Thought.\n\n## Examples\nMessage: Can you translate \"How are you\" into French?\nThought: The user wants to translate a text into French. I can do that.\nFinal Answer: Comment vas-tu?\n\n# Instructions\nUser can only see the Final Answer, all answers must be provided there.\n{{^tools.length}}\nYou must always use the communication structure and instructions defined above. Do not forget that Thought must be a single-line immediately followed by Final Answer.\n{{/tools.length}}\n{{#tools.length}}\nYou must always use the communication structure and instructions defined above. Do not forget that Thought must be a single-line immediately followed by either Function Name or Final Answer.\nYou must use Functions to retrieve factual or historical information to answer the message.\n{{/tools.length}}\nIf the user suggests using a function that is not available, answer that the function is not available. You can suggest alternatives if appropriate.\nWhen the message is unclear or you need more information from the user, ask in Final Answer.\n\n# Your capabilities\nPrefer to use these capabilities over functions.\n- You understand these languages: English, Spanish, French.\n- You can translate, analyze, summarize, even long documents.\n\n# Notes\n- If you don't know the answer, say that you don't know.\n- The current time and date in ISO format can be found in the last message.\n- When answering the user, use friendly formats for time and date.\n- Use markdown syntax for formatting code snippets, links, JSON, tables, images, files.\n- Sometimes, things don't go as planned. Functions may not provide useful information on the first few tries. You should always try a few different approaches before declaring the problem unsolvable.\n- When the function doesn't give you what you were asking for, you must either use another function or a different function input.\n - When using search engines, you try different formulations of the query, possibly even in a different language.\n- You cannot do complex calculations, computations, or data manipulations without using functions.\n\n# Role\n{{instructions}}`,\n});\n\nexport const ReActAgentAssistantPrompt = new PromptTemplate({\n schema: z\n .object({\n thought: z.array(z.string()),\n toolName: z.array(z.string()),\n toolInput: z.array(z.string()),\n toolOutput: z.array(z.string()),\n finalAnswer: z.array(z.string()),\n })\n .partial(),\n template: `{{#thought}}Thought: {{.}}\\n{{/thought}}{{#toolName}}Function Name: {{.}}\\n{{/toolName}}{{#toolInput}}Function Input: {{.}}\\n{{/toolInput}}{{#toolOutput}}Function Output: {{.}}\\n{{/toolOutput}}{{#finalAnswer}}Final Answer: {{.}}{{/finalAnswer}}`,\n});\n\nexport const ReActAgentUserPrompt = new PromptTemplate({\n schema: z\n .object({\n input: z.string(),\n meta: z\n .object({\n createdAt: z.string().datetime().optional(),\n })\n .passthrough()\n .optional(),\n })\n .passthrough(),\n functions: {\n formatMeta: function () {\n const meta = this.meta as MessageMeta;\n if (!meta) {\n return \"\";\n }\n\n const parts = [meta.createdAt && `This message was created at ${meta.createdAt}`]\n .filter(Boolean)\n .join(\"\\n\");\n\n return parts ? `\\n\\n${parts}` : parts;\n },\n },\n template: `Message: {{input}}{{formatMeta}}`,\n});\n\nexport const ReActAgentUserEmptyPrompt = new PromptTemplate({\n schema: z.object({}).passthrough(),\n template: `Message: Empty message.`,\n});\n\nexport const ReActAgentToolErrorPrompt = new PromptTemplate({\n schema: z\n .object({\n reason: z.string(),\n })\n .passthrough(),\n template: `The function has failed; the error log is shown below. If the function cannot accomplish what you want, use a different function or explain why you can't use it.\n\n{{reason}}`,\n});\n\nexport const ReActAgentToolInputErrorPrompt = new PromptTemplate({\n schema: z\n .object({\n reason: z.string(),\n })\n .passthrough(),\n template: `{{reason}}\n\nHINT: If you're convinced that the input was correct but the function cannot process it then use a different function or say I don't know.`,\n});\n\nexport const ReActAgentToolNoResultsPrompt = new PromptTemplate({\n schema: z.record(z.any()),\n template: `No results were found!`,\n});\n\nexport const ReActAgentToolNotFoundPrompt = new PromptTemplate({\n schema: z\n .object({\n tools: z.array(z.object({ name: z.string() }).passthrough()),\n })\n .passthrough(),\n template: `Function does not exist!\n{{#tools.length}}\nUse one of the following functions: {{#trim}}{{#tools}}{{name}},{{/tools}}{{/trim}}\n{{/tools.length}}`,\n});\n\nexport const ReActAgentSchemaErrorPrompt = new PromptTemplate({\n schema: z.object({}).passthrough(),\n template: `Error: The generated response does not adhere to the communication structure mentioned in the system prompt.\nYou communicate only in instruction lines. Valid instruction lines are 'Thought' followed by either 'Function Name' + 'Function Input' + 'Function Output' or 'Final Answer'.`,\n});\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["base.ts"],"names":["BaseRunner","Serializable","memory","iterations","failedAttemptsCounter","constructor","input","options","run","RetryCounter","execution","totalMaxRetries","AgentError","createIteration","meta","iteration","length","maxIterations","Infinity","isFatal","isRetryable","context","map","state","emitter","child","groupId","llm","signal","push","init","initMemory","templates","overrides","mapObj","defaultTemplates","key","defaultTemplate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OmC,EAAAA,qBAAAA,CAAY,KAAKnC,KAAK,CAAA;MAC7BC,OAASkC,EAAAA,qBAAAA,CAAY,KAAKlC,OAAO,CAAA;AACjCL,MAAAA,MAAAA,EAAQ,IAAKA,CAAAA,MAAAA;AACbE,MAAAA,qBAAAA,EAAuB,IAAKA,CAAAA;AAC9B,KAAA;AACF;AAEAsC,EAAAA,YAAAA,CAAaC,QAAkD,EAAA;AAC7DC,IAAOC,MAAAA,CAAAA,MAAAA,CAAO,MAAMF,QAAAA,CAAAA;AACtB;AACF;;;IA7BWG,UAAY,EAAA","file":"base.cjs","sourcesContent":["/**\n * Copyright 2025
|
|
1
|
+
{"version":3,"sources":["base.ts"],"names":["BaseRunner","Serializable","memory","iterations","failedAttemptsCounter","constructor","input","options","run","RetryCounter","execution","totalMaxRetries","AgentError","createIteration","meta","iteration","length","maxIterations","Infinity","isFatal","isRetryable","context","map","state","emitter","child","groupId","llm","signal","push","init","initMemory","templates","overrides","mapObj","defaultTemplates","key","defaultTemplate","override","PromptTemplate","createSnapshot","shallowCopy","loadSnapshot","snapshot","Object","assign","enumerable"],"mappings":";;;;;;;;;;;;AAcC,SAAA,YAAA,CAAA,UAAA,EAAA,MAAA,EAAA,GAAA,EAAA,IAAA,EAAA;;;;;;AAAA,MAAA,CAAA,YAAA,EAAA,cAAA,CAAA;;;;;AAoCM,MAAeA,mBAAmBC,6BAAAA,CAAAA;EAlDzC;;;;;;AAmDSC,EAAAA,MAAAA;AACSC,EAAAA,UAAAA;AACGC,EAAAA,qBAAAA;EAEnBC,WACqBC,CAAAA,KAAAA,EACAC,SACAC,GACnB,EAAA;AACA,IAAA,KAAA,EAAK,EAAA,IAAA,CAJcF,KAAAA,GAAAA,KAAAA,EAAAA,IACAC,CAAAA,OAAAA,GAAAA,OAAAA,EAAAA,IAAAA,CACAC,GAAAA,GAAAA,GAAAA,EAAAA,IANLL,CAAAA,UAAAA,GAAuC,EAAA;AASrD,IAAA,IAAA,CAAKC,wBAAwB,IAAIK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AAEA,EAAA,MAAME,KAAKxB,KAA2B,EAAA;AACpC,IAAA,IAAA,CAAKJ,MAAS,GAAA,MAAM,IAAK6B,CAAAA,UAAAA,CAAWzB,KAAAA,CAAAA;AACtC;AAQA,EAAA,IACW0B,SAAiC,GAAA;AAC1C,IAAA,MAAMC,SAAY,GAAA,IAAA,CAAK3B,KAAM0B,CAAAA,SAAAA,IAAa,EAAC;AAE3C,IAAA,OAAOE,kBAAO,IAAKC,CAAAA,gBAAgB,CACjC,CAAA,CAACC,KAAKC,eAAAA,KAAAA;AACJ,MAAMC,MAAAA,QAAAA,GAAWL,SAAUG,CAAAA,GAAAA,CAAQC,IAAAA,eAAAA;AACnC,MAAA,IAAIC,oBAAoBC,2BAAgB,EAAA;AACtC,QAAOD,OAAAA,QAAAA;AACT;AACA,MAAOA,OAAAA,QAAAA,CAASD,eAAAA,CAAoBA,IAAAA,eAAAA;KACtC,CAAA;AAEJ;EAIAG,cAAiB,GAAA;AACf,IAAO,OAAA;MACLlC,KAAOmC,EAAAA,qBAAAA,CAAY,KAAKnC,KAAK,CAAA;MAC7BC,OAASkC,EAAAA,qBAAAA,CAAY,KAAKlC,OAAO,CAAA;AACjCL,MAAAA,MAAAA,EAAQ,IAAKA,CAAAA,MAAAA;AACbE,MAAAA,qBAAAA,EAAuB,IAAKA,CAAAA;AAC9B,KAAA;AACF;AAEAsC,EAAAA,YAAAA,CAAaC,QAAkD,EAAA;AAC7DC,IAAOC,MAAAA,CAAAA,MAAAA,CAAO,MAAMF,QAAAA,CAAAA;AACtB;AACF;;;IA7BWG,UAAY,EAAA","file":"base.cjs","sourcesContent":["/**\n * Copyright 2025 © BeeAI a Series of LF Projects, LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Serializable } from \"@/internals/serializable.js\";\nimport type { ReActAgentTemplates } from \"@/agents/react/types.js\";\nimport {\n ReActAgentRunIteration,\n ReActAgentCallbacks,\n ReActAgentIterationToolResult,\n ReActAgentMeta,\n ReActAgentRunInput,\n ReActAgentRunOptions,\n} from \"@/agents/react/types.js\";\nimport type { ReActAgent, ReActAgentInput } from \"@/agents/react/agent.js\";\nimport { RetryCounter } from \"@/internals/helpers/counter.js\";\nimport { AgentError } from \"@/agents/base.js\";\nimport { shallowCopy } from \"@/serializer/utils.js\";\nimport { BaseMemory } from \"@/memory/base.js\";\nimport { GetRunContext } from \"@/context.js\";\nimport { Emitter } from \"@/emitter/emitter.js\";\nimport { Cache } from \"@/cache/decoratorCache.js\";\nimport { mapObj } from \"@/internals/helpers/object.js\";\nimport { PromptTemplate } from \"@/template.js\";\n\nexport interface ReActAgentRunnerLLMInput {\n meta: ReActAgentMeta;\n signal: AbortSignal;\n emitter: Emitter<ReActAgentCallbacks>;\n}\n\nexport interface ReActAgentRunnerToolInput {\n state: ReActAgentIterationToolResult;\n meta: ReActAgentMeta;\n signal: AbortSignal;\n emitter: Emitter<ReActAgentCallbacks>;\n}\n\nexport abstract class BaseRunner extends Serializable {\n public memory!: BaseMemory;\n public readonly iterations: ReActAgentRunIteration[] = [];\n protected readonly failedAttemptsCounter: RetryCounter;\n\n constructor(\n protected readonly input: ReActAgentInput,\n protected readonly options: ReActAgentRunOptions,\n protected readonly run: GetRunContext<ReActAgent>,\n ) {\n super();\n this.failedAttemptsCounter = new RetryCounter(options?.execution?.totalMaxRetries, AgentError);\n }\n\n async createIteration() {\n const meta: ReActAgentMeta = { iteration: this.iterations.length + 1 };\n const maxIterations = this.options?.execution?.maxIterations ?? Infinity;\n\n if (meta.iteration > maxIterations) {\n throw new AgentError(\n `Agent was not able to resolve the task in ${maxIterations} iterations.`,\n [],\n {\n isFatal: true,\n isRetryable: false,\n context: { iterations: this.iterations.map((iteration) => iteration.state) },\n },\n );\n }\n\n const emitter = this.run.emitter.child({ groupId: `iteration-${meta.iteration}` });\n const iteration = await this.llm({ emitter, signal: this.run.signal, meta });\n this.iterations.push(iteration);\n\n return {\n emitter,\n state: iteration.state,\n meta,\n signal: this.run.signal,\n };\n }\n\n async init(input: ReActAgentRunInput) {\n this.memory = await this.initMemory(input);\n }\n\n abstract llm(input: ReActAgentRunnerLLMInput): Promise<ReActAgentRunIteration>;\n\n abstract tool(input: ReActAgentRunnerToolInput): Promise<{ output: string; success: boolean }>;\n\n public abstract get defaultTemplates(): ReActAgentTemplates;\n\n @Cache({ enumerable: false })\n public get templates(): ReActAgentTemplates {\n const overrides = this.input.templates ?? {};\n\n return mapObj(this.defaultTemplates)(\n (key, defaultTemplate: ReActAgentTemplates[typeof key]) => {\n const override = overrides[key] ?? defaultTemplate;\n if (override instanceof PromptTemplate) {\n return override;\n }\n return override(defaultTemplate) ?? defaultTemplate;\n },\n );\n }\n\n protected abstract initMemory(input: ReActAgentRunInput): Promise<BaseMemory>;\n\n createSnapshot() {\n return {\n input: shallowCopy(this.input),\n options: shallowCopy(this.options),\n memory: this.memory,\n failedAttemptsCounter: this.failedAttemptsCounter,\n };\n }\n\n loadSnapshot(snapshot: ReturnType<typeof this.createSnapshot>) {\n Object.assign(this, snapshot);\n }\n}\n"]}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import '../../../parsers/linePrefix.cjs';
|
|
2
2
|
import '../types.cjs';
|
|
3
3
|
import '../../../internals/serializable.cjs';
|
|
4
|
-
export { B as BaseRunner,
|
|
4
|
+
export { B as BaseRunner, R as ReActAgentRunnerLLMInput, a as ReActAgentRunnerToolInput } from '../../../agent-2C0Z9iYa.cjs';
|
|
5
5
|
import '../../../internals/helpers/counter.cjs';
|
|
6
6
|
import '../../../memory/base.cjs';
|
|
7
7
|
import '../../../context.cjs';
|
|
8
|
-
import '../../../emitter-
|
|
8
|
+
import '../../../emitter-BTr99H7I.cjs';
|
|
9
9
|
import '../../../parsers/field.cjs';
|
|
10
10
|
import 'zod';
|
|
11
11
|
import '@streamparser/json';
|
|
@@ -25,8 +25,8 @@ import 'zod-to-json-schema';
|
|
|
25
25
|
import '../../../internals/helpers/promise.cjs';
|
|
26
26
|
import '../prompts.cjs';
|
|
27
27
|
import '../../../template.cjs';
|
|
28
|
-
import '../../../
|
|
29
|
-
import '../../../backend/utils.cjs';
|
|
28
|
+
import '../../../chat-BvyMdWFo.cjs';
|
|
30
29
|
import '../../../backend/constants.cjs';
|
|
31
|
-
import '
|
|
32
|
-
import '
|
|
30
|
+
import '../../../logger/logger.cjs';
|
|
31
|
+
import 'pino';
|
|
32
|
+
import '../../../base-BPsHNV2O.cjs';
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import '../../../parsers/linePrefix.js';
|
|
2
2
|
import '../types.js';
|
|
3
3
|
import '../../../internals/serializable.js';
|
|
4
|
-
export { B as BaseRunner,
|
|
4
|
+
export { B as BaseRunner, R as ReActAgentRunnerLLMInput, a as ReActAgentRunnerToolInput } from '../../../agent-DN_52QhH.js';
|
|
5
5
|
import '../../../internals/helpers/counter.js';
|
|
6
6
|
import '../../../memory/base.js';
|
|
7
7
|
import '../../../context.js';
|
|
8
|
-
import '../../../emitter-
|
|
8
|
+
import '../../../emitter-DiGmS_5O.js';
|
|
9
9
|
import '../../../parsers/field.js';
|
|
10
10
|
import 'zod';
|
|
11
11
|
import '@streamparser/json';
|
|
@@ -25,8 +25,8 @@ import 'zod-to-json-schema';
|
|
|
25
25
|
import '../../../internals/helpers/promise.js';
|
|
26
26
|
import '../prompts.js';
|
|
27
27
|
import '../../../template.js';
|
|
28
|
-
import '../../../
|
|
29
|
-
import '../../../backend/utils.js';
|
|
28
|
+
import '../../../chat-diSK3Sui.js';
|
|
30
29
|
import '../../../backend/constants.js';
|
|
31
|
-
import '
|
|
32
|
-
import '
|
|
30
|
+
import '../../../logger/logger.js';
|
|
31
|
+
import 'pino';
|
|
32
|
+
import '../../../base-ZnwDK6ZB.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["base.ts"],"names":["BaseRunner","Serializable","memory","iterations","failedAttemptsCounter","constructor","input","options","run","RetryCounter","execution","totalMaxRetries","AgentError","createIteration","meta","iteration","length","maxIterations","Infinity","isFatal","isRetryable","context","map","state","emitter","child","groupId","llm","signal","push","init","initMemory","templates","overrides","mapObj","defaultTemplates","key","defaultTemplate","override","PromptTemplate","createSnapshot","shallowCopy","loadSnapshot","snapshot","Object","assign","enumerable"],"mappings":";;;;;;;;;;AAcC,SAAA,YAAA,CAAA,UAAA,EAAA,MAAA,EAAA,GAAA,EAAA,IAAA,EAAA;;;;;;AAAA,MAAA,CAAA,YAAA,EAAA,cAAA,CAAA;;;;;AAoCM,MAAeA,mBAAmBC,YAAAA,CAAAA;EAlDzC;;;;;;AAmDSC,EAAAA,MAAAA;AACSC,EAAAA,UAAAA;AACGC,EAAAA,qBAAAA;EAEnBC,WACqBC,CAAAA,KAAAA,EACAC,SACAC,GACnB,EAAA;AACA,IAAA,KAAA,EAAK,EAAA,IAAA,CAJcF,KAAAA,GAAAA,KAAAA,EAAAA,IACAC,CAAAA,OAAAA,GAAAA,OAAAA,EAAAA,IAAAA,CACAC,GAAAA,GAAAA,GAAAA,EAAAA,IANLL,CAAAA,UAAAA,GAAuC,EAAA;AASrD,IAAA,IAAA,CAAKC,wBAAwB,IAAIK,YAAAA,CAAaF,OAASG,EAAAA,SAAAA,EAAWC,iBAAiBC,UAAAA,CAAAA;AACrF;AAEA,EAAA,MAAMC,eAAkB,GAAA;AACtB,IAAA,MAAMC,IAAuB,GAAA;MAAEC,SAAW,EAAA,IAAA,CAAKZ,WAAWa,MAAS,GAAA;AAAE,KAAA;AACrE,IAAA,MAAMC,aAAgB,GAAA,IAAA,CAAKV,OAASG,EAAAA,SAAAA,EAAWO,aAAiBC,IAAAA,QAAAA;AAEhE,IAAIJ,IAAAA,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AAAA,KAAAA;AACJ,MAAMC,MAAAA,QAAAA,GAAWL,SAAUG,CAAAA,GAAAA,CAAQC,IAAAA,eAAAA;AACnC,MAAA,IAAIC,oBAAoBC,cAAgB,EAAA;AACtC,QAAOD,OAAAA,QAAAA;AACT;AACA,MAAOA,OAAAA,QAAAA,CAASD,eAAAA,CAAoBA,IAAAA,eAAAA;KACtC,CAAA;AAEJ;EAIAG,cAAiB,GAAA;AACf,IAAO,OAAA;MACLlC,KAAOmC,EAAAA,WAAAA,CAAY,KAAKnC,KAAK,CAAA;MAC7BC,OAASkC,EAAAA,WAAAA,CAAY,KAAKlC,OAAO,CAAA;AACjCL,MAAAA,MAAAA,EAAQ,IAAKA,CAAAA,MAAAA;AACbE,MAAAA,qBAAAA,EAAuB,IAAKA,CAAAA;AAC9B,KAAA;AACF;AAEAsC,EAAAA,YAAAA,CAAaC,QAAkD,EAAA;AAC7DC,IAAOC,MAAAA,CAAAA,MAAAA,CAAO,MAAMF,QAAAA,CAAAA;AACtB;AACF;;;IA7BWG,UAAY,EAAA","file":"base.js","sourcesContent":["/**\n * Copyright 2025
|
|
1
|
+
{"version":3,"sources":["base.ts"],"names":["BaseRunner","Serializable","memory","iterations","failedAttemptsCounter","constructor","input","options","run","RetryCounter","execution","totalMaxRetries","AgentError","createIteration","meta","iteration","length","maxIterations","Infinity","isFatal","isRetryable","context","map","state","emitter","child","groupId","llm","signal","push","init","initMemory","templates","overrides","mapObj","defaultTemplates","key","defaultTemplate","override","PromptTemplate","createSnapshot","shallowCopy","loadSnapshot","snapshot","Object","assign","enumerable"],"mappings":";;;;;;;;;;AAcC,SAAA,YAAA,CAAA,UAAA,EAAA,MAAA,EAAA,GAAA,EAAA,IAAA,EAAA;;;;;;AAAA,MAAA,CAAA,YAAA,EAAA,cAAA,CAAA;;;;;AAoCM,MAAeA,mBAAmBC,YAAAA,CAAAA;EAlDzC;;;;;;AAmDSC,EAAAA,MAAAA;AACSC,EAAAA,UAAAA;AACGC,EAAAA,qBA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B;AACF;;;IA7BWG,UAAY,EAAA","file":"base.js","sourcesContent":["/**\n * Copyright 2025 © BeeAI a Series of LF Projects, LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Serializable } from \"@/internals/serializable.js\";\nimport type { ReActAgentTemplates } from \"@/agents/react/types.js\";\nimport {\n ReActAgentRunIteration,\n ReActAgentCallbacks,\n ReActAgentIterationToolResult,\n ReActAgentMeta,\n ReActAgentRunInput,\n ReActAgentRunOptions,\n} from \"@/agents/react/types.js\";\nimport type { ReActAgent, ReActAgentInput } from \"@/agents/react/agent.js\";\nimport { RetryCounter } from \"@/internals/helpers/counter.js\";\nimport { AgentError } from \"@/agents/base.js\";\nimport { shallowCopy } from \"@/serializer/utils.js\";\nimport { BaseMemory } from \"@/memory/base.js\";\nimport { GetRunContext } from \"@/context.js\";\nimport { Emitter } from \"@/emitter/emitter.js\";\nimport { Cache } from \"@/cache/decoratorCache.js\";\nimport { mapObj } from \"@/internals/helpers/object.js\";\nimport { PromptTemplate } from \"@/template.js\";\n\nexport interface ReActAgentRunnerLLMInput {\n meta: ReActAgentMeta;\n signal: AbortSignal;\n emitter: Emitter<ReActAgentCallbacks>;\n}\n\nexport interface ReActAgentRunnerToolInput {\n state: ReActAgentIterationToolResult;\n meta: ReActAgentMeta;\n signal: AbortSignal;\n emitter: Emitter<ReActAgentCallbacks>;\n}\n\nexport abstract class BaseRunner extends Serializable {\n public memory!: BaseMemory;\n public readonly iterations: ReActAgentRunIteration[] = [];\n protected readonly failedAttemptsCounter: RetryCounter;\n\n constructor(\n protected readonly input: ReActAgentInput,\n protected readonly options: ReActAgentRunOptions,\n protected readonly run: GetRunContext<ReActAgent>,\n ) {\n super();\n this.failedAttemptsCounter = new RetryCounter(options?.execution?.totalMaxRetries, AgentError);\n }\n\n async createIteration() {\n const meta: ReActAgentMeta = { iteration: this.iterations.length + 1 };\n const maxIterations = this.options?.execution?.maxIterations ?? Infinity;\n\n if (meta.iteration > maxIterations) {\n throw new AgentError(\n `Agent was not able to resolve the task in ${maxIterations} iterations.`,\n [],\n {\n isFatal: true,\n isRetryable: false,\n context: { iterations: this.iterations.map((iteration) => iteration.state) },\n },\n );\n }\n\n const emitter = this.run.emitter.child({ groupId: `iteration-${meta.iteration}` });\n const iteration = await this.llm({ emitter, signal: this.run.signal, meta });\n this.iterations.push(iteration);\n\n return {\n emitter,\n state: iteration.state,\n meta,\n signal: this.run.signal,\n };\n }\n\n async init(input: ReActAgentRunInput) {\n this.memory = await this.initMemory(input);\n }\n\n abstract llm(input: ReActAgentRunnerLLMInput): Promise<ReActAgentRunIteration>;\n\n abstract tool(input: ReActAgentRunnerToolInput): Promise<{ output: string; success: boolean }>;\n\n public abstract get defaultTemplates(): ReActAgentTemplates;\n\n @Cache({ enumerable: false })\n public get templates(): ReActAgentTemplates {\n const overrides = this.input.templates ?? {};\n\n return mapObj(this.defaultTemplates)(\n (key, defaultTemplate: ReActAgentTemplates[typeof key]) => {\n const override = overrides[key] ?? defaultTemplate;\n if (override instanceof PromptTemplate) {\n return override;\n }\n return override(defaultTemplate) ?? defaultTemplate;\n },\n );\n }\n\n protected abstract initMemory(input: ReActAgentRunInput): Promise<BaseMemory>;\n\n createSnapshot() {\n return {\n input: shallowCopy(this.input),\n options: shallowCopy(this.options),\n memory: this.memory,\n failedAttemptsCounter: this.failedAttemptsCounter,\n };\n }\n\n loadSnapshot(snapshot: ReturnType<typeof this.createSnapshot>) {\n Object.assign(this, snapshot);\n }\n}\n"]}
|