Skip to content

Fix BedrockAugmentedLLM config and generate_structured() #253

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 6, 2025

Conversation

StreetLamb
Copy link
Collaborator

@StreetLamb StreetLamb commented Jun 6, 2025

Fixes #247

Summary by CodeRabbit

  • Bug Fixes
    • Improved error handling for missing Bedrock configuration, providing clearer error messages.
    • Corrected AWS region selection for Bedrock client requests to ensure proper connectivity.
    • Updated message formatting when sending requests to Bedrock for better compatibility.

Copy link

coderabbitai bot commented Jun 6, 2025

Walkthrough

The changes update error handling in the BedrockAugmentedLLM constructor to ensure missing Bedrock configuration is caught early. In BedrockCompletionTasks, AWS region references are corrected, and the message format sent to the Bedrock client is simplified to avoid sending non-text prompts, aligning with the Bedrock provider's requirements.

Changes

File(s) Change Summary
src/mcp_agent/workflows/llm/augmented_llm_bedrock.py Added error handling for missing Bedrock config in constructor; fixed AWS region reference; updated message format for Bedrock calls

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Orchestrator
    participant BedrockAugmentedLLM
    participant BedrockClient

    User->>Orchestrator: Initiate task (generate/generate_structured)
    Orchestrator->>BedrockAugmentedLLM: Request completion/structured completion
    BedrockAugmentedLLM->>BedrockClient: Send request with corrected region and message format
    BedrockClient-->>BedrockAugmentedLLM: Return response
    BedrockAugmentedLLM-->>Orchestrator: Return processed response
    Orchestrator-->>User: Deliver result
Loading

Assessment against linked issues

Objective Addressed Explanation
Fix BedrockAugmentedLLM orchestration failures due to region misconfiguration (#247)
Ensure message content sent to Bedrock is string, not list, to prevent NotImplementedError (#247)
Add early error handling for missing Bedrock config in context (#247)

Poem

In the warren of code, a bug did hop,
Bedrock’s config missing—oh, what a flop!
Now with regions set right and messages clear,
The orchestrator runs without fear.
🐇✨ No more errors, just smooth delight—
This rabbit’s code now works just right!

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0b7a645 and 79311ee.

📒 Files selected for processing (1)
  • src/mcp_agent/workflows/llm/augmented_llm_bedrock.py (4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/mcp_agent/workflows/llm/augmented_llm_bedrock.py (2)
src/mcp_agent/app.py (2)
  • logger (164-168)
  • config (128-129)
src/mcp_agent/logging/logger.py (1)
  • error (135-143)
🔇 Additional comments (3)
src/mcp_agent/workflows/llm/augmented_llm_bedrock.py (3)

72-78: Excellent error handling for missing Bedrock configuration.

This early validation prevents runtime errors and provides clear feedback when the required Bedrock configuration is missing. The combination of logging and raising a descriptive ValueError follows best practices.


423-423: Consistent AWS region configuration fix.

Good consistency with the previous fix at line 387. Both completion task methods now correctly access the AWS region configuration.


434-434:

✅ Verification successful

Message format simplification looks good.

The change from nested text structure to direct string content simplifies the message format for structured completion. This likely fixes compatibility with the Bedrock API or instructor library expectations.


🌐 Web query:

What is the expected message format for the instructor library when using instructor.from_bedrock() with Bedrock's chat completions API?

💡 Result:

The instructor library, when used with AWS Bedrock via instructor.from_bedrock(), follows a specific message format for the chat completions API. This format enables structured outputs by integrating Pydantic models with Bedrock's foundation models.

Message Format Structure

When using instructor with Bedrock's chat completions API, you'll need to structure your messages as a list of dictionaries, with each dictionary representing a message in the conversation. The basic structure includes:

messages=[
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Extract: Jason is 25 years old"},
]

Each message dictionary contains two key components:

  • A role field that can be "system", "user", or "assistant"
  • A content field that contains the actual message text

Working with Bedrock Models

When using instructor with Bedrock, the implementation follows this pattern:

import boto3
import instructor
from pydantic import BaseModel

# Initialize the Bedrock client
bedrock_client = boto3.client('bedrock-runtime')

# Enable instructor patches for Bedrock client
client = instructor.from_bedrock(bedrock_client)

class User(BaseModel):
    name: str
    age: int

# Create structured output
user = client.chat.completions.create(
    modelId="anthropic.claude-3-sonnet-20240229-v1:0",
    messages=[
        {"role": "user", "content": [{"text": "Extract: Jason is 25 years old"}]},
    ],
    response_model=User,
)

Note that with some models like Claude, the content field can take a list of content objects with a text key[4].

Response Structure

When using instructor with Bedrock, the response will be a Pydantic object instance of your defined model rather than the raw API response. For example, the above code would return a User object with name="Jason" and age=25[4].

Behind the scenes, instructor is managing:

  1. Sending your messages to the model
  2. Adding special instructions to extract structured data
  3. Parsing the response into your Pydantic model
  4. Validating that the response matches your model's schema

Advanced Usage

For more complex scenarios, you can incorporate system messages to provide context:

client.chat.completions.create(
    modelId="anthropic.claude-3-sonnet-20240229-v1:0",
    messages=[
        {"role": "system", "content": "Extract structured information based on the user's request."},
        {"role": "user", "content": "Create a user for a model with a name, age, and properties."},
    ],
    response_model=User,
)

This format aligns with how the Anthropic Claude models work in Bedrock, allowing you to leverage structured outputs while maintaining the familiar chat completion interface[6].

Citations:


Approve message format update

The instructor.from_bedrock chat completions API accepts messages as a list of {role: string, content: string} dictionaries. Switching from a nested text-object list to a direct string aligns with the documented contract and maintains compatibility with structured outputs. No further changes needed.

@StreetLamb StreetLamb requested a review from saqadri June 6, 2025 13:42
@saqadri saqadri merged commit 28f64cc into main Jun 6, 2025
7 checks passed
@StreetLamb StreetLamb deleted the fix/augmented_llm_bedrock branch June 6, 2025 23:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Orchestrator with BedrockAugmentedLLM is failing
2 participants