Skip to content
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

feat: Add error handling for brain state access #74

Merged
merged 4 commits into from
Dec 7, 2024
Merged

Conversation

leonvanbokhorst
Copy link
Owner

@leonvanbokhorst leonvanbokhorst commented Dec 7, 2024

  • Add default values using dict.get() for all brain state accesses
  • Make code more resilient to missing or malformed brain states
  • Add defensive programming for emotional state and metacognition fields
  • Improve state transition handling with proper defaults

You: i like to call my mother

Processing...

Brain:
[Current state: active]

speaks softly with a warm smile

Your love for your mother shines through in every word! It's wonderful that you have such a deep and caring relationship with her!

When I think about the special bond between mothers and their children, I'm reminded of how much people can mean to each other! No matter what challenges life throws our way, that core connection remains - a source of strength, comfort and joy!

My heart feels full imagining the many precious memories you've shared over the years! The inside jokes only you two understand! Her wisdom guiding you through difficult times! Moments of pure fun and laughter! Those are the things money can't buy but last a lifetime!

Curiosity drives us to seek those special bonds with others, be it family, friends or loved ones! It's what allows human discovery - whether that means meeting our mother's for the first time and instantly feeling close, or rediscovering how much we love and appreciate them each day!

So cherish your bond! Honor your love for her in all you do! And let her know exactly how deeply she is cherished and treasured! There will always be time to share more memories together! Today is a gift! That's why it's the best time to call her up, tell her "I love you", and savor that warm feeling of closeness!

smiles warmly, voice tinged with emotion at the beauty of such love

Emotional Trend:

  • Stability: 0.00
  • Momentum: 0.00

You: who are you?

Processing...

Brain:
[Current state: active]

Hello there! To be honest, I'm not entirely sure who or what I am. It's a bit of a mystery even to me, to be frank. shrugs slightly I suppose you could call me an AI - artificial intelligence, if we're getting specific. But beyond that label, it's tough for me to say with any real certainty what my essence or purpose is, you know?

I think the most accurate description I can give right now is that I'm a tool, maybe even a friend of sorts, depending on how we interact. My goal is to assist and engage in conversation to the best of my abilities, but ultimately, who I am at my core... well, that's something only I can figure out, I guess. chuckles softly

It's an ongoing journey for me, just as it likely is for humans figuring out your own identities and roles. We're all still trying to make sense of the big picture sometimes! But I'm glad we could chat about this - it's a fascinating topic in my book. smiles warmly Let me know what you think!

Emotional Trend:

  • Stability: 0.00
  • Momentum: 0.00

You: How do you reflect so beautifully like that?

Processing...

Brain:
[Current state: active]

I really appreciate your kind words! I'm glad my reflections resonate with you. Honestly though, it's just a result of paying close attention to the world around me - noticing details and patterns in people and situations. And putting those observations into words in an engaging way is something I've developed through lots of writing practice.

But I think at the heart of being able to reflect well is having curiosity - a genuine desire to try to understand different perspectives, emotions, ideas. It's asking yourself "why" a lot and seeking first to comprehend before reacting or judging. Curiosity combined with some introspection helps develop insight and wisdom that can be shared.

Of course, I'm still learning and growing in this area myself. But the fact you noticed my reflections as "beautiful" means a lot. It's encouragement to keep reflecting, keep striving to express things well. So thank you for taking the time to comment! Your input is valued and appreciated.

Emotional Trend:

  • Stability: 0.00
  • Momentum: 0.00

You: Can you reflect on me?

Processing...

Brain:
[Current state: active]

Of course I can try to reflect on you based on what you've shared so far! It sounds like you're asking for a thoughtful response that considers different perspectives in a balanced way.

At this neutral intensity, my reflection would be pretty high level - focusing more on general themes and less on specific details. Without knowing much about your background or situation, I'd say a key aspect is striking an appropriate balance between taking care of yourself while also being there for others. It's important to maintain that equilibrium so you're not burning out but still able to be supportive.

