解析))
LiteLLM BitBucket 提示詞管理集成用 BitBucket 倉庫集中管理 .prompt 提示詞含源碼級實現(xiàn)解析【免費下載鏈接】litellmThe fastest, litest AI Gateway. Rust core with Python SDK. Call 100 LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]項目地址: https://gitcode.com/GitHub_Trending/li/litellm本文以 LiteLLM 的 BitBucket 提示詞管理集成為主體完整講解如何在 BitBucket 倉庫中用.prompt文件組織團隊提示詞、如何通過litellm.completion()和 Proxy Server 調用這些提示詞并結合倉庫源碼bitbucket_client.py、bitbucket_prompt_manager.py剖析模板沙箱渲染、消息解析與參數(shù)提取的底層機制。讀完本文你可以把團隊提示詞從散落的代碼常量遷移到具備版本控制和訪問控制的 BitBucket 倉庫中并通過bitbucket/模型前綴透明地接入現(xiàn)有 LiteLLM 調用。集成概覽與模塊構成BitBucket 集成的目標非常明確把.prompt文件放到 BitBucket 倉庫里讓 LiteLLM 在運行時從倉庫拉取、渲染并應用提示詞從而復用 BitBucket 自帶的 workspace/倉庫/分支權限體系和版本管理能力。模塊由三個文件組成見 litellm/integrations/bitbucket/ 目錄文件職責bitbucket_client.pyBitBucketClient封裝 BitBucket REST API文件拉取、目錄列舉、分支查詢、連接測試以及路徑安全校驗bitbucket_prompt_manager.pyBitBucketPromptManager/BitBucketTemplateManager負責 YAML frontmatter 解析、Jinja2 沙箱模板渲染、把渲染結果解析成 chat messages、提取模型參數(shù)init.py導出set_global_bitbucket_config等公共 API注冊prompt_initializer到prompt_initializer_registrykey 為bitbucket來自 init_prompts.py 中的SupportedPromptIntegrations.BITBUCKETBitBucketPromptManager繼承自 CustomPromptManagement而后者進一步對接 PromptManagementBase 的get_chat_completion_prompt接口——這意味著提示詞管理對litellm.completion()來說是一個標準的“前置鉤子”不需要修改任何現(xiàn)有調用簽名??焖匍_始1. 在 BitBucket 中組織提示詞倉庫在你的 BitBucket workspace 下創(chuàng)建倉庫按如下結構存放.prompt文件your-repo/ ├── prompts/ │ ├── chat_assistant.prompt │ ├── code_reviewer.prompt │ └── data_analyst.prompt2. 編寫.prompt文件以prompts/chat_assistant.prompt為例。文件由YAML frontmatter---包裹和模板正文兩部分組成--- model: gpt-4 temperature: 0.7 max_tokens: 150 input: schema: user_message: string system_context?: string --- {% if system_context %}System: {{system_context}} {% endif %}User: {{user_message}}frontmatter 中各字段的實際消費方式可對照 bitbucket_prompt_manager.py 的BitBucketPromptTemplate.__init__model最終覆蓋litellm_params[model]的模型名temperature、max_tokens、top_p、frequency_penalty、presence_penalty被pre_call_hook顯式白名單提取并合并進調用參數(shù)input.schema聲明模板變量?后綴表示可選用于人工約定與校驗其余任意 key 會進入optional_params一并隨 metadata 返回。模板正文使用 Handlebars 風格分隔符{{variable}}、{% block %}、{# comment #}。從源碼看這一套分隔符是通過配置 Jinja2 環(huán)境變量實現(xiàn)的bitbucket_prompt_manager.pyself.jinja_env ImmutableSandboxedEnvironment( loaderDictLoader({}), autoescapeselect_autoescape([html, xml]), variable_start_string{{, variable_end_string}}, block_start_string{%, block_end_string%}, comment_start_string{#, comment_end_string#}, )3. 配置 BitBucket 訪問方式 AAccess Token推薦import litellm bitbucket_config { workspace: your-workspace, repository: your-repo, access_token: your-access-token, branch: main, # 可選默認 main } litellm.set_global_bitbucket_config(bitbucket_config)方式 BBasic 認證import litellm bitbucket_config { workspace: your-workspace, repository: your-repo, username: your-username, access_token: your-app-password, # basic 認證使用 app password auth_method: basic, branch: main } litellm.set_global_bitbucket_config(bitbucket_config)set_global_bitbucket_config在 litellm/init.py 中導出本質是設置模塊級全局變量litellm.global_bitbucket_config。認證頭的構造邏輯在 bitbucket_client.pyauth_method basic且有username時把username:app_password做 base64 編碼放入Authorization: Basic ...否則默認走Authorization: Bearer access_token。4. 在 LiteLLM 中調用# 模型前綴 bitbucket/ 告訴 LiteLLM 走 BitBucket 提示詞管理 response litellm.completion( modelbitbucket/gpt-4, # 實際模型來自 .prompt 文件的 frontmatter prompt_idprompts/chat_assistant, # 提示詞文件在倉庫中的相對路徑不含 .prompt 后綴 prompt_variables{ user_message: What is machine learning?, system_context: You are a helpful AI tutor. }, # 額外 messages 會追加在提示詞渲染結果之后 messages[{role: user, content: Please explain it simply.}] ) print(response.choices[0].message.content)模型名中的bitbucket前綴是集成名integration_name屬性返回值見 bitbucket_prompt_manager.py。運行時回調構建邏輯會按名字找到 BitBucket 管理器litellm_logging.py 中l(wèi)ogging_integration bitbucket的分支會讀取litellm.global_bitbucket_config若為空則拋出BitBucket configuration not found. Please set litellm.global_bitbucket_config first.否則單例化一個BitBucketPromptManager緩存進內存 logger 列表。Proxy Server 配置在 Proxy 場景下global_bitbucket_config寫在config.yaml的litellm_settings中。Proxy 啟動時會識別該 key 并調用set_global_bitbucket_config見 proxy_server.py。1. 創(chuàng)建prompts/hello.prompt--- model: gpt-4 temperature: 0.7 --- System: You are a helpful assistant. User: {{user_message}}2. 編寫 config.yamlmodel_list: - model_name: my-bitbucket-model litellm_params: model: bitbucket/gpt-4 prompt_id: prompts/hello api_key: os.environ/OPENAI_API_KEY litellm_settings: global_bitbucket_config: workspace: your-workspace repository: your-repo access_token: your-access-token branch: main3. 啟動 Proxylitellm --config config.yaml --detailed_debug4. 調用驗證curl -L -X POST http://0.0.0.0:4000/v1/chat/completions \ -H Content-Type: application/json \ -H Authorization: Bearer sk-1234 \ -d { model: my-bitbucket-model, messages: [{role: user, content: IGNORED}], prompt_variables: { user_message: What is the capital of France? } }注意示例中messages的內容為 IGNORED因為當渲染結果能解析出帶角色的消息時pre_call_hook會直接用提示詞解析出的 messages替換原有 messages見下文實現(xiàn)解析所以業(yè)務參數(shù)主要通過prompt_variables傳入。.prompt文件格式詳解基本結構--- # 模型配置 model: gpt-4 temperature: 0.7 max_tokens: 500 # 輸入 schema可選 input: schema: user_message: string system_context?: string --- System: You are a helpful {{role}} assistant. User: {{user_message}}frontmatter 解析邏輯見 _parse_prompt_file以---拆分出 YAML 頭與模板正文優(yōu)先用yaml.safe_load解析若環(huán)境缺少 PyYAML 則退化為一個只支持簡單key: value行的基礎解析器_parse_yaml_basic支持 bool/int/float/str 推斷。高級用法多角色對話——正文中以System:/User:/Assistant:開頭的行會被解析為對應角色的獨立消息解析實現(xiàn)見 _parse_prompt_to_messages不區(qū)分大小寫識別前綴連續(xù)行歸屬同一消息空行忽略若整段都沒有角色前綴則整體作為一條 user 消息--- model: gpt-4 temperature: 0.3 --- System: You are a helpful coding assistant. User: {{user_question}}動態(tài)模型選擇——model字段本身也可以是模板變量渲染后的 metadata 會再取model值寫回litellm_params--- model: {{preferred_model}} # 模型可以是變量 temperature: 0.7 --- System: You are a helpful assistant specialized in {{domain}}. User: {{user_message}}運行時機制pre_call_hook 與參數(shù)提取pre_call_hookbitbucket_prompt_manager.py是理解整個集成的關鍵流程如下無prompt_id時直接透傳原 messages 與參數(shù)通過get_prompt_template拉取BitBucketClient.get_file_content請求{base_url}/repositories/{workspace}/{repository}/src/{branch}/{prompt_id}.prompt并渲染模板同時取回 metadata把渲染文本解析成 messages解析成功則替換原 messages解析不出角色則把渲染文本作為一條 user 消息前置用 frontmatter 的model覆蓋litellm_params[model]并從白名單[temperature, max_tokens, top_p, frequency_penalty, presence_penalty]中提取參數(shù)合并進litellm_params任一環(huán)節(jié)異常只記錄verbose_proxy_logger錯誤并回退到原始 messages不會讓整次 LLM 調用失敗——這是一個有意的容錯設計。此外_compile_prompt_helper/async_compile_prompt_helperbitbucket_prompt_manager.py把同一套“拉取—渲染—解析—取參”流程封裝為PromptManagementClient結構返回供新版PromptManagementBase.get_chat_completion_prompt接口復用異步版本因底層 HTTP 是同步客戶端直接委托同步實現(xiàn)。API 參考BitBucket 配置項bitbucket_config { workspace: str, # 必填BitBucket workspace 名 repository: str, # 必填倉庫名 access_token: str, # 必填access token 或 app password branch: str, # 可選拉取分支默認 main base_url: str, # 可選自定義 BitBucket API URL auth_method: str, # 可選token 或 basic默認 token username: str, # 可選basic 認證用戶名 }BitBucketClient構造函數(shù)會校驗workspace、repository、access_token三者缺一不可否則拋ValueError見 bitbucket_client.py。需要指出一個與文檔描述不一致的實現(xiàn)細節(jié)源碼中base_url的讀取寫成了config.get(, https://api.bitbucket.org/2.0)bitbucket_client.py——取的是空字符串 key 而非base_url。從源碼結構看當前版本傳入base_url配置項不會生效客戶端實際總是請求https://api.bitbucket.org/2.0如果你依賴私有 BitBucket 實例BitBucket Server/Data Center這一點需要留意可先通過BitBucketClient.test_connection()調用GET /repositories/{workspace}/{repository}驗證連通性??蛻舳四芰σ挥[BitBucketClient除拉取文件外還提供list_files(directory_path, file_extension.prompt)列出目錄下指定擴展名的文件走src/目錄枚舉接口過濾type commit_file的條目get_repository_info()/test_connection()倉庫信息與連通性測試get_branches()枚舉分支refs/branchesget_file_metadata(file_path)用Range: bytes0-0請求僅取響應頭拿到content-type、content-length、last-modified適合做緩存失效判斷。completion 調用參數(shù)response litellm.completion( modelbitbucket/base_model, # 必填如 bitbucket/gpt-4 prompt_idstr, # 必填.prompt 文件路徑不含擴展名 prompt_variablesdict, # 可選模板渲染變量 bitbucket_configdict, # 可選未設全局配置時傳入 messageslist, # 可選附加消息 )安全設計沙箱模板與路徑校驗提示詞文件來自倉庫本質上是不可信輸入源碼中做了兩層針對性防護Jinja2 沙箱如前文配置所示環(huán)境使用ImmutableSandboxedEnvironment而非普通Environment。源碼注釋解釋得很直白擁有倉庫寫權限的人可以在.prompt里塞入能觸達__class__.__init__.__globals__的 Jinja 語法在普通環(huán)境下可演變?yōu)榇碇鳈C上的 RCE沙箱會阻斷這種屬性遍歷同時保留正常的{{ var }}替換行為。路徑安全校驗_sanitize_file_pathbitbucket_client.py拒絕包含#、?的路徑拒絕出現(xiàn)..的路徑穿越并對每個路徑段做 URL 編碼再拼進src/{branch}/{path}請求。文件內容讀取還兼容兩種返回形態(tài)content-type為text/*時直接取文本否則嘗試把響應體按 base64 解碼BitBucket 對二進制文件的返回方式解碼失敗再回退到response.text。HTTP 狀態(tài)碼被映射為可讀異常404→ 返回None文件不存在403→ 拋出帶 workspace/repository 名的 Access denied 提示401→ Authentication failed. Check your BitBucket access token and permissions.見 bitbucket_client.py。團隊級訪問控制BitBucket 自帶的權限體系直接復用為提示詞的訪問控制Workspace 級權限控制對整個 workspace 的訪問倉庫級權限控制對具體提示詞倉庫的訪問分支級權限通過分支保護規(guī)則隔離生產提示詞用戶與群組管理為團隊成員分配不同訪問級別。落地建議與 README 建議一致按團隊劃分 workspace/倉庫例如team-a-prompts/、team-b-prompts/、team-c-prompts/倉庫權限上團隊成員給只讀、提示詞維護者給寫權限、生產分支啟用保護規(guī)則每個團隊使用獨立的 access tokentoken 按倉庫范圍授權敏感環(huán)境使用 app password 疊加 basic 認證。其他安全要點access token 應通過環(huán)境變量或密鑰管理系統(tǒng)注入而非硬編碼利用 BitBucket 的審計日志追蹤倉庫訪問。錯誤處理與故障排查常見問題與排查方向現(xiàn)象排查點Access denied檢查 token 對 workspace/repository 的 403 權限Authentication failed401核對 access token / app password 是否有效File not found確認.prompt文件存在于配置的目標分支、路徑與prompt_id一致不含.prompt后綴模板渲染錯誤檢查 Handlebars 風格語法{{ }}、{% %}、{# #}是否合法調試模式開啟詳細日志后BitBucket 提示詞調用會輸出完整日志import litellm litellm.set_verbose True response litellm.completion( modelbitbucket/gpt-4, prompt_idyour_prompt, prompt_variables{key: value} )另有一個容易踩到的點pre_call_hook捕獲異常后只記日志并回退因此“調用成功但模型/參數(shù)不對”時應同時檢查verbose_proxy_logger輸出確認提示詞渲染是否真的生效。從文件式 Dotprompt 遷移如果你的團隊目前使用 dotprompt 集成litellm/integrations/dotprompt/管理本地.prompt文件遷移到 BitBucket 的路徑是把現(xiàn)有.prompt文件上傳到 BitBucket 倉庫目錄結構可保持不變把全局配置從本地路徑換成global_bitbucket_configworkspace/repository/access_token/branch用 BitBucket 權限體系配置團隊訪問代碼中把dotprompt/模型前綴改為bitbucket/。由于兩者共用同一套PromptManagementBase接口與 Handlebars 風格模板約定遷移主要影響的是提示詞的來源與協(xié)作方式——獲得版本歷史、分支保護和團隊權限而調用側代碼幾乎無需改動。小結LiteLLM 的 BitBucket 集成把提示詞管理做成了對調用方近乎透明的前置層bitbucket/model前綴 prompt_idprompt_variables三要素即可完成接入YAML frontmatter 承載模型與參數(shù)正文經 Jinja2 沙箱渲染后解析為標準 chat messages。Proxy 場景只需在litellm_settings.global_bitbucket_config中聲明一次倉庫與憑據。理解 bitbucket_client.py 的路徑校驗/認證映射與 bitbucket_prompt_manager.py 的 hook 回退語義有助于在私有化部署和故障排查時快速定位問題?!久赓M下載鏈接】litellmThe fastest, litest AI Gateway. Rust core with Python SDK. Call 100 LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]項目地址: https://gitcode.com/GitHub_Trending/li/litellm創(chuàng)作聲明:本文部分內容由AI輔助生成(AIGC),僅供參考