Elffuss BraidHub

kikocis/llama-stack public

24a815d896f1 · 3.8 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 json
8import logging
9import uuid
10from typing import AsyncGenerator
11
12from llama_stack.apis.inference import Inference
13from llama_stack.apis.memory import Memory
14from llama_stack.apis.safety import Safety
15from llama_stack.apis.agents import * # noqa: F403
16
17from llama_stack.providers.utils.kvstore import InmemoryKVStoreImpl, kvstore_impl
18
19from .agent_instance import ChatAgent
20from .config import MetaReferenceAgentsImplConfig
21
22logger = logging.getLogger()
23logger.setLevel(logging.INFO)
24
25
26class MetaReferenceAgentsImpl(Agents):
27 def __init__(
28 self,
29 config: MetaReferenceAgentsImplConfig,
30 inference_api: Inference,
31 memory_api: Memory,
32 safety_api: Safety,
33 ):
34 self.config = config
35 self.inference_api = inference_api
36 self.memory_api = memory_api
37 self.safety_api = safety_api
38 self.in_memory_store = InmemoryKVStoreImpl()
39
40 async def initialize(self) -> None:
41 self.persistence_store = await kvstore_impl(self.config.persistence_store)
42
43 async def create_agent(
44 self,
45 agent_config: AgentConfig,
46 ) -> AgentCreateResponse:
47 agent_id = str(uuid.uuid4())
48
49 await self.persistence_store.set(
50 key=f"agent:{agent_id}",
51 value=agent_config.json(),
52 )
53 return AgentCreateResponse(
54 agent_id=agent_id,
55 )
56
57 async def get_agent(self, agent_id: str) -> ChatAgent:
58 agent_config = await self.persistence_store.get(
59 key=f"agent:{agent_id}",
60 )
61 if not agent_config:
62 raise ValueError(f"Could not find agent config for {agent_id}")
63
64 try:
65 agent_config = json.loads(agent_config)
66 except json.JSONDecodeError as e:
67 raise ValueError(
68 f"Could not JSON decode agent config for {agent_id}"
69 ) from e
70
71 try:
72 agent_config = AgentConfig(**agent_config)
73 except Exception as e:
74 raise ValueError(
75 f"Could not validate(?) agent config for {agent_id}"
76 ) from e
77
78 return ChatAgent(
79 agent_id=agent_id,
80 agent_config=agent_config,
81 inference_api=self.inference_api,
82 safety_api=self.safety_api,
83 memory_api=self.memory_api,
84 persistence_store=(
85 self.persistence_store
86 if agent_config.enable_session_persistence
87 else self.in_memory_store
88 ),
89 )
90
91 async def create_agent_session(
92 self,
93 agent_id: str,
94 session_name: str,
95 ) -> AgentSessionCreateResponse:
96 agent = await self.get_agent(agent_id)
97
98 session_id = await agent.create_session(session_name)
99 return AgentSessionCreateResponse(
100 session_id=session_id,
101 )
102
103 async def create_agent_turn(
104 self,
105 agent_id: str,
106 session_id: str,
107 messages: List[
108 Union[
109 UserMessage,
110 ToolResponseMessage,
111 ]
112 ],
113 attachments: Optional[List[Attachment]] = None,
114 stream: Optional[bool] = False,
115 ) -> AsyncGenerator:
116 agent = await self.get_agent(agent_id)
117
118 # wrapper request to make it easier to pass around (internal only, not exposed to API)
119 request = AgentTurnCreateRequest(
120 agent_id=agent_id,
121 session_id=session_id,
122 messages=messages,
123 attachments=attachments,
124 stream=stream,
125 )
126
127 async for event in agent.create_and_execute_turn(request):
128 yield event