The core while(True) tool-calling loop.
(self)
| 900 | self._orchestrator_tools = saved_orch |
| 901 | |
| 902 | def _inner_loop(self) -> str: |
| 903 | """The core while(True) tool-calling loop.""" |
| 904 | context_limit = get_model_context_limit(self.config.model) |
| 905 | wrapping_up = False |
| 906 | empty_response_count = 0 |
| 907 | |
| 908 | while self.session.turn_count < self.config.max_turns: |
| 909 | self.session.turn_count += 1 |
| 910 | |
| 911 | # ── Proactive context monitoring ────────────────────────────── |
| 912 | if not wrapping_up: |
| 913 | current_tokens = count_message_tokens( |
| 914 | self.session.messages, self.config.model |
| 915 | ) |
| 916 | if current_tokens > 0: |
| 917 | utilization = current_tokens / context_limit |
| 918 | self.logger.event( |
| 919 | "agent_iteration", |
| 920 | { |
| 921 | "number": self.session.turn_count, |
| 922 | "max": self.config.max_turns, |
| 923 | "tokens": current_tokens, |
| 924 | "limit": context_limit, |
| 925 | "utilization": round(utilization * 100, 1), |
| 926 | }, |
| 927 | ) |
| 928 | if utilization >= _CONTEXT_WRAP_UP_THRESHOLD: |
| 929 | self.session.add_user_message( |
| 930 | "You are approaching the context limit. " |
| 931 | "Please wrap up your current work and provide a final " |
| 932 | "response now. Do not start any new tool calls." |
| 933 | ) |
| 934 | self.logger.event( |
| 935 | "warning", |
| 936 | { |
| 937 | "message": ( |
| 938 | f"Context at {utilization:.0%} " |
| 939 | f"({current_tokens:,}/{context_limit:,} tokens). " |
| 940 | "Wrap-up message injected." |
| 941 | ), |
| 942 | }, |
| 943 | ) |
| 944 | wrapping_up = True |
| 945 | |
| 946 | # ── Call LLM ───────────────────────────────────────────────── |
| 947 | try: |
| 948 | response = self.llm_client.completion( |
| 949 | model=self.config.model, |
| 950 | messages=self.session.messages, |
| 951 | tools=self._all_tools if self._all_tools else None, |
| 952 | temperature=self.config.temperature, |
| 953 | **self.config.model_kwargs, |
| 954 | ) |
| 955 | except litellm.NotFoundError as e: |
| 956 | self.logger.event( |
| 957 | "error", |
| 958 | { |
| 959 | "message": f"Model not found: '{self.config.model}'. Check the model name and try again.\n{e}", |
no test coverage detected