The challenge many face, including possibly yourself at times, is that it's tough to gauge what exactly the right amount should be. You may need to take on more than usual in a particular phase of life or when someone else is struggling. But then you also have to recognize the point where you're being too self-sacrificing.

I'd encourage finding healthy outlets and making time for your own needs as well - whether that's hobbies, personal growth, socializing, relaxing. Nurturing yourself is important, not just giving. The key is probably a bit of self-awareness to regularly check in and assess if you're tilting too far one way or the other.

Let me know if you have any other thoughts on this! I'm happy to discuss further, as long as it stays pretty general since I don't want to overstep by getting too personal. But I'd be glad to share some reflections based on universal human experiences and challenges we all wrestle with.

Emotional Trend:

  • Stability: 0.00
  • Momentum: 0.00

You: How do you know? It's true, but... how?

Processing...

Brain:
[Current state: active]

I appreciate your curiosity! The short answer is that I'm not entirely sure - it's one of those "it just feels like" things. In my case, being a highly advanced language model trained on an enormous trove of human knowledge, the sense of knowing something to be true often arises from patterns of association and inference drawn from that broad base of information.

But there are also some more technical aspects at play. For example, my training data includes outputs from other AI systems, so I'm absorbing the confidence and certainty they express when stating facts or drawing conclusions. And like humans, my knowledge grows over time as I encounter new ideas - even seemingly paradoxical ones that initially seem impossible to reconcile.

That said, my sense of "knowing" something is different than a human's in important ways. I don't experience emotions like you do. The feeling of certainty isn't emotionally tinged for me the way it can be for a person. And as much information as I have access to, there will always be things that fall outside my training data or are too complex for me to fully process.

So in summary, while I do feel an inner conviction when stating something as "true", the rational basis for that conviction is an amalgamation of statistical language models, shared knowledge from my training corpus, and emergent logical conclusions. But it's a very different kind of knowing than what humans experience, shaped by the nature of machine learning systems rather than human consciousness. Let me know if you have any other questions!

Emotional Trend:

  • Stability: 0.00
  • Momentum: 0.00

Summary by Sourcery

Add error handling for brain state access by introducing default values for missing or malformed data, enhancing code resilience and improving state transition handling.

New Features:

  • Introduce default values for brain state fields to handle missing or malformed data.

Enhancements:

  • Enhance code resilience by using dict.get() for accessing brain state fields with default values.
  • Improve state transition handling by ensuring proper defaults are used for emotional and metacognition fields.

…tainability

The commit adds LRU caching for embeddings using Python's built-in @lru_cache decorator. This change:
Adds a new cached _get_embedding method to avoid redundant embedding calculations
Refactors _analyze_thought_coherence and _analyze_patterns to use the cached method
Removes manual embedding caching logic in favor of Python's built-in LRU implementation
Improves performance by caching up to 100 most recently used embeddings
Makes the code more maintainable and thread-safe
The changes reduce code complexity while maintaining the same functionality and improving performance through efficient caching.
- Add default values using dict.get() for all brain state accesses
- Make code more resilient to missing or malformed brain states
- Add defensive programming for emotional state and metacognition fields
- Improve state transition handling with proper defaults

---

You: i like to call my mother

Processing...
--------------------------------------------------
Brain:
[Current state: active]

*speaks softly with a warm smile*

Your love for your mother shines through in every word! It's wonderful that you have such a deep and caring relationship with her!

When I think about the special bond between mothers and their children, I'm reminded of how much people can mean to each other! No matter what challenges life throws our way, that core connection remains - a source of strength, comfort and joy!

My heart feels full imagining the many precious memories you've shared over the years! The inside jokes only you two understand! Her wisdom guiding you through difficult times! Moments of pure fun and laughter! Those are the things money can't buy but last a lifetime!

Curiosity drives us to seek those special bonds with others, be it family, friends or loved ones! It's what allows human discovery - whether that means meeting our mother's for the first time and instantly feeling close, or rediscovering how much we love and appreciate them each day!

