|
| 1 | +"""Request parameter model for Llama Stack responses API calls.""" |
| 2 | + |
| 3 | +from collections.abc import Mapping |
| 4 | +from typing import Any, Final, Optional |
| 5 | + |
| 6 | +from llama_stack_api.openai_responses import ( |
| 7 | + OpenAIResponseInputTool as InputTool, |
| 8 | +) |
| 9 | +from llama_stack_api.openai_responses import ( |
| 10 | + OpenAIResponseInputToolChoice as ToolChoice, |
| 11 | +) |
| 12 | +from llama_stack_api.openai_responses import ( |
| 13 | + OpenAIResponsePrompt as Prompt, |
| 14 | +) |
| 15 | +from llama_stack_api.openai_responses import ( |
| 16 | + OpenAIResponseReasoning as Reasoning, |
| 17 | +) |
| 18 | +from llama_stack_api.openai_responses import ( |
| 19 | + OpenAIResponseText as Text, |
| 20 | +) |
| 21 | +from llama_stack_api.openai_responses import ( |
| 22 | + OpenAIResponseToolMCP as OutputToolMCP, |
| 23 | +) |
| 24 | +from pydantic import BaseModel, Field |
| 25 | + |
| 26 | +from utils.tool_formatter import translate_vector_store_ids_to_user_facing |
| 27 | +from utils.types import IncludeParameter, ResponseInput |
| 28 | + |
| 29 | +# Attribute names that are echoed back in the response. |
| 30 | +_ECHOED_FIELDS: Final[set[str]] = set( |
| 31 | + { |
| 32 | + "instructions", |
| 33 | + "max_tool_calls", |
| 34 | + "max_output_tokens", |
| 35 | + "metadata", |
| 36 | + "model", |
| 37 | + "parallel_tool_calls", |
| 38 | + "previous_response_id", |
| 39 | + "prompt", |
| 40 | + "reasoning", |
| 41 | + "safety_identifier", |
| 42 | + "temperature", |
| 43 | + "top_p", |
| 44 | + "truncation", |
| 45 | + "text", |
| 46 | + "tool_choice", |
| 47 | + "store", |
| 48 | + } |
| 49 | +) |
| 50 | + |
| 51 | + |
| 52 | +class ResponsesApiParams(BaseModel): |
| 53 | + """Parameters for a Llama Stack Responses API request. |
| 54 | +
|
| 55 | + All fields accepted by the Llama Stack client responses.create() body are |
| 56 | + included so that dumped model can be passed directly to response create. |
| 57 | + """ |
| 58 | + |
| 59 | + input: ResponseInput = Field(description="The input text or structured input items") |
| 60 | + model: str = Field(description='The full model ID in format "provider/model"') |
| 61 | + conversation: str = Field(description="The conversation ID in llama-stack format") |
| 62 | + include: Optional[list[IncludeParameter]] = Field( |
| 63 | + default=None, |
| 64 | + description="Output item types to include in the response", |
| 65 | + ) |
| 66 | + instructions: Optional[str] = Field( |
| 67 | + default=None, description="The resolved system prompt" |
| 68 | + ) |
| 69 | + max_infer_iters: Optional[int] = Field( |
| 70 | + default=None, |
| 71 | + description="Maximum number of inference iterations", |
| 72 | + ) |
| 73 | + max_output_tokens: Optional[int] = Field( |
| 74 | + default=None, |
| 75 | + description="Maximum number of tokens allowed in the response", |
| 76 | + ) |
| 77 | + max_tool_calls: Optional[int] = Field( |
| 78 | + default=None, |
| 79 | + description="Maximum tool calls allowed in a single response", |
| 80 | + ) |
| 81 | + metadata: Optional[dict[str, str]] = Field( |
| 82 | + default=None, |
| 83 | + description="Custom metadata for tracking or logging", |
| 84 | + ) |
| 85 | + parallel_tool_calls: Optional[bool] = Field( |
| 86 | + default=None, |
| 87 | + description="Whether the model can make multiple tool calls in parallel", |
| 88 | + ) |
| 89 | + previous_response_id: Optional[str] = Field( |
| 90 | + default=None, |
| 91 | + description="Identifier of the previous response in a multi-turn conversation", |
| 92 | + ) |
| 93 | + prompt: Optional[Prompt] = Field( |
| 94 | + default=None, |
| 95 | + description="Prompt template with variables for dynamic substitution", |
| 96 | + ) |
| 97 | + reasoning: Optional[Reasoning] = Field( |
| 98 | + default=None, |
| 99 | + description="Reasoning configuration for the response", |
| 100 | + ) |
| 101 | + safety_identifier: Optional[str] = Field( |
| 102 | + default=None, |
| 103 | + description="Stable identifier for safety monitoring and abuse detection", |
| 104 | + ) |
| 105 | + store: bool = Field(description="Whether to store the response") |
| 106 | + stream: bool = Field(description="Whether to stream the response") |
| 107 | + temperature: Optional[float] = Field( |
| 108 | + default=None, |
| 109 | + description="Sampling temperature (e.g. 0.0-2.0)", |
| 110 | + ) |
| 111 | + text: Optional[Text] = Field( |
| 112 | + default=None, |
| 113 | + description="Text response configuration (format constraints)", |
| 114 | + ) |
| 115 | + tool_choice: Optional[ToolChoice] = Field( |
| 116 | + default=None, |
| 117 | + description="Tool selection strategy", |
| 118 | + ) |
| 119 | + tools: Optional[list[InputTool]] = Field( |
| 120 | + default=None, |
| 121 | + description="Prepared tool groups for Responses API (same type as ResponsesRequest.tools)", |
| 122 | + ) |
| 123 | + extra_headers: Optional[dict[str, str]] = Field( |
| 124 | + default=None, |
| 125 | + description="Extra HTTP headers to send with the request (e.g. x-llamastack-provider-data)", |
| 126 | + ) |
| 127 | + |
| 128 | + def model_dump(self, *args: Any, **kwargs: Any) -> dict[str, Any]: |
| 129 | + """Serialize params, re-injecting MCP authorization stripped by exclude=True. |
| 130 | +
|
| 131 | + llama-stack-api marks ``InputToolMCP.authorization`` with |
| 132 | + ``Field(exclude=True)`` to prevent token leakage in API responses. |
| 133 | + The base ``model_dump()`` therefore strips the field, but we need it |
| 134 | + in the request payload so llama-stack server can authenticate with |
| 135 | + MCP servers. See LCORE-1414 / GitHub issue #1269. |
| 136 | + """ |
| 137 | + result = super().model_dump(*args, **kwargs) |
| 138 | + # Only one context option is allowed, previous_response_id has priority |
| 139 | + # Turn is added to conversation manually if previous_response_id is used |
| 140 | + if self.previous_response_id: |
| 141 | + result.pop("conversation", None) |
| 142 | + dumped_tools = result.get("tools") |
| 143 | + if not self.tools or not isinstance(dumped_tools, list): |
| 144 | + return result |
| 145 | + if len(dumped_tools) != len(self.tools): |
| 146 | + return result |
| 147 | + for tool, dumped_tool in zip(self.tools, dumped_tools): |
| 148 | + authorization = getattr(tool, "authorization", None) |
| 149 | + if authorization is not None and isinstance(dumped_tool, dict): |
| 150 | + dumped_tool["authorization"] = authorization |
| 151 | + return result |
| 152 | + |
| 153 | + def echoed_params(self, rag_id_mapping: Mapping[str, str]) -> dict[str, Any]: |
| 154 | + """Build kwargs echoed into synthetic OpenAI-style responses (e.g. moderation blocks). |
| 155 | +
|
| 156 | + Parameters: |
| 157 | + rag_id_mapping: Llama Stack vector_db_id to user-facing RAG id (from app config). |
| 158 | + Returns: |
| 159 | + dict[str, Any]: Field names and values to merge into the response object. |
| 160 | + """ |
| 161 | + data = self.model_dump(include=_ECHOED_FIELDS) |
| 162 | + if self.tools is not None: |
| 163 | + tool_dicts: list[dict[str, Any]] = [] |
| 164 | + for t in self.tools: |
| 165 | + if t.type == "mcp": |
| 166 | + validated = OutputToolMCP.model_validate(t.model_dump()) |
| 167 | + tool_dicts.append(validated.model_dump()) |
| 168 | + else: |
| 169 | + tool_dicts.append(t.model_dump()) |
| 170 | + |
| 171 | + data["tools"] = translate_vector_store_ids_to_user_facing( |
| 172 | + tool_dicts, rag_id_mapping |
| 173 | + ) |
| 174 | + |
| 175 | + return data |
0 commit comments