Elffuss BraidHub

kikocis/llama-stack public

3fc339af16ee · 12.3 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
7from datetime import datetime
8from enum import Enum
9from typing import Any, Dict, List, Literal, Optional, Protocol, Union
10
11from llama_models.schema_utils import json_schema_type, webmethod
12
13from pydantic import BaseModel, ConfigDict, Field
14from typing_extensions import Annotated
15
16from llama_models.llama3.api.datatypes import * # noqa: F403
17from llama_stack.apis.common.deployment_types import * # noqa: F403
18from llama_stack.apis.inference import * # noqa: F403
19from llama_stack.apis.safety import * # noqa: F403
20from llama_stack.apis.memory import * # noqa: F403
21
22
23@json_schema_type
24class Attachment(BaseModel):
25 content: InterleavedTextMedia | URL
26 mime_type: str
27
28
29class AgentTool(Enum):
30 brave_search = "brave_search"
31 wolfram_alpha = "wolfram_alpha"
32 photogen = "photogen"
33 code_interpreter = "code_interpreter"
34
35 function_call = "function_call"
36 memory = "memory"
37
38
39class ToolDefinitionCommon(BaseModel):
40 input_shields: Optional[List[ShieldDefinition]] = Field(default_factory=list)
41 output_shields: Optional[List[ShieldDefinition]] = Field(default_factory=list)
42
43
44class SearchEngineType(Enum):
45 bing = "bing"
46 brave = "brave"
47
48
49@json_schema_type
50class SearchToolDefinition(ToolDefinitionCommon):
51 # NOTE: brave_search is just a placeholder since model always uses
52 # brave_search as tool call name
53 type: Literal[AgentTool.brave_search.value] = AgentTool.brave_search.value
54 api_key: str
55 engine: SearchEngineType = SearchEngineType.brave
56 remote_execution: Optional[RestAPIExecutionConfig] = None
57
58
59@json_schema_type
60class WolframAlphaToolDefinition(ToolDefinitionCommon):
61 type: Literal[AgentTool.wolfram_alpha.value] = AgentTool.wolfram_alpha.value
62 api_key: str
63 remote_execution: Optional[RestAPIExecutionConfig] = None
64
65
66@json_schema_type
67class PhotogenToolDefinition(ToolDefinitionCommon):
68 type: Literal[AgentTool.photogen.value] = AgentTool.photogen.value
69 remote_execution: Optional[RestAPIExecutionConfig] = None
70
71
72@json_schema_type
73class CodeInterpreterToolDefinition(ToolDefinitionCommon):
74 type: Literal[AgentTool.code_interpreter.value] = AgentTool.code_interpreter.value
75 enable_inline_code_execution: bool = True
76 remote_execution: Optional[RestAPIExecutionConfig] = None
77
78
79@json_schema_type
80class FunctionCallToolDefinition(ToolDefinitionCommon):
81 type: Literal[AgentTool.function_call.value] = AgentTool.function_call.value
82 function_name: str
83 description: str
84 parameters: Dict[str, ToolParamDefinition]
85 remote_execution: Optional[RestAPIExecutionConfig] = None
86
87
88class _MemoryBankConfigCommon(BaseModel):
89 bank_id: str
90
91
92class AgentVectorMemoryBankConfig(_MemoryBankConfigCommon):
93 type: Literal[MemoryBankType.vector.value] = MemoryBankType.vector.value
94
95
96class AgentKeyValueMemoryBankConfig(_MemoryBankConfigCommon):
97 type: Literal[MemoryBankType.keyvalue.value] = MemoryBankType.keyvalue.value
98 keys: List[str] # what keys to focus on
99
100
101class AgentKeywordMemoryBankConfig(_MemoryBankConfigCommon):
102 type: Literal[MemoryBankType.keyword.value] = MemoryBankType.keyword.value
103
104
105class AgentGraphMemoryBankConfig(_MemoryBankConfigCommon):
106 type: Literal[MemoryBankType.graph.value] = MemoryBankType.graph.value
107 entities: List[str] # what entities to focus on
108
109
110MemoryBankConfig = Annotated[
111 Union[
112 AgentVectorMemoryBankConfig,
113 AgentKeyValueMemoryBankConfig,
114 AgentKeywordMemoryBankConfig,
115 AgentGraphMemoryBankConfig,
116 ],
117 Field(discriminator="type"),
118]
119
120
121class MemoryQueryGenerator(Enum):
122 default = "default"
123 llm = "llm"
124 custom = "custom"
125
126
127class DefaultMemoryQueryGeneratorConfig(BaseModel):
128 type: Literal[MemoryQueryGenerator.default.value] = (
129 MemoryQueryGenerator.default.value
130 )
131 sep: str = " "
132
133
134class LLMMemoryQueryGeneratorConfig(BaseModel):
135 type: Literal[MemoryQueryGenerator.llm.value] = MemoryQueryGenerator.llm.value
136 model: str
137 template: str
138
139
140class CustomMemoryQueryGeneratorConfig(BaseModel):
141 type: Literal[MemoryQueryGenerator.custom.value] = MemoryQueryGenerator.custom.value
142
143
144MemoryQueryGeneratorConfig = Annotated[
145 Union[
146 DefaultMemoryQueryGeneratorConfig,
147 LLMMemoryQueryGeneratorConfig,
148 CustomMemoryQueryGeneratorConfig,
149 ],
150 Field(discriminator="type"),
151]
152
153
154class MemoryToolDefinition(ToolDefinitionCommon):
155 type: Literal[AgentTool.memory.value] = AgentTool.memory.value
156 memory_bank_configs: List[MemoryBankConfig] = Field(default_factory=list)
157 # This config defines how a query is generated using the messages
158 # for memory bank retrieval.
159 query_generator_config: MemoryQueryGeneratorConfig = Field(
160 default=DefaultMemoryQueryGeneratorConfig()
161 )
162 max_tokens_in_context: int = 4096
163 max_chunks: int = 10
164
165
166AgentToolDefinition = Annotated[
167 Union[
168 SearchToolDefinition,
169 WolframAlphaToolDefinition,
170 PhotogenToolDefinition,
171 CodeInterpreterToolDefinition,
172 FunctionCallToolDefinition,
173 MemoryToolDefinition,
174 ],
175 Field(discriminator="type"),
176]
177
178
179class StepCommon(BaseModel):
180 turn_id: str
181 step_id: str
182 started_at: Optional[datetime] = None
183 completed_at: Optional[datetime] = None
184
185
186class StepType(Enum):
187 inference = "inference"
188 tool_execution = "tool_execution"
189 shield_call = "shield_call"
190 memory_retrieval = "memory_retrieval"
191
192
193@json_schema_type
194class InferenceStep(StepCommon):
195 model_config = ConfigDict(protected_namespaces=())
196
197 step_type: Literal[StepType.inference.value] = StepType.inference.value
198 model_response: CompletionMessage
199
200
201@json_schema_type
202class ToolExecutionStep(StepCommon):
203 step_type: Literal[StepType.tool_execution.value] = StepType.tool_execution.value
204 tool_calls: List[ToolCall]
205 tool_responses: List[ToolResponse]
206
207
208@json_schema_type
209class ShieldCallStep(StepCommon):
210 step_type: Literal[StepType.shield_call.value] = StepType.shield_call.value
211 response: ShieldResponse
212
213
214@json_schema_type
215class MemoryRetrievalStep(StepCommon):
216 step_type: Literal[StepType.memory_retrieval.value] = (
217 StepType.memory_retrieval.value
218 )
219 memory_bank_ids: List[str]
220 inserted_context: InterleavedTextMedia
221
222
223Step = Annotated[
224 Union[
225 InferenceStep,
226 ToolExecutionStep,
227 ShieldCallStep,
228 MemoryRetrievalStep,
229 ],
230 Field(discriminator="step_type"),
231]
232
233
234@json_schema_type
235class Turn(BaseModel):
236 """A single turn in an interaction with an Agentic System."""
237
238 turn_id: str
239 session_id: str
240 input_messages: List[
241 Union[
242 UserMessage,
243 ToolResponseMessage,
244 ]
245 ]
246 steps: List[Step]
247 output_message: CompletionMessage
248 output_attachments: List[Attachment] = Field(default_factory=list)
249
250 started_at: datetime
251 completed_at: Optional[datetime] = None
252
253
254@json_schema_type
255class Session(BaseModel):
256 """A single session of an interaction with an Agentic System."""
257
258 session_id: str
259 session_name: str
260 turns: List[Turn]
261 started_at: datetime
262
263 memory_bank: Optional[MemoryBank] = None
264
265
266class AgentConfigCommon(BaseModel):
267 sampling_params: Optional[SamplingParams] = SamplingParams()
268
269 input_shields: Optional[List[ShieldDefinition]] = Field(default_factory=list)
270 output_shields: Optional[List[ShieldDefinition]] = Field(default_factory=list)
271
272 tools: Optional[List[AgentToolDefinition]] = Field(default_factory=list)
273 tool_choice: Optional[ToolChoice] = Field(default=ToolChoice.auto)
274 tool_prompt_format: Optional[ToolPromptFormat] = Field(
275 default=ToolPromptFormat.json
276 )
277
278
279@json_schema_type
280class AgentConfig(AgentConfigCommon):
281 model: str
282 instructions: str
283
284
285class AgentConfigOverridablePerTurn(AgentConfigCommon):
286 instructions: Optional[str] = None
287
288
289class AgentTurnResponseEventType(Enum):
290 step_start = "step_start"
291 step_complete = "step_complete"
292 step_progress = "step_progress"
293
294 turn_start = "turn_start"
295 turn_complete = "turn_complete"
296
297
298@json_schema_type
299class AgentTurnResponseStepStartPayload(BaseModel):
300 event_type: Literal[AgentTurnResponseEventType.step_start.value] = (
301 AgentTurnResponseEventType.step_start.value
302 )
303 step_type: StepType
304 step_id: str
305 metadata: Optional[Dict[str, Any]] = Field(default_factory=dict)
306
307
308@json_schema_type
309class AgentTurnResponseStepCompletePayload(BaseModel):
310 event_type: Literal[AgentTurnResponseEventType.step_complete.value] = (
311 AgentTurnResponseEventType.step_complete.value
312 )
313 step_type: StepType
314 step_details: Step
315
316
317@json_schema_type
318class AgentTurnResponseStepProgressPayload(BaseModel):
319 model_config = ConfigDict(protected_namespaces=())
320
321 event_type: Literal[AgentTurnResponseEventType.step_progress.value] = (
322 AgentTurnResponseEventType.step_progress.value
323 )
324 step_type: StepType
325 step_id: str
326
327 model_response_text_delta: Optional[str] = None
328 tool_call_delta: Optional[ToolCallDelta] = None
329 tool_response_text_delta: Optional[str] = None
330
331
332@json_schema_type
333class AgentTurnResponseTurnStartPayload(BaseModel):
334 event_type: Literal[AgentTurnResponseEventType.turn_start.value] = (
335 AgentTurnResponseEventType.turn_start.value
336 )
337 turn_id: str
338
339
340@json_schema_type
341class AgentTurnResponseTurnCompletePayload(BaseModel):
342 event_type: Literal[AgentTurnResponseEventType.turn_complete.value] = (
343 AgentTurnResponseEventType.turn_complete.value
344 )
345 turn: Turn
346
347
348@json_schema_type
349class AgentTurnResponseEvent(BaseModel):
350 """Streamed agent execution response."""
351
352 payload: Annotated[
353 Union[
354 AgentTurnResponseStepStartPayload,
355 AgentTurnResponseStepProgressPayload,
356 AgentTurnResponseStepCompletePayload,
357 AgentTurnResponseTurnStartPayload,
358 AgentTurnResponseTurnCompletePayload,
359 ],
360 Field(discriminator="event_type"),
361 ]
362
363
364@json_schema_type
365class AgentCreateResponse(BaseModel):
366 agent_id: str
367
368
369@json_schema_type
370class AgentSessionCreateResponse(BaseModel):
371 session_id: str
372
373
374@json_schema_type
375class AgentTurnCreateRequest(AgentConfigOverridablePerTurn):
376 agent_id: str
377 session_id: str
378
379 # TODO: figure out how we can simplify this and make why
380 # ToolResponseMessage needs to be here (it is function call
381 # execution from outside the system)
382 messages: List[
383 Union[
384 UserMessage,
385 ToolResponseMessage,
386 ]
387 ]
388 attachments: Optional[List[Attachment]] = None
389
390 stream: Optional[bool] = False
391
392
393@json_schema_type
394class AgentTurnResponseStreamChunk(BaseModel):
395 event: AgentTurnResponseEvent
396
397
398@json_schema_type
399class AgentStepResponse(BaseModel):
400 step: Step
401
402
403class Agents(Protocol):
404 @webmethod(route="/agents/create")
405 async def create_agent(
406 self,
407 agent_config: AgentConfig,
408 ) -> AgentCreateResponse: ...
409
410 @webmethod(route="/agents/turn/create")
411 async def create_agent_turn(
412 self,
413 agent_id: str,
414 session_id: str,
415 messages: List[
416 Union[
417 UserMessage,
418 ToolResponseMessage,
419 ]
420 ],
421 attachments: Optional[List[Attachment]] = None,
422 stream: Optional[bool] = False,
423 ) -> AgentTurnResponseStreamChunk: ...
424
425 @webmethod(route="/agents/turn/get")
426 async def get_agents_turn(
427 self,
428 agent_id: str,
429 turn_id: str,
430 ) -> Turn: ...
431
432 @webmethod(route="/agents/step/get")
433 async def get_agents_step(
434 self, agent_id: str, turn_id: str, step_id: str
435 ) -> AgentStepResponse: ...
436
437 @webmethod(route="/agents/session/create")
438 async def create_agent_session(
439 self,
440 agent_id: str,
441 session_name: str,
442 ) -> AgentSessionCreateResponse: ...
443
444 @webmethod(route="/agents/session/get")
445 async def get_agents_session(
446 self,
447 agent_id: str,
448 session_id: str,
449 turn_ids: Optional[List[str]] = None,
450 ) -> Session: ...
451
452 @webmethod(route="/agents/session/delete")
453 async def delete_agents_session(self, agent_id: str, session_id: str) -> None: ...
454
455 @webmethod(route="/agents/delete")
456 async def delete_agents(
457 self,
458 agent_id: str,
459 ) -> None: ...