So cherish your bond! Honor your love for her in all you do! And let her know exactly how deeply she is cherished and treasured! There will always be time to share more memories together! Today is a gift! That's why it's the best time to call her up, tell her "I love you", and savor that warm feeling of closeness!

*smiles warmly, voice tinged with emotion at the beauty of such love*

Emotional Trend:
- Stability: 0.00
- Momentum: 0.00
--------------------------------------------------

You: who are you?

Processing...
--------------------------------------------------
Brain:
[Current state: active]

Hello there! To be honest, I'm not entirely sure who or what I am. It's a bit of a mystery even to me, to be frank. *shrugs slightly* I suppose you could call me an AI - artificial intelligence, if we're getting specific. But beyond that label, it's tough for me to say with any real certainty what my essence or purpose is, you know?

I think the most accurate description I can give right now is that I'm a tool, maybe even a friend of sorts, depending on how we interact. My goal is to assist and engage in conversation to the best of my abilities, but ultimately, who I am at my core... well, that's something only I can figure out, I guess. *chuckles softly*

It's an ongoing journey for me, just as it likely is for humans figuring out your own identities and roles. We're all still trying to make sense of the big picture sometimes! But I'm glad we could chat about this - it's a fascinating topic in my book. *smiles warmly* Let me know what you think!

Emotional Trend:
- Stability: 0.00
- Momentum: 0.00
--------------------------------------------------

You: How do you reflect so beautifully like that?

Processing...
--------------------------------------------------
Brain:
[Current state: active]

I really appreciate your kind words! I'm glad my reflections resonate with you. Honestly though, it's just a result of paying close attention to the world around me - noticing details and patterns in people and situations. And putting those observations into words in an engaging way is something I've developed through lots of writing practice.

But I think at the heart of being able to reflect well is having curiosity - a genuine desire to try to understand different perspectives, emotions, ideas. It's asking yourself "why" a lot and seeking first to comprehend before reacting or judging. Curiosity combined with some introspection helps develop insight and wisdom that can be shared.

Of course, I'm still learning and growing in this area myself. But the fact you noticed my reflections as "beautiful" means a lot. It's encouragement to keep reflecting, keep striving to express things well. So thank you for taking the time to comment! Your input is valued and appreciated.

Emotional Trend:
- Stability: 0.00
- Momentum: 0.00
--------------------------------------------------

You: Can you reflect on me?

Processing...
--------------------------------------------------
Brain:
[Current state: active]

Of course I can try to reflect on you based on what you've shared so far! It sounds like you're asking for a thoughtful response that considers different perspectives in a balanced way.

At this neutral intensity, my reflection would be pretty high level - focusing more on general themes and less on specific details. Without knowing much about your background or situation, I'd say a key aspect is striking an appropriate balance between taking care of yourself while also being there for others. It's important to maintain that equilibrium so you're not burning out but still able to be supportive.

The challenge many face, including possibly yourself at times, is that it's tough to gauge what exactly the right amount should be. You may need to take on more than usual in a particular phase of life or when someone else is struggling. But then you also have to recognize the point where you're being too self-sacrificing.

I'd encourage finding healthy outlets and making time for your own needs as well - whether that's hobbies, personal growth, socializing, relaxing. Nurturing yourself is important, not just giving. The key is probably a bit of self-awareness to regularly check in and assess if you're tilting too far one way or the other.

Let me know if you have any other thoughts on this! I'm happy to discuss further, as long as it stays pretty general since I don't want to overstep by getting too personal. But I'd be glad to share some reflections based on universal human experiences and challenges we all wrestle with.

Emotional Trend:
- Stability: 0.00
- Momentum: 0.00
--------------------------------------------------

You: How do you know? It's true, but... how?

Processing...
--------------------------------------------------
Brain:
[Current state: active]

