@@ -58,36 +58,48 @@ def echo_message(value: str, topic: str, offset: int) -> str:
5858)
5959
6060
61- with AgentRuntime () as runtime :
62- handle = runtime .start (agent , "Start consuming messages from Kafka." )
63- print (f"Agent started: { handle .execution_id } " )
64-
65- consumer = Consumer (
66- {
67- "bootstrap.servers" : KAFKA_BOOTSTRAP ,
68- "group.id" : KAFKA_GROUP ,
69- "auto.offset.reset" : "latest" ,
70- }
71- )
72- consumer .subscribe ([KAFKA_TOPIC ])
73- try :
74- while True :
75- msg = consumer .poll (timeout = 1.0 )
76- if msg is None :
77- continue
78- if msg .error ():
79- if msg .error ().code () == KafkaError ._PARTITION_EOF :
61+ def main () -> None :
62+ with AgentRuntime () as runtime :
63+ handle = runtime .start (agent , "Start consuming messages from Kafka." )
64+ print (f"Agent started: { handle .execution_id } " )
65+
66+ consumer = Consumer (
67+ {
68+ "bootstrap.servers" : KAFKA_BOOTSTRAP ,
69+ "group.id" : KAFKA_GROUP ,
70+ "auto.offset.reset" : "latest" ,
71+ }
72+ )
73+ consumer .subscribe ([KAFKA_TOPIC ])
74+ print (f"Consuming '{ KAFKA_TOPIC } ' from { KAFKA_BOOTSTRAP } — Ctrl+C to stop." )
75+ try :
76+ while True :
77+ msg = consumer .poll (timeout = 1.0 )
78+ if msg is None :
8079 continue
81- raise RuntimeError (f"Kafka error: { msg .error ()} " )
82- runtime .send_message (
83- handle .execution_id ,
84- {
85- "topic" : msg .topic (),
86- "partition" : msg .partition (),
87- "offset" : msg .offset (),
88- "key" : msg .key ().decode ("utf-8" ) if msg .key () else None ,
89- "value" : msg .value ().decode ("utf-8" ) if msg .value () else "" ,
90- },
91- )
92- finally :
93- consumer .close ()
80+ if msg .error ():
81+ if msg .error ().code () == KafkaError ._PARTITION_EOF :
82+ continue
83+ raise RuntimeError (f"Kafka error: { msg .error ()} " )
84+ runtime .send_message (
85+ handle .execution_id ,
86+ {
87+ "topic" : msg .topic (),
88+ "partition" : msg .partition (),
89+ "offset" : msg .offset (),
90+ "key" : msg .key ().decode ("utf-8" ) if msg .key () else None ,
91+ "value" : msg .value ().decode ("utf-8" ) if msg .value () else "" ,
92+ },
93+ )
94+ except KeyboardInterrupt :
95+ print ("\n Stopping agent..." )
96+ handle .stop ()
97+ finally :
98+ consumer .close ()
99+
100+
101+ # Guard the runtime block: spawned tool workers re-import this module, and
102+ # without the guard they would re-run the orchestration (multiprocessing's
103+ # "Safe importing of main module" error).
104+ if __name__ == "__main__" :
105+ main ()
0 commit comments