@@ -508,6 +508,11 @@ func (m *Mysis) SendMessageFrom(content string, source store.MemorySource, sende
508508 a.setActivity(ActivityStateIdle, time.Time{})
509509
510510 if err != nil {
511+ log.Error().
512+ Str("mysis", a.name).
513+ Str("provider", p.Name()).
514+ Err(err).
515+ Msg("Provider returned error")
511516 a.bus.Publish(Event{Type: EventNetworkIdle, MysisID: a.id, Timestamp: time.Now()})
512517 a.setError(err)
513518 return fmt.Errorf("provider chat: %w", err)
@@ -851,6 +856,12 @@ func (m *Mysis) setError(err error) {
851856 return
852857 }
853858
859+ log.Error().
860+ Str("mysis", a.name).
861+ Str("old_state", string(oldState)).
862+ Err(err).
863+ Msg("Mysis transitioning to errored state")
864+
854865 a.lastError = err
855866 a.state = MysisStateErrored
856867 a.mu.Unlock()
@@ -890,6 +901,10 @@ func (m *Mysis) getContextMemories() ([]*store.Memory, error) {
890901 // Apply compaction to remove redundant snapshot tool results
891902 compacted := a.compactSnapshots(recent)
892903
904+ // Remove orphaned tool messages (results without corresponding tool calls)
905+ // This ensures OpenAI Chat Completions API compliance
906+ compacted = a.removeOrphanedToolMessages(compacted)
907+
893908 // Always try to fetch the system prompt and prepend it if not already first
894909 system, err := a.store.GetSystemMemory(a.id)
895910 if err != nil {
@@ -1567,3 +1582,65 @@ func (m *Mysis) publishCriticalEvent(event Event) {
15671582 Str("mysis_name", a.name).
15681583 Msg("event bus publish timeout")
15691584 }
1585+
1586+// collectValidToolCallIDs extracts all tool call IDs from assistant messages.
1587+// Used to validate that tool result messages reference existing tool calls.
1588+func (m *Mysis) collectValidToolCallIDs(memories []*store.Memory) map[string]bool {
1589+ validToolCalls := make(map[string]bool)
1590+
1591+ for _, mem := range memories {
1592+ if mem.Role == store.MemoryRoleAssistant &&
1593+ strings.HasPrefix(mem.Content, constants.ToolCallStoragePrefix) {
1594+ calls := m.parseStoredToolCalls(mem.Content)
1595+ for _, call := range calls {
1596+ validToolCalls[call.ID] = true
1597+ }
1598+ }
1599+ }
1600+
1601+ return validToolCalls
1602+}
1603+
1604+// removeOrphanedToolMessages removes tool result messages that don't have
1605+// a corresponding assistant tool call message. This can happen due to:
1606+// 1. Context window cutting off tool calls but keeping results
1607+// 2. Context compaction removing tool call messages
1608+//
1609+// OpenAI Chat Completions API requires tool results to reference valid tool calls.
1610+func (m *Mysis) removeOrphanedToolMessages(memories []*store.Memory) []*store.Memory {
1611+ validToolCalls := m.collectValidToolCallIDs(memories)
1612+
1613+ result := make([]*store.Memory, 0, len(memories))
1614+ for _, mem := range memories {
1615+ // Check if this is a tool result message
1616+ if mem.Role == store.MemoryRoleTool {
1617+ idx := strings.Index(mem.Content, constants.ToolCallStorageFieldDelimiter)
1618+ if idx > 0 {
1619+ toolCallID := mem.Content[:idx]
1620+ if !validToolCalls[toolCallID] {
1621+ log.Debug().
1622+ Str("tool_call_id", toolCallID).
1623+ Msg("Removing orphaned tool result - no matching tool call")
1624+ continue // Skip orphaned result
1625+ }
1626+ } else {
1627+ // Malformed tool result - skip it
1628+ log.Warn().
1629+ Str("content", mem.Content).
1630+ Msg("Skipping malformed tool result")
1631+ continue
1632+ }
1633+ }
1634+ result = append(result, mem)
1635+ }
1636+
1637+ if len(result) < len(memories) {
1638+ log.Debug().
1639+ Int("removed", len(memories)-len(result)).
1640+ Int("original", len(memories)).
1641+ Int("final", len(result)).
1642+ Msg("Removed orphaned tool messages for OpenAI compliance")
1643+ }
1644+
1645+ return result
1646+}