)
LiteLLM BitBucket 提示词管理集成用 BitBucket 仓库集中管理 .prompt 提示词含源码级实现解析【免费下载链接】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剖析模板沙箱渲染、消息解析与参数提取的底层机制。读完本文你可以把团队提示词从散落的代码常量迁移到具备版本控制和访问控制的 BitBucket 仓库中并通过bitbucket/模型前缀透明地接入现有 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、提取模型参数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()来说是一个标准的“前置钩子”不需要修改任何现有调用签名。快速开始1. 在 BitBucket 中组织提示词仓库在你的 BitBucket workspace 下创建仓库按如下结构存放.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显式白名单提取并合并进调用参数input.schema声明模板变量?后缀表示可选用于人工约定与校验其余任意 key 会进入optional_params一并随 metadata 返回。模板正文使用 Handlebars 风格分隔符{{variable}}、{% block %}、{# comment #}。从源码看这一套分隔符是通过配置 Jinja2 环境变量实现的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 中logging_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. 创建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见下文实现解析所以业务参数主要通过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 头与模板正文优先用yaml.safe_load解析若环境缺少 PyYAML 则退化为一个只支持简单key: value行的基础解析器_parse_yaml_basic支持 bool/int/float/str 推断。高级用法多角色对话——正文中以System:/User:/Assistant:开头的行会被解析为对应角色的独立消息解析实现见 _parse_prompt_to_messages不区分大小写识别前缀连续行归属同一消息空行忽略若整段都没有角色前缀则整体作为一条 user 消息--- model: gpt-4 temperature: 0.3 --- System: You are a helpful coding assistant. User: {{user_question}}动态模型选择——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 与参数提取pre_call_hookbitbucket_prompt_manager.py是理解整个集成的关键流程如下无prompt_id时直接透传原 messages 与参数通过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]中提取参数合并进litellm_params任一环节异常只记录verbose_proxy_logger错误并回退到原始 messages不会让整次 LLM 调用失败——这是一个有意的容错设计。此外_compile_prompt_helper/async_compile_prompt_helperbitbucket_prompt_manager.py把同一套“拉取—渲染—解析—取参”流程封装为PromptManagementClient结构返回供新版PromptManagementBase.get_chat_completion_prompt接口复用异步版本因底层 HTTP 是同步客户端直接委托同步实现。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构造函数会校验workspace、repository、access_token三者缺一不可否则抛ValueError见 bitbucket_client.py。需要指出一个与文档描述不一致的实现细节源码中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 调用参数response litellm.completion( modelbitbucket/base_model, # 必填如 bitbucket/gpt-4 prompt_idstr, # 必填.prompt 文件路径不含扩展名 prompt_variablesdict, # 可选模板渲染变量 bitbucket_configdict, # 可选未设全局配置时传入 messageslist, # 可选附加消息 )安全设计沙箱模板与路径校验提示词文件来自仓库本质上是不可信输入源码中做了两层针对性防护Jinja2 沙箱如前文配置所示环境使用ImmutableSandboxedEnvironment而非普通Environment。源码注释解释得很直白拥有仓库写权限的人可以在.prompt里塞入能触达__class__.__init__.__globals__的 Jinja 语法在普通环境下可演变为代理主机上的 RCE沙箱会阻断这种属性遍历同时保留正常的{{ var }}替换行为。路径安全校验_sanitize_file_pathbitbucket_client.py拒绝包含#、?的路径拒绝出现..的路径穿越并对每个路径段做 URL 编码再拼进src/{branch}/{path}请求。文件内容读取还兼容两种返回形态content-type为text/*时直接取文本否则尝试把响应体按 base64 解码BitBucket 对二进制文件的返回方式解码失败再回退到response.text。HTTP 状态码被映射为可读异常404→ 返回None文件不存在403→ 抛出带 workspace/repository 名的 Access denied 提示401→ Authentication failed. Check your BitBucket access token and permissions.见 bitbucket_client.py。团队级访问控制BitBucket 自带的权限体系直接复用为提示词的访问控制Workspace 级权限控制对整个 workspace 的访问仓库级权限控制对具体提示词仓库的访问分支级权限通过分支保护规则隔离生产提示词用户与群组管理为团队成员分配不同访问级别。落地建议与 README 建议一致按团队划分 workspace/仓库例如team-a-prompts/、team-b-prompts/、team-c-prompts/仓库权限上团队成员给只读、提示词维护者给写权限、生产分支启用保护规则每个团队使用独立的 access tokentoken 按仓库范围授权敏感环境使用 app password 叠加 basic 认证。其他安全要点access token 应通过环境变量或密钥管理系统注入而非硬编码利用 BitBucket 的审计日志追踪仓库访问。错误处理与故障排查常见问题与排查方向现象排查点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捕获异常后只记日志并回退因此“调用成功但模型/参数不对”时应同时检查verbose_proxy_logger输出确认提示词渲染是否真的生效。从文件式 Dotprompt 迁移如果你的团队目前使用 dotprompt 集成litellm/integrations/dotprompt/管理本地.prompt文件迁移到 BitBucket 的路径是把现有.prompt文件上传到 BitBucket 仓库目录结构可保持不变把全局配置从本地路径换成global_bitbucket_configworkspace/repository/access_token/branch用 BitBucket 权限体系配置团队访问代码中把dotprompt/模型前缀改为bitbucket/。由于两者共用同一套PromptManagementBase接口与 Handlebars 风格模板约定迁移主要影响的是提示词的来源与协作方式——获得版本历史、分支保护和团队权限而调用侧代码几乎无需改动。小结LiteLLM 的 BitBucket 集成把提示词管理做成了对调用方近乎透明的前置层bitbucket/model前缀 prompt_idprompt_variables三要素即可完成接入YAML frontmatter 承载模型与参数正文经 Jinja2 沙箱渲染后解析为标准 chat messages。Proxy 场景只需在litellm_settings.global_bitbucket_config中声明一次仓库与凭据。理解 bitbucket_client.py 的路径校验/认证映射与 bitbucket_prompt_manager.py 的 hook 回退语义有助于在私有化部署和故障排查时快速定位问题。【免费下载链接】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创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考