akseljoonas HF Staff commited on
Commit
e7068c0
·
1 Parent(s): 00d49da

adding observability

Browse files
agent/core/agent_loop.py CHANGED
@@ -6,6 +6,7 @@ import asyncio
6
  import json
7
 
8
  from litellm import ChatCompletionMessageToolCall, Message, ModelResponse, acompletion
 
9
 
10
  from agent.config import Config
11
  from agent.core.session import Event, OpType, Session
@@ -18,8 +19,20 @@ class Handlers:
18
  """Handler functions for each operation type"""
19
 
20
  @staticmethod
21
- async def run_agent(session: Session, text: str, max_iterations: int = 10) -> None:
22
- """Handle user input (like user_input_or_turn in codex.rs:1291)"""
 
 
 
 
 
 
 
 
 
 
 
 
23
  # Add user message to history
24
  user_msg = Message(role="user", content=text)
25
  session.context_manager.add_message(user_msg)
@@ -31,6 +44,8 @@ class Handlers:
31
 
32
  # Agentic loop - continue until model doesn't call tools or max iterations is reached
33
  iteration = 0
 
 
34
  while iteration < max_iterations:
35
  messages = session.context_manager.get_messages()
36
  tools = session.tool_router.get_tool_specs_for_llm()
@@ -60,6 +75,7 @@ class Handlers:
60
  data={"content": content},
61
  )
62
  )
 
63
  break
64
 
65
  # Add assistant message with tool calls to history
@@ -118,7 +134,7 @@ class Handlers:
118
  await session.send_event(
119
  Event(
120
  event_type="error",
121
- data={"error": str(e + "\n" + traceback.format_exc())},
122
  )
123
  )
124
  break
@@ -129,6 +145,7 @@ class Handlers:
129
  data={"history_size": len(session.context_manager.items)},
130
  )
131
  )
 
132
 
133
  @staticmethod
134
  async def interrupt(session: Session) -> None:
@@ -202,6 +219,7 @@ async def process_submission(session: Session, submission) -> bool:
202
  return True
203
 
204
 
 
205
  async def submission_loop(
206
  submission_queue: asyncio.Queue,
207
  event_queue: asyncio.Queue,
 
6
  import json
7
 
8
  from litellm import ChatCompletionMessageToolCall, Message, ModelResponse, acompletion
9
+ from lmnr import observe
10
 
11
  from agent.config import Config
12
  from agent.core.session import Event, OpType, Session
 
19
  """Handler functions for each operation type"""
20
 
21
  @staticmethod
22
+ @observe(name="run_agent")
23
+ async def run_agent(
24
+ session: Session, text: str, max_iterations: int = 10
25
+ ) -> str | None:
26
+ """
27
+ Handle user input (like user_input_or_turn in codex.rs:1291)
28
+ Returns the final assistant response content, if any.
29
+ """
30
+ # Set session ID for this trace
31
+ if hasattr(session, "session_id"):
32
+ from lmnr import Laminar
33
+
34
+ Laminar.set_trace_session_id(session_id=session.session_id)
35
+
36
  # Add user message to history
37
  user_msg = Message(role="user", content=text)
38
  session.context_manager.add_message(user_msg)
 
44
 
45
  # Agentic loop - continue until model doesn't call tools or max iterations is reached
46
  iteration = 0
47
+ final_response = None
48
+
49
  while iteration < max_iterations:
50
  messages = session.context_manager.get_messages()
51
  tools = session.tool_router.get_tool_specs_for_llm()
 
75
  data={"content": content},
76
  )
77
  )
78
+ final_response = content
79
  break
80
 
81
  # Add assistant message with tool calls to history
 
134
  await session.send_event(
135
  Event(
136
  event_type="error",
137
+ data={"error": str(e) + "\n" + traceback.format_exc()},
138
  )
139
  )
140
  break
 
145
  data={"history_size": len(session.context_manager.items)},
146
  )
147
  )
148
+ return final_response
149
 
150
  @staticmethod
151
  async def interrupt(session: Session) -> None:
 
219
  return True
220
 
221
 