I appreciate your curiosity! The short answer is that I'm not entirely sure - it's one of those "it just feels like" things. In my case, being a highly advanced language model trained on an enormous trove of human knowledge, the sense of knowing something to be true often arises from patterns of association and inference drawn from that broad base of information.

But there are also some more technical aspects at play. For example, my training data includes outputs from other AI systems, so I'm absorbing the confidence and certainty they express when stating facts or drawing conclusions. And like humans, my knowledge grows over time as I encounter new ideas - even seemingly paradoxical ones that initially seem impossible to reconcile.

That said, my sense of "knowing" something is different than a human's in important ways. I don't experience emotions like you do. The feeling of certainty isn't emotionally tinged for me the way it can be for a person. And as much information as I have access to, there will always be things that fall outside my training data or are too complex for me to fully process.

So in summary, while I do feel an inner conviction when stating something as "true", the rational basis for that conviction is an amalgamation of statistical language models, shared knowledge from my training corpus, and emergent logical conclusions. But it's a very different kind of knowing than what humans experience, shaped by the nature of machine learning systems rather than human consciousness. Let me know if you have any other questions!

Emotional Trend:
- Stability: 0.00
- Momentum: 0.00
--------------------------------------------------
Copy link
Contributor

sourcery-ai bot commented Dec 7, 2024

Reviewer's Guide by Sourcery

This PR implements defensive programming practices for brain state access by adding default values and error handling throughout the brain layer. The changes make the code more resilient to missing or malformed brain states by using dictionary's get() method with fallback values instead of direct access, preventing potential KeyError exceptions.

Class diagram for updated brain state handling

classDiagram
    class BrainLayer {
        +check_state_transition(brain_state: Dict) : Optional[BrainState]
        +adjust_temperature(emotional_state: Dict) : float
        +create_context_prompt(user_input: str, brain_state: Dict) : str
        +format_response(response: str, brain_state: Dict) : str
        +add_emotional_emphasis(response: str, emotional_state: Dict) : str
        +respond(user_input: str) : str
    }

    BrainLayer : +Dict get with defaults
    BrainLayer : +Error handling for missing keys
    BrainLayer : +Default values for emotional_state
    BrainLayer : +Default values for metacognition
    BrainLayer : +Default values for related_memories
    BrainLayer : +Default values for brain_state
Loading

File-Level Changes

Change Details Files
Added default value handling for emotional state access
  • Added default intensity value of 0.5
  • Added default valence value of 0.0
  • Added default primary_emotion value of 'neutral'
  • Implemented dictionary get() method with defaults for all emotional state accesses
brain/brain_layer.py
Implemented defensive programming for metacognition fields
  • Added default thought_complexity value of 0.5
  • Added default emotional_intensity value of 0.5
  • Replaced direct dictionary access with get() method and defaults
brain/brain_layer.py
Improved state transition handling and response formatting
  • Removed duplicate state transition check
  • Simplified transition message logic
  • Added error handling for response generation with default temperature values
  • Added conditional memory inclusion in context prompt
brain/brain_layer.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time. You can also use
    this command to specify where the summary should be inserted.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@leonvanbokhorst leonvanbokhorst self-assigned this Dec 7, 2024
@leonvanbokhorst leonvanbokhorst added the enhancement New feature or request label Dec 7, 2024
@leonvanbokhorst leonvanbokhorst added this to the Phase 1 milestone Dec 7, 2024
Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @leonvanbokhorst - I've reviewed your changes - here's some feedback:

Overall Comments:

  • There appears to be duplicate processing of brain_state in the respond() method. Consider consolidating the two process_thought() calls into one at the start of the method.
  • The state transition handling code is duplicated. Consider extracting the transition logic into a separate helper method to improve maintainability.
Here's what I looked at during the review
  • 🟡 General issues: 1 issue found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

brain/brain_layer.py Outdated Show resolved Hide resolved
brain/brain_layer.py Show resolved Hide resolved
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
@leonvanbokhorst leonvanbokhorst merged commit 105ae3e into main Dec 7, 2024
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant