Elffuss BraidHub

kikocis/llama-stack public

11d754a72cde · 29.1 KiBRawPermalink
1# Copyright (c) Meta Platforms, Inc. and affiliates.
2# All rights reserved.
3#
4# This source code is licensed under the terms described in the LICENSE file in
5# the root directory of this source tree.
6
7import asyncio
8import copy
9import os
10import secrets
11import shutil
12import string
13import tempfile
14import uuid
15from datetime import datetime
16from typing import AsyncGenerator, List, Tuple
17from urllib.parse import urlparse
18
19import httpx
20
21from termcolor import cprint
22
23from llama_stack.apis.agents import * # noqa: F403
24from llama_stack.apis.inference import * # noqa: F403
25from llama_stack.apis.memory import * # noqa: F403
26from llama_stack.apis.safety import * # noqa: F403
27
28from .rag.context_retriever import generate_rag_query
29from .safety import SafetyException, ShieldRunnerMixin
30from .tools.base import BaseTool
31from .tools.builtin import interpret_content_as_attachment, SingleMessageBuiltinTool
32
33
34def make_random_string(length: int = 8):
35 return "".join(
36 secrets.choice(string.ascii_letters + string.digits) for _ in range(length)
37 )
38
39
40class ChatAgent(ShieldRunnerMixin):
41 def __init__(
42 self,
43 agent_config: AgentConfig,
44 inference_api: Inference,
45 memory_api: Memory,
46 safety_api: Safety,
47 builtin_tools: List[SingleMessageBuiltinTool],
48 max_infer_iters: int = 10,
49 ):
50 self.agent_config = agent_config
51 self.inference_api = inference_api
52 self.memory_api = memory_api
53 self.safety_api = safety_api
54
55 self.max_infer_iters = max_infer_iters
56 self.tools_dict = {t.get_name(): t for t in builtin_tools}
57
58 self.tempdir = tempfile.mkdtemp()
59 self.sessions = {}
60
61 ShieldRunnerMixin.__init__(
62 self,
63 safety_api,
64 input_shields=agent_config.input_shields,
65 output_shields=agent_config.output_shields,
66 )
67
68 def __del__(self):
69 shutil.rmtree(self.tempdir)
70
71 def turn_to_messages(self, turn: Turn) -> List[Message]:
72 messages = []
73
74 # We do not want to keep adding RAG context to the input messages
75 # May be this should be a parameter of the agentic instance
76 # that can define its behavior in a custom way
77 for m in turn.input_messages:
78 msg = m.copy()
79 if isinstance(msg, UserMessage):
80 msg.context = None
81 messages.append(msg)
82
83 # messages.extend(turn.input_messages)
84 for step in turn.steps:
85 if step.step_type == StepType.inference.value:
86 messages.append(step.model_response)
87 elif step.step_type == StepType.tool_execution.value:
88 for response in step.tool_responses:
89 messages.append(
90 ToolResponseMessage(
91 call_id=response.call_id,
92 tool_name=response.tool_name,
93 content=response.content,
94 )
95 )
96 elif step.step_type == StepType.shield_call.value:
97 response = step.response
98 if response.is_violation:
99 # CompletionMessage itself in the ShieldResponse
100 messages.append(
101 CompletionMessage(
102 content=response.violation_return_message,
103 stop_reason=StopReason.end_of_turn,
104 )
105 )
106 # print_dialog(messages)
107 return messages
108
109 def create_session(self, name: str) -> Session:
110 session_id = str(uuid.uuid4())
111 session = Session(
112 session_id=session_id,
113 session_name=name,
114 turns=[],
115 started_at=datetime.now(),
116 )
117 self.sessions[session_id] = session
118 return session
119
120 async def create_and_execute_turn(
121 self, request: AgentTurnCreateRequest
122 ) -> AsyncGenerator:
123 assert (
124 request.session_id in self.sessions
125 ), f"Session {request.session_id} not found"
126
127 session = self.sessions[request.session_id]
128
129 messages = []
130 for i, turn in enumerate(session.turns):
131 messages.extend(self.turn_to_messages(turn))
132
133 messages.extend(request.messages)
134
135 # print("processed dialog ======== ")
136 # print_dialog(messages)
137
138 turn_id = str(uuid.uuid4())
139 start_time = datetime.now()
140 yield AgentTurnResponseStreamChunk(
141 event=AgentTurnResponseEvent(
142 payload=AgentTurnResponseTurnStartPayload(
143 turn_id=turn_id,
144 )
145 )
146 )
147
148 steps = []
149 output_message = None
150 async for chunk in self.run(
151 session=session,
152 turn_id=turn_id,
153 input_messages=messages,
154 attachments=request.attachments or [],
155 sampling_params=self.agent_config.sampling_params,
156 stream=request.stream,
157 ):
158 if isinstance(chunk, CompletionMessage):
159 cprint(
160 f"{chunk.role.capitalize()}: {chunk.content}",
161 "white",
162 attrs=["bold"],
163 )
164 output_message = chunk
165 continue
166
167 assert isinstance(
168 chunk, AgentTurnResponseStreamChunk
169 ), f"Unexpected type {type(chunk)}"
170 event = chunk.event
171 if (
172 event.payload.event_type
173 == AgentTurnResponseEventType.step_complete.value
174 ):
175 steps.append(event.payload.step_details)
176
177 yield chunk
178
179 assert output_message is not None
180
181 turn = Turn(
182 turn_id=turn_id,
183 session_id=request.session_id,
184 input_messages=request.messages,
185 output_message=output_message,
186 started_at=start_time,
187 completed_at=datetime.now(),
188 steps=steps,
189 )
190 session.turns.append(turn)
191
192 chunk = AgentTurnResponseStreamChunk(
193 event=AgentTurnResponseEvent(
194 payload=AgentTurnResponseTurnCompletePayload(
195 turn=turn,
196 )
197 )
198 )
199 yield chunk
200
201 async def run(
202 self,
203 session: Session,
204 turn_id: str,
205 input_messages: List[Message],
206 attachments: List[Attachment],
207 sampling_params: SamplingParams,
208 stream: bool = False,
209 ) -> AsyncGenerator:
210 # Doing async generators makes downstream code much simpler and everything amenable to
211 # streaming. However, it also makes things complicated here because AsyncGenerators cannot
212 # return a "final value" for the `yield from` statement. we simulate that by yielding a
213 # final boolean (to see whether an exception happened) and then explicitly testing for it.
214
215 async for res in self.run_shields_wrapper(
216 turn_id, input_messages, self.input_shields, "user-input"
217 ):
218 if isinstance(res, bool):
219 return
220 else:
221 yield res
222
223 async for res in self._run(
224 session, turn_id, input_messages, attachments, sampling_params, stream
225 ):
226 if isinstance(res, bool):
227 return
228 elif isinstance(res, CompletionMessage):
229 final_response = res
230 break
231 else:
232 yield res
233
234 assert final_response is not None
235 # for output shields run on the full input and output combination
236 messages = input_messages + [final_response]
237
238 async for res in self.run_shields_wrapper(
239 turn_id, messages, self.output_shields, "assistant-output"
240 ):
241 if isinstance(res, bool):
242 return
243 else:
244 yield res
245
246 yield final_response
247
248 async def run_shields_wrapper(
249 self,
250 turn_id: str,
251 messages: List[Message],
252 shields: List[ShieldDefinition],
253 touchpoint: str,
254 ) -> AsyncGenerator:
255 if len(shields) == 0:
256 return
257
258 step_id = str(uuid.uuid4())
259 try:
260 yield AgentTurnResponseStreamChunk(
261 event=AgentTurnResponseEvent(
262 payload=AgentTurnResponseStepStartPayload(
263 step_type=StepType.shield_call.value,
264 step_id=step_id,
265 metadata=dict(touchpoint=touchpoint),
266 )
267 )
268 )
269 await self.run_shields(messages, shields)
270
271 except SafetyException as e:
272 yield AgentTurnResponseStreamChunk(
273 event=AgentTurnResponseEvent(
274 payload=AgentTurnResponseStepCompletePayload(
275 step_type=StepType.shield_call.value,
276 step_details=ShieldCallStep(
277 step_id=step_id,
278 turn_id=turn_id,
279 response=e.response,
280 ),
281 )
282 )
283 )
284
285 yield CompletionMessage(
286 content=str(e),
287 stop_reason=StopReason.end_of_turn,
288 )
289 yield False
290
291 yield AgentTurnResponseStreamChunk(
292 event=AgentTurnResponseEvent(
293 payload=AgentTurnResponseStepCompletePayload(
294 step_type=StepType.shield_call.value,
295 step_details=ShieldCallStep(
296 step_id=step_id,
297 turn_id=turn_id,
298 response=ShieldResponse(
299 # TODO: fix this, give each shield a shield type method and
300 # fire one event for each shield run
301 shield_type=BuiltinShield.llama_guard,
302 is_violation=False,
303 ),
304 ),
305 )
306 )
307 )
308
309 async def _run(
310 self,
311 session: Session,
312 turn_id: str,
313 input_messages: List[Message],
314 attachments: List[Attachment],
315 sampling_params: SamplingParams,
316 stream: bool = False,
317 ) -> AsyncGenerator:
318 enabled_tools = set(t.type for t in self.agent_config.tools)
319 need_rag_context = await self._should_retrieve_context(
320 input_messages, attachments
321 )
322 if need_rag_context:
323 step_id = str(uuid.uuid4())
324 yield AgentTurnResponseStreamChunk(
325 event=AgentTurnResponseEvent(
326 payload=AgentTurnResponseStepStartPayload(
327 step_type=StepType.memory_retrieval.value,
328 step_id=step_id,
329 )
330 )
331 )
332
333 # TODO: find older context from the session and either replace it
334 # or append with a sliding window. this is really a very simplistic implementation
335 rag_context, bank_ids = await self._retrieve_context(
336 session, input_messages, attachments
337 )
338
339 step_id = str(uuid.uuid4())
340 yield AgentTurnResponseStreamChunk(
341 event=AgentTurnResponseEvent(
342 payload=AgentTurnResponseStepCompletePayload(
343 step_type=StepType.memory_retrieval.value,
344 step_id=step_id,
345 step_details=MemoryRetrievalStep(
346 turn_id=turn_id,
347 step_id=step_id,
348 memory_bank_ids=bank_ids,
349 inserted_context=rag_context or "",
350 ),
351 )
352 )
353 )
354
355 if rag_context:
356 last_message = input_messages[-1]
357 last_message.context = "\n".join(rag_context)
358
359 elif attachments and AgentTool.code_interpreter.value in enabled_tools:
360 urls = [a.content for a in attachments if isinstance(a.content, URL)]
361 msg = await attachment_message(self.tempdir, urls)
362 input_messages.append(msg)
363
364 output_attachments = []
365
366 n_iter = 0
367 while True:
368 msg = input_messages[-1]
369 if msg.role == Role.user.value:
370 color = "blue"
371 elif msg.role == Role.ipython.value:
372 color = "yellow"
373 else:
374 color = None
375 cprint(f"{str(msg)}", color=color)
376
377 step_id = str(uuid.uuid4())
378 yield AgentTurnResponseStreamChunk(
379 event=AgentTurnResponseEvent(
380 payload=AgentTurnResponseStepStartPayload(
381 step_type=StepType.inference.value,
382 step_id=step_id,
383 )
384 )
385 )
386
387 tool_calls = []
388 content = ""
389 stop_reason = None
390 async for chunk in self.inference_api.chat_completion(
391 self.agent_config.model,
392 input_messages,
393 tools=self._get_tools(),
394 tool_prompt_format=self.agent_config.tool_prompt_format,
395 stream=True,
396 sampling_params=sampling_params,
397 ):
398 event = chunk.event
399 if event.event_type == ChatCompletionResponseEventType.start:
400 continue
401 elif event.event_type == ChatCompletionResponseEventType.complete:
402 stop_reason = StopReason.end_of_turn
403 continue
404
405 delta = event.delta
406 if isinstance(delta, ToolCallDelta):
407 if delta.parse_status == ToolCallParseStatus.success:
408 tool_calls.append(delta.content)
409
410 if stream:
411 yield AgentTurnResponseStreamChunk(
412 event=AgentTurnResponseEvent(
413 payload=AgentTurnResponseStepProgressPayload(
414 step_type=StepType.inference.value,
415 step_id=step_id,
416 model_response_text_delta="",
417 tool_call_delta=delta,
418 )
419 )
420 )
421
422 elif isinstance(delta, str):
423 content += delta
424 if stream and event.stop_reason is None:
425 yield AgentTurnResponseStreamChunk(
426 event=AgentTurnResponseEvent(
427 payload=AgentTurnResponseStepProgressPayload(
428 step_type=StepType.inference.value,
429 step_id=step_id,
430 model_response_text_delta=event.delta,
431 )
432 )
433 )
434 else:
435 raise ValueError(f"Unexpected delta type {type(delta)}")
436
437 if event.stop_reason is not None:
438 stop_reason = event.stop_reason
439
440 stop_reason = stop_reason or StopReason.out_of_tokens
441 message = CompletionMessage(
442 content=content,
443 stop_reason=stop_reason,
444 tool_calls=tool_calls,
445 )
446
447 yield AgentTurnResponseStreamChunk(
448 event=AgentTurnResponseEvent(
449 payload=AgentTurnResponseStepCompletePayload(
450 step_type=StepType.inference.value,
451 step_id=step_id,
452 step_details=InferenceStep(
453 # somewhere deep, we are re-assigning message or closing over some
454 # variable which causes message to mutate later on. fix with a
455 # `deepcopy` for now, but this is symptomatic of a deeper issue.
456 step_id=step_id,
457 turn_id=turn_id,
458 model_response=copy.deepcopy(message),
459 ),
460 )
461 )
462 )
463
464 if n_iter >= self.max_infer_iters:
465 cprint("Done with MAX iterations, exiting.")
466 yield message
467 break
468
469 if stop_reason == StopReason.out_of_tokens:
470 cprint("Out of token budget, exiting.")
471 yield message
472 break
473
474 if len(message.tool_calls) == 0:
475 if stop_reason == StopReason.end_of_turn:
476 # TODO: UPDATE RETURN TYPE TO SEND A TUPLE OF (MESSAGE, ATTACHMENTS)
477 if len(output_attachments) > 0:
478 if isinstance(message.content, list):
479 message.content += attachments
480 else:
481 message.content = [message.content] + attachments
482 yield message
483 else:
484 cprint(f"Partial message: {str(message)}", color="green")
485 input_messages = input_messages + [message]
486 else:
487 cprint(f"{str(message)}", color="green")
488 try:
489 tool_call = message.tool_calls[0]
490
491 name = tool_call.tool_name
492 if not isinstance(name, BuiltinTool):
493 yield message
494 return
495
496 step_id = str(uuid.uuid4())
497 yield AgentTurnResponseStreamChunk(
498 event=AgentTurnResponseEvent(
499 payload=AgentTurnResponseStepStartPayload(
500 step_type=StepType.tool_execution.value,
501 step_id=step_id,
502 )
503 )
504 )
505 yield AgentTurnResponseStreamChunk(
506 event=AgentTurnResponseEvent(
507 payload=AgentTurnResponseStepProgressPayload(
508 step_type=StepType.tool_execution.value,
509 step_id=step_id,
510 tool_call=tool_call,
511 )
512 )
513 )
514
515 result_messages = await execute_tool_call_maybe(
516 self.tools_dict,
517 [message],
518 )
519 assert (
520 len(result_messages) == 1
521 ), "Currently not supporting multiple messages"
522 result_message = result_messages[0]
523
524 yield AgentTurnResponseStreamChunk(
525 event=AgentTurnResponseEvent(
526 payload=AgentTurnResponseStepCompletePayload(
527 step_type=StepType.tool_execution.value,
528 step_details=ToolExecutionStep(
529 step_id=step_id,
530 turn_id=turn_id,
531 tool_calls=[tool_call],
532 tool_responses=[
533 ToolResponse(
534 call_id=result_message.call_id,
535 tool_name=result_message.tool_name,
536 content=result_message.content,
537 )
538 ],
539 ),
540 )
541 )
542 )
543
544 # TODO: add tool-input touchpoint and a "start" event for this step also
545 # but that needs a lot more refactoring of Tool code potentially
546 yield AgentTurnResponseStreamChunk(
547 event=AgentTurnResponseEvent(
548 payload=AgentTurnResponseStepCompletePayload(
549 step_type=StepType.shield_call.value,
550 step_details=ShieldCallStep(
551 step_id=str(uuid.uuid4()),
552 turn_id=turn_id,
553 response=ShieldResponse(
554 # TODO: fix this, give each shield a shield type method and
555 # fire one event for each shield run
556 shield_type=BuiltinShield.llama_guard,
557 is_violation=False,
558 ),
559 ),
560 )
561 )
562 )
563
564 except SafetyException as e:
565 yield AgentTurnResponseStreamChunk(
566 event=AgentTurnResponseEvent(
567 payload=AgentTurnResponseStepCompletePayload(
568 step_type=StepType.shield_call.value,
569 step_details=ShieldCallStep(
570 step_id=str(uuid.uuid4()),
571 turn_id=turn_id,
572 response=e.response,
573 ),
574 )
575 )
576 )
577
578 yield CompletionMessage(
579 content=str(e),
580 stop_reason=StopReason.end_of_turn,
581 )
582 yield False
583 return
584
585 if out_attachment := interpret_content_as_attachment(
586 result_message.content
587 ):
588 # NOTE: when we push this message back to the model, the model may ignore the
589 # attached file path etc. since the model is trained to only provide a user message
590 # with the summary. We keep all generated attachments and then attach them to final message
591 output_attachments.append(out_attachment)
592
593 input_messages = input_messages + [message, result_message]
594
595 n_iter += 1
596
597 async def _ensure_memory_bank(self, session: Session) -> MemoryBank:
598 if session.memory_bank is None:
599 session.memory_bank = await self.memory_api.create_memory_bank(
600 name=f"memory_bank_{session.session_id}",
601 config=VectorMemoryBankConfig(
602 embedding_model="sentence-transformer/all-MiniLM-L6-v2",
603 chunk_size_in_tokens=512,
604 ),
605 )
606
607 return session.memory_bank
608
609 async def _should_retrieve_context(
610 self, messages: List[Message], attachments: List[Attachment]
611 ) -> bool:
612 enabled_tools = set(t.type for t in self.agent_config.tools)
613 if attachments:
614 if (
615 AgentTool.code_interpreter.value in enabled_tools
616 and self.agent_config.tool_choice == ToolChoice.required
617 ):
618 return False
619 else:
620 return True
621
622 return AgentTool.memory.value in enabled_tools
623
624 def _memory_tool_definition(self) -> Optional[MemoryToolDefinition]:
625 for t in self.agent_config.tools:
626 if t.type == AgentTool.memory.value:
627 return t
628
629 return None
630
631 async def _retrieve_context(
632 self, session: Session, messages: List[Message], attachments: List[Attachment]
633 ) -> Tuple[List[str], List[int]]: # (rag_context, bank_ids)
634 bank_ids = []
635
636 memory = self._memory_tool_definition()
637 assert memory is not None, "Memory tool not configured"
638 bank_ids.extend(c.bank_id for c in memory.memory_bank_configs)
639
640 if attachments:
641 bank = await self._ensure_memory_bank(session)
642 bank_ids.append(bank.bank_id)
643
644 documents = [
645 MemoryBankDocument(
646 document_id=str(uuid.uuid4()),
647 content=a.content,
648 mime_type=a.mime_type,
649 metadata={},
650 )
651 for a in attachments
652 ]
653 await self.memory_api.insert_documents(bank.bank_id, documents)
654 elif session.memory_bank:
655 bank_ids.append(session.memory_bank.bank_id)
656
657 if not bank_ids:
658 # this can happen if the per-session memory bank is not yet populated
659 # (i.e., no prior turns uploaded an Attachment)
660 return None, []
661
662 query = await generate_rag_query(
663 memory.query_generator_config, messages, inference_api=self.inference_api
664 )
665 tasks = [
666 self.memory_api.query_documents(
667 bank_id=bank_id,
668 query=query,
669 params={
670 "max_chunks": 5,
671 },
672 )
673 for bank_id in bank_ids
674 ]
675 results: List[QueryDocumentsResponse] = await asyncio.gather(*tasks)
676 chunks = [c for r in results for c in r.chunks]
677 scores = [s for r in results for s in r.scores]
678
679 # sort by score
680 chunks, scores = zip(
681 *sorted(zip(chunks, scores), key=lambda x: x[1], reverse=True)
682 )
683 if not chunks:
684 return None, bank_ids
685
686 tokens = 0
687 picked = []
688 for c in chunks[: memory.max_chunks]:
689 tokens += c.token_count
690 if tokens > memory.max_tokens_in_context:
691 cprint(
692 f"Using {len(picked)} chunks; reached max tokens in context: {tokens}",
693 "red",
694 )
695 break
696 picked.append(f"id:{c.document_id}; content:{c.content}")
697
698 return [
699 "Here are the retrieved documents for relevant context:\n=== START-RETRIEVED-CONTEXT ===\n",
700 *picked,
701 "\n=== END-RETRIEVED-CONTEXT ===\n",
702 ], bank_ids
703
704 def _get_tools(self) -> List[ToolDefinition]:
705 ret = []
706 for t in self.agent_config.tools:
707 if isinstance(t, SearchToolDefinition):
708 ret.append(ToolDefinition(tool_name=BuiltinTool.brave_search))
709 elif isinstance(t, WolframAlphaToolDefinition):
710 ret.append(ToolDefinition(tool_name=BuiltinTool.wolfram_alpha))
711 elif isinstance(t, PhotogenToolDefinition):
712 ret.append(ToolDefinition(tool_name=BuiltinTool.photogen))
713 elif isinstance(t, CodeInterpreterToolDefinition):
714 ret.append(ToolDefinition(tool_name=BuiltinTool.code_interpreter))
715 elif isinstance(t, FunctionCallToolDefinition):
716 ret.append(
717 ToolDefinition(
718 tool_name=t.function_name,
719 description=t.description,
720 parameters=t.parameters,
721 )
722 )
723 return ret
724
725
726async def attachment_message(tempdir: str, urls: List[URL]) -> ToolResponseMessage:
727 content = []
728
729 for url in urls:
730 uri = url.uri
731 if uri.startswith("file://"):
732 filepath = uri[len("file://") :]
733 elif uri.startswith("http"):
734 path = urlparse(uri).path
735 basename = os.path.basename(path)
736 filepath = f"{tempdir}/{make_random_string() + basename}"
737 print(f"Downloading {url} -> {filepath}")
738
739 async with httpx.AsyncClient() as client:
740 r = await client.get(uri)
741 resp = r.text
742 with open(filepath, "w") as fp:
743 fp.write(resp)
744 else:
745 raise ValueError(f"Unsupported URL {url}")
746
747 content.append(f'# There is a file accessible to you at "{filepath}"\n')
748
749 return ToolResponseMessage(
750 call_id="",
751 tool_name=BuiltinTool.code_interpreter,
752 content=content,
753 )
754
755
756async def execute_tool_call_maybe(
757 tools_dict: Dict[str, BaseTool], messages: List[CompletionMessage]
758) -> List[ToolResponseMessage]:
759 # While Tools.run interface takes a list of messages,
760 # All tools currently only run on a single message
761 # When this changes, we can drop this assert
762 # Whether to call tools on each message and aggregate
763 # or aggregate and call tool once, reamins to be seen.
764 assert len(messages) == 1, "Expected single message"
765 message = messages[0]
766
767 tool_call = message.tool_calls[0]
768 name = tool_call.tool_name
769 assert isinstance(name, BuiltinTool)
770
771 name = name.value
772
773 assert name in tools_dict, f"Tool {name} not found"
774 tool = tools_dict[name]
775 result_messages = await tool.run(messages)
776 return result_messages
777
778
779def print_dialog(messages: List[Message]):
780 for i, m in enumerate(messages):
781 if m.role == Role.user.value:
782 color = "red"
783 elif m.role == Role.assistant.value:
784 color = "white"
785 elif m.role == Role.ipython.value:
786 color = "yellow"
787 elif m.role == Role.system.value:
788 color = "green"
789 else:
790 color = "white"
791
792 s = str(m)
793 cprint(f"{i} ::: {s[:100]}...", color=color)