Elffuss BraidHub

kikocis/llama-stack public

main · 12.4 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[str]] = Field(default_factory=list)
41 output_shields: Optional[List[str]] = 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
154@json_schema_type
155class MemoryToolDefinition(ToolDefinitionCommon):
156 type: Literal[AgentTool.memory.value] = AgentTool.memory.value
157 memory_bank_configs: List[MemoryBankConfig] = Field(default_factory=list)
158 # This config defines how a query is generated using the messages
159 # for memory bank retrieval.
160 query_generator_config: MemoryQueryGeneratorConfig = Field(
161 default=DefaultMemoryQueryGeneratorConfig()
162 )
163 max_tokens_in_context: int = 4096
164 max_chunks: int = 10
165
166
167AgentToolDefinition = Annotated[
168 Union[
169 SearchToolDefinition,
170 WolframAlphaToolDefinition,
171 PhotogenToolDefinition,
172 CodeInterpreterToolDefinition,
173 FunctionCallToolDefinition,
174 MemoryToolDefinition,
175 ],
176 Field(discriminator="type"),
177]
178
179
180class StepCommon(BaseModel):
181 turn_id: str
182 step_id: str
183 started_at: Optional[datetime] = None
184 completed_at: Optional[datetime] = None
185
186
187class StepType(Enum):
188 inference = "inference"
189 tool_execution = "tool_execution"
190 shield_call = "shield_call"
191 memory_retrieval = "memory_retrieval"
192
193
194@json_schema_type
195class InferenceStep(StepCommon):
196 model_config = ConfigDict(protected_namespaces=())
197
198 step_type: Literal[StepType.inference.value] = StepType.inference.value
199 model_response: CompletionMessage
200
201
202@json_schema_type
203class ToolExecutionStep(StepCommon):
204 step_type: Literal[StepType.tool_execution.value] = StepType.tool_execution.value
205 tool_calls: List[ToolCall]
206 tool_responses: List[ToolResponse]
207
208
209@json_schema_type
210class ShieldCallStep(StepCommon):
211 step_type: Literal[StepType.shield_call.value] = StepType.shield_call.value
212 violation: Optional[SafetyViolation]
213
214
215@json_schema_type
216class MemoryRetrievalStep(StepCommon):
217 step_type: Literal[StepType.memory_retrieval.value] = (
218 StepType.memory_retrieval.value
219 )
220 memory_bank_ids: List[str]
221 inserted_context: InterleavedTextMedia
222
223
224Step = Annotated[
225 Union[
226 InferenceStep,
227 ToolExecutionStep,
228 ShieldCallStep,
229 MemoryRetrievalStep,
230 ],
231 Field(discriminator="step_type"),
232]
233
234
235@json_schema_type
236class Turn(BaseModel):
237 """A single turn in an interaction with an Agentic System."""
238
239 turn_id: str
240 session_id: str
241 input_messages: List[
242 Union[
243 UserMessage,
244 ToolResponseMessage,
245 ]
246 ]
247 steps: List[Step]
248 output_message: CompletionMessage
249 output_attachments: List[Attachment] = Field(default_factory=list)
250
251 started_at: datetime
252 completed_at: Optional[datetime] = None
253
254
255@json_schema_type
256class Session(BaseModel):
257 """A single session of an interaction with an Agentic System."""
258
259 session_id: str
260 session_name: str
261 turns: List[Turn]
262 started_at: datetime
263
264 memory_bank: Optional[MemoryBank] = None
265
266
267class AgentConfigCommon(BaseModel):
268 sampling_params: Optional[SamplingParams] = SamplingParams()
269
270 input_shields: Optional[List[str]] = Field(default_factory=list)
271 output_shields: Optional[List[str]] = Field(default_factory=list)
272
273 tools: Optional[List[AgentToolDefinition]] = Field(default_factory=list)
274 tool_choice: Optional[ToolChoice] = Field(default=ToolChoice.auto)
275 tool_prompt_format: Optional[ToolPromptFormat] = Field(
276 default=ToolPromptFormat.json
277 )
278
279 max_infer_iters: int = 10
280
281
282@json_schema_type
283class AgentConfig(AgentConfigCommon):
284 model: str
285 instructions: str
286 enable_session_persistence: bool
287
288
289class AgentConfigOverridablePerTurn(AgentConfigCommon):
290 instructions: Optional[str] = None
291
292
293class AgentTurnResponseEventType(Enum):
294 step_start = "step_start"
295 step_complete = "step_complete"
296 step_progress = "step_progress"
297
298 turn_start = "turn_start"
299 turn_complete = "turn_complete"
300
301
302@json_schema_type
303class AgentTurnResponseStepStartPayload(BaseModel):
304 event_type: Literal[AgentTurnResponseEventType.step_start.value] = (
305 AgentTurnResponseEventType.step_start.value
306 )
307 step_type: StepType
308 step_id: str
309 metadata: Optional[Dict[str, Any]] = Field(default_factory=dict)
310
311
312@json_schema_type
313class AgentTurnResponseStepCompletePayload(BaseModel):
314 event_type: Literal[AgentTurnResponseEventType.step_complete.value] = (
315 AgentTurnResponseEventType.step_complete.value
316 )
317 step_type: StepType
318 step_details: Step
319
320
321@json_schema_type
322class AgentTurnResponseStepProgressPayload(BaseModel):
323 model_config = ConfigDict(protected_namespaces=())
324
325 event_type: Literal[AgentTurnResponseEventType.step_progress.value] = (
326 AgentTurnResponseEventType.step_progress.value
327 )
328 step_type: StepType
329 step_id: str
330
331 model_response_text_delta: Optional[str] = None
332 tool_call_delta: Optional[ToolCallDelta] = None
333 tool_response_text_delta: Optional[str] = None
334
335
336@json_schema_type
337class AgentTurnResponseTurnStartPayload(BaseModel):
338 event_type: Literal[AgentTurnResponseEventType.turn_start.value] = (
339 AgentTurnResponseEventType.turn_start.value
340 )
341 turn_id: str
342
343
344@json_schema_type
345class AgentTurnResponseTurnCompletePayload(BaseModel):
346 event_type: Literal[AgentTurnResponseEventType.turn_complete.value] = (
347 AgentTurnResponseEventType.turn_complete.value
348 )
349 turn: Turn
350
351
352@json_schema_type
353class AgentTurnResponseEvent(BaseModel):
354 """Streamed agent execution response."""
355
356 payload: Annotated[
357 Union[
358 AgentTurnResponseStepStartPayload,
359 AgentTurnResponseStepProgressPayload,
360 AgentTurnResponseStepCompletePayload,
361 AgentTurnResponseTurnStartPayload,
362 AgentTurnResponseTurnCompletePayload,
363 ],
364 Field(discriminator="event_type"),
365 ]
366
367
368@json_schema_type
369class AgentCreateResponse(BaseModel):
370 agent_id: str
371
372
373@json_schema_type
374class AgentSessionCreateResponse(BaseModel):
375 session_id: str
376
377
378@json_schema_type
379class AgentTurnCreateRequest(AgentConfigOverridablePerTurn):
380 agent_id: str
381 session_id: str
382
383 # TODO: figure out how we can simplify this and make why
384 # ToolResponseMessage needs to be here (it is function call
385 # execution from outside the system)
386 messages: List[
387 Union[
388 UserMessage,
389 ToolResponseMessage,
390 ]
391 ]
392 attachments: Optional[List[Attachment]] = None
393
394 stream: Optional[bool] = False
395
396
397@json_schema_type
398class AgentTurnResponseStreamChunk(BaseModel):
399 event: AgentTurnResponseEvent
400
401
402@json_schema_type
403class AgentStepResponse(BaseModel):
404 step: Step
405
406
407class Agents(Protocol):
408 @webmethod(route="/agents/create")
409 async def create_agent(
410 self,
411 agent_config: AgentConfig,
412 ) -> AgentCreateResponse: ...
413
414 @webmethod(route="/agents/turn/create")
415 async def create_agent_turn(
416 self,
417 agent_id: str,
418 session_id: str,
419 messages: List[
420 Union[
421 UserMessage,
422 ToolResponseMessage,
423 ]
424 ],
425 attachments: Optional[List[Attachment]] = None,
426 stream: Optional[bool] = False,
427 ) -> AgentTurnResponseStreamChunk: ...
428
429 @webmethod(route="/agents/turn/get")
430 async def get_agents_turn(
431 self,
432 agent_id: str,
433 turn_id: str,
434 ) -> Turn: ...
435
436 @webmethod(route="/agents/step/get")
437 async def get_agents_step(
438 self, agent_id: str, turn_id: str, step_id: str
439 ) -> AgentStepResponse: ...
440
441 @webmethod(route="/agents/session/create")
442 async def create_agent_session(
443 self,
444 agent_id: str,
445 session_name: str,
446 ) -> AgentSessionCreateResponse: ...
447
448 @webmethod(route="/agents/session/get")
449 async def get_agents_session(
450 self,
451 agent_id: str,
452 session_id: str,
453 turn_ids: Optional[List[str]] = None,
454 ) -> Session: ...
455
456 @webmethod(route="/agents/session/delete")
457 async def delete_agents_session(self, agent_id: str, session_id: str) -> None: ...
458
459 @webmethod(route="/agents/delete")
460 async def delete_agents(
461 self,
462 agent_id: str,
463 ) -> None: ...