222
+ @observe(name="submission_loop")
223
  async def submission_loop(
224
  submission_queue: asyncio.Queue,
225
  event_queue: asyncio.Queue,
agent/core/session.py CHANGED
@@ -1,8 +1,13 @@
1
  import asyncio
 
 
2
  from dataclasses import dataclass
3
  from enum import Enum
4
  from typing import Any, Optional
5
 
 
 
 
6
  from agent.config import Config
7
  from agent.context_manager.manager import ContextManager
8
 
@@ -33,8 +38,19 @@ class Session:
33
  event_queue: asyncio.Queue,
34
  config: Config | None = None,
35
  ):
 
 
 
 
 
 
 
 
 
 
36
  self.context_manager = ContextManager()
37
  self.event_queue = event_queue
 
38
  self.config = config or Config(
39
  model_name="anthropic/claude-sonnet-4-5-20250929",
40
  tools=[],
 
1
  import asyncio
2
+ import os
3
+ import uuid
4
  from dataclasses import dataclass
5
  from enum import Enum
6
  from typing import Any, Optional
7
 
8
+ import litellm
9
+ from lmnr import Laminar, LaminarLiteLLMCallback
10
+
11
  from agent.config import Config
12
  from agent.context_manager.manager import ContextManager
13
 
 
38
  event_queue: asyncio.Queue,
39
  config: Config | None = None,
40
  ):
41
+ # Initialize Laminar if API key is present
42
+ lmnr_api_key = os.environ.get("LMNR_API_KEY")
43
+ if lmnr_api_key:
44
+ try:
45
+ Laminar.initialize(project_api_key=lmnr_api_key)
46
+ litellm.callbacks = [LaminarLiteLLMCallback()]
47
+ print("✅ Laminar initialized")
48
+ except Exception as e:
49
+ print(f"⚠️ Failed to initialize Laminar: {e}")
50
+
51
  self.context_manager = ContextManager()
52
  self.event_queue = event_queue
53
+ self.session_id = str(uuid.uuid4())
54
  self.config = config or Config(
55
  model_name="anthropic/claude-sonnet-4-5-20250929",
56
  tools=[],
agent/core/tools.py CHANGED
@@ -9,6 +9,7 @@ from dataclasses import dataclass
9
  from typing import Any, Awaitable, Callable, Optional
10
 
11
  from fastmcp import Client
 
12
  from mcp.types import EmbeddedResource, ImageContent, TextContent
13
 
14
  from agent.config import MCPServerConfig
@@ -142,6 +143,7 @@ class ToolRouter:
142
  await self.mcp_client.__aexit__(exc_type, exc, tb)
143
  self._mcp_initialized = False
144
 
 
145
  async def call_tool(
146
  self, tool_name: str, arguments: dict[str, Any]
147
  ) -> tuple[str, bool]:
 
9
  from typing import Any, Awaitable, Callable, Optional
10
 
11
  from fastmcp import Client
12
+ from lmnr import observe
13
  from mcp.types import EmbeddedResource, ImageContent, TextContent
14
 
15
  from agent.config import MCPServerConfig
 
143
  await self.mcp_client.__aexit__(exc_type, exc, tb)
144
  self._mcp_initialized = False
145
 
146
+ @observe(name="call_tool")
147
  async def call_tool(
148
  self, tool_name: str, arguments: dict[str, Any]
149
  ) -> tuple[str, bool]:
agent/main.py CHANGED
@@ -160,6 +160,7 @@ async def main():
160
  op_type=OpType.USER_INPUT, data={"text": user_input}
161
  ),
162
  )
 
163
  await submission_queue.put(submission)
164
 
165
  except KeyboardInterrupt:
 
160
  op_type=OpType.USER_INPUT, data={"text": user_input}
161
  ),
162
  )
163
+ print(f"Main submitting: {submission.operation.op_type}")
164
  await submission_queue.put(submission)
165
 
166
  except KeyboardInterrupt:
pyproject.toml CHANGED
@@ -16,4 +16,7 @@ dependencies = [
16
  "huggingface-hub>=1.0.1",
17
  "fastmcp>=2.4.0",
18
  "inspect-ai>=0.3.149",
 
 
 
19
  ]
 
16
  "huggingface-hub>=1.0.1",
17
  "fastmcp>=2.4.0",
18
  "inspect-ai>=0.3.149",
19
+ "lmnr[all]>=0.7.23",
20
+ "transformers>=2.3.0",
21
+ "torch>=2.9.1",
22
  ]
uv.lock CHANGED
The diff for this file is too large to render. See raw diff