首页
/ 生产级 LLM 应用的 Prompt 模板系统实战:从变量插值到多轮状态机

生产级 LLM 应用的 Prompt 模板系统实战:从变量插值到多轮状态机

2026-09-09 15:06:19作者:郦嵘贵Just

导读

本文系统讲解 LLM 应用开发中最容易被低估却至关重要的基础设施——Prompt 模板系统(Prompt Template Systems)。内容源自 llm-application-dev 插件中 prompt-engineering-patterns 技能的 prompt-templates.md 参考文档,并结合仓库中的 SKILL.mdprompt-template-library.mdfew-shot-examples.jsonoptimize-prompt.py 源码进行纵深佐证。读完本文,你将掌握从"手写字符串拼接"升级为"可复用、可校验、可缓存、可继承"的工程化模板体系所需的全部核心模式:基础渲染、条件块与循环、模块化组合、模板继承、变量校验、缓存、多轮对话模板与状态机模板,并能直接复制落地到自己的 RAG、分类、抽取、生成等生产场景中。

一、为什么需要模板系统:模板即代码

在生产级 LLM 应用中,Prompt 不再是"一次性输入",而是需要被反复渲染、回归测试、版本管理的资产。技能文档在 SKILL.md 中将其归纳为六大核心能力之一,并给出明确的使用场景:

  • 为生产 LLM 应用设计复杂提示词;
  • 创建带变量插值的可复用 Prompt 模板;
  • 实现基于角色的 Prompt 组合与模块化组件;
  • 构建多轮对话模板;
  • 调试输出不一致的 Prompt。

模板系统的核心价值在于把「结构」与「数据」分离:模板承载任务指令、格式要求与示例,变量承载每次调用不同的输入。SKILL.md 的 Best Practices 中专门强调两条与模板直接相关的原则:"Hardcoded values(硬编码值)是不参数化 Prompt 复用"的常见陷阱,以及 "Version Control:把 Prompt 当作代码来版本管理"。这意味着模板字符串应当像源代码一样入库、评审、diff。

仓库配套的 few-shot-examples.json 就是"模板与数据分离"的典型实践:其中 sentiment_analysis、entity_extraction、text_classification 等任务的示例数据全部以结构化 JSON 存储,运行时才被注入模板,而非写死在模板字符串里。

二、模板架构:三个递进层次

参考文档将模板架构分为基础模板、条件模板、模块化模板三个递进层次,以下完整继承并逐一展开。

2.1 基础模板结构:最小可用的渲染器

最朴素的 PromptTemplate 做三件事:声明变量、渲染前校验、执行格式化:

class PromptTemplate:
    def __init__(self, template_string, variables=None):
        self.template = template_string
        self.variables = variables or []

    def render(self, **kwargs):
        missing = set(self.variables) - set(kwargs.keys())
        if missing:
            raise ValueError(f"Missing required variables: {missing}")

        return self.template.format(**kwargs)

# Usage
template = PromptTemplate(
    template_string="Translate {text} from {source_lang} to {target_lang}",
    variables=['text', 'source_lang', 'target_lang']
)

prompt = template.render(
    text="Hello world",
    source_lang="English",
    target_lang="Spanish"
)

这段实现的三个细节值得注意:

  1. 缺失变量提前失败(Fail Fast)render 在真正拼字符串之前就检查 variables 与传入 kwargs 的差集,缺变量直接抛 ValueError。这正是 SKILL.md 最佳实践中 "Validate Early: Check variables before rendering" 的落地——把错误暴露在渲染前,而不是让模型拿到残缺指令后输出幻觉内容。
  2. 底层依赖 str.format:模板用 {name} 占位符,天然与 Python 生态的格式化语义一致。
  3. 声明式变量清单variables 参数让模板自描述,便于文档化与静态检查。

2.2 条件模板:用 {{#if}}{{#each}} 控制 Prompt 结构

真实场景中,同一任务的不同输入需要不同结构的 Prompt——例如只有用户显式要求情感分析时才追加"提供情感分析"指令。参考文档用子类 ConditionalTemplate 实现了一个轻量级模板引擎,支持两种块语法:

  • {{#if variable}}content{{/if}}:变量为真时保留块内容,否则删除;
  • {{#each items}}{{this}}{{/each}}:遍历列表变量,将 {{this}} 替换为每个元素。
class ConditionalTemplate(PromptTemplate):
    def render(self, **kwargs):
        # Process conditional blocks
        result = self.template

        # Handle if-blocks: {{#if variable}}content{{/if}}
        import re
        if_pattern = r'\{\{#if (\w+)\}\}(.*?)\{\{/if\}\}'

        def replace_if(match):
            var_name = match.group(1)
            content = match.group(2)
            return content if kwargs.get(var_name) else ''

        result = re.sub(if_pattern, replace_if, result, flags=re.DOTALL)

        # Handle for-loops: {{#each items}}{{this}}{{/each}}
        each_pattern = r'\{\{#each (\w+)\}\}(.*?)\{\{/each\}\}'

        def replace_each(match):
            var_name = match.group(1)
            content = match.group(2)
            items = kwargs.get(var_name, [])
            return '\\n'.join(content.replace('{{this}}', str(item)) for item in items)

        result = re.sub(each_pattern, replace_each, result, flags=re.DOTALL)

        # Finally, render remaining variables
        return result.format(**kwargs)

实现要点:

  • re.DOTALL 标志让 . 匹配换行,条件块可以跨多行书写;
  • 处理顺序是先 ifeach 最后 format,避免嵌套块与占位符互相干扰;
  • 每个 each 块以换行符 \n 连接,天然生成列表格式。

典型用法——一段"分析文本"的复合模板,按需注入情感分析、实体抽取与参考示例三个可选区块:

template = ConditionalTemplate("""
Analyze the following text:
{text}

{{#if include_sentiment}}
Provide sentiment analysis.
{{/if}}

{{#if include_entities}}
Extract named entities.
{{/if}}

{{#if examples}}
Reference examples:
{{#each examples}}
- {{this}}
{{/each}}
{{/if}}
""")

这种"按变量开关折叠区块"的能力,是控制 Token 消耗、保持 Prompt 聚焦的关键手段——对应 SKILL.md Common Pitfalls 中 "Context overflow: Exceeding token limits with excessive examples" 的规避策略。

2.3 模块化模板组合:以组件复用替代整体复制

当不同场景需要不同 Prompt 结构时,最怕"复制粘贴再改两行"。参考文档给出的 ModularTemplate 把 Prompt 拆成 system / context / instruction / examples / input / format 等可注册组件,用"结构清单"声明组合顺序:

class ModularTemplate:
    def __init__(self):
        self.components = {}

    def register_component(self, name, template):
        self.components[name] = template

    def render(self, structure, **kwargs):
        parts = []
        for component_name in structure:
            if component_name in self.components:
                component = self.components[component_name]
                parts.append(component.format(**kwargs))

        return '\n\n'.join(parts)

# Usage
builder = ModularTemplate()

builder.register_component('system', "You are a {role}.")
builder.register_component('context', "Context: {context}")
builder.register_component('instruction', "Task: {task}")
builder.register_component('examples', "Examples:\n{examples}")
builder.register_component('input', "Input: {input}")
builder.register_component('format', "Output format: {format}")

# Compose different templates for different scenarios
basic_prompt = builder.render(
    ['system', 'instruction', 'input'],
    role='helpful assistant',
    instruction='Summarize the text',
    input='...'
)

advanced_prompt = builder.render(
    ['system', 'context', 'examples', 'instruction', 'input', 'format'],
    role='expert analyst',
    context='Financial analysis',
    examples='...',
    instruction='Analyze sentiment',
    input='...',
    format='JSON'
)

这一设计对应 SKILL.md 核心能力中 "Role-based prompt composition" 与 "Modular prompt components"。与仓库中 system-prompts.md 给出的系统提示词结构公式 [Role Definition] + [Expertise Areas] + [Behavioral Guidelines] + [Output Format] + [Constraints] 完全同构——模块化渲染器就是该公式的可执行实现,后续接入 LangChain 生态时,ChatPromptTemplate.from_messages([...]) 也遵循同样的分段思想(见 SKILL.md Quick Start 示例)。

三、四类通用模板模式:分类 / 抽取 / 生成 / 变换

参考文档归纳了 LLM 任务四大基元,并给出带条件块的标准模板骨架,完整继承如下。

3.1 分类模板(Classification Template)

CLASSIFICATION_TEMPLATE = """
Classify the following {content_type} into one of these categories: {categories}

{{#if description}}
Category descriptions:
{description}
{{/if}}

{{#if examples}}
Examples:
{examples}
{{/if}}

{content_type}: {input}

Category:"""

末尾以 Category: 结尾,利用"补全式"(completion-style)提示引导模型直接输出标签。仓库 prompt-template-library.md 中的 Sentiment Analysis、Intent Detection、Topic Classification 模板(如 Text: {text}\n\nSentiment:)就是该骨架的具体实例。

3.2 抽取模板(Extraction Template)

EXTRACTION_TEMPLATE = """
Extract structured information from the {content_type}.

Required fields:
{field_definitions}

{{#if examples}}
Example extraction:
{examples}
{{/if}}

{content_type}: {input}

Extracted information (JSON):"""

关键技巧是用 Extracted information (JSON): 声明输出协议,让模型以 JSON 结构作答,便于程序解析。这与技能在"Structured Outputs"上的整体取向一致:SKILL.md 明确推荐 "JSON mode for reliable parsing" 与 "Pydantic schema enforcement",而 details.md 中的 Pattern 1 展示了配合 Pydantic 模型(Literal 枚举、Field(ge=0, le=1) 约束)做结构化校验的完整链路。同时,few-shot-examples.json 中的 entity_extraction 示例正是"输入文本 → 输出 {"persons": [...], "organizations": [...]}"的 JSON 抽取范式。

3.3 生成模板(Generation Template)

GENERATION_TEMPLATE = """
Generate {output_type} based on the following {input_type}.

Requirements:
{requirements}

{{#if style}}
Style: {style}
{{/if}}

{{#if constraints}}
Constraints:
{constraints}
{{/if}}

{{#if examples}}
Examples:
{examples}
{{/if}}

{input_type}: {input}

{output_type}:"""

生成类任务的可变项最多(风格、约束、示例都是可选项),因此条件块在这里价值最大。仓库模板库中的 Email Generation、Code Generation、Creative Writing 模板均可视为该骨架的参数化实例,例如代码生成模板固定注入 "Error handling / Input validation / Inline comments" 三条硬性要求,来约束模型输出质量。

3.4 变换模板(Transformation Template)

TRANSFORMATION_TEMPLATE = """
Transform the input {source_format} to {target_format}.

Transformation rules:
{rules}

{{#if examples}}
Example transformations:
{examples}
{{/if}}

Input {source_format}:
{input}

Output {target_format}:"""

适用于格式转换、翻译、摘要等"输入输出一一映射"任务。模板库中的 Summarization、Translation with Context、Format Conversion 模板是它的直接落地形态,例如 Translate the following {source_lang} text to {target_lang} 通过 ContextTone 两个附加变量实现"带上下文与语气的翻译"。

四、高级特性:继承、校验与缓存

4.1 模板继承:用 Registry 复用基模板

面向对象中的继承思想同样适用于 Prompt。参考文档的 TemplateRegistry 支持以 parent 声明继承关系,子模板通过字典合并覆盖父模板的同名区块:

class TemplateRegistry:
    def __init__(self):
        self.templates = {}

    def register(self, name, template, parent=None):
        if parent and parent in self.templates:
            # Inherit from parent
            base = self.templates[parent]
            template = self.merge_templates(base, template)

        self.templates[name] = template

    def merge_templates(self, parent, child):
        # Child overwrites parent sections
        return {**parent, **child}

# Usage
registry = TemplateRegistry()

registry.register('base_analysis', {
    'system': 'You are an expert analyst.',
    'format': 'Provide analysis in structured format.'
})

registry.register('sentiment_analysis', {
    'instruction': 'Analyze sentiment',
    'format': 'Provide sentiment score from -1 to 1.'
}, parent='base_analysis')

sentiment_analysis 继承自 base_analysissystem 区块沿用父级,format 区块被子级覆盖。注意合并语义是浅层字典合并{**parent, **child}),适用于"区块级"覆盖;若需嵌套覆盖,则需要按区块递归合并。这种模式与 system-prompts.md 中"同一角色不同约束变体"的管理诉求高度契合——base 角色定义只维护一份,变体只声明差异。

4.2 变量校验:类型、范围与枚举约束

模板是给模型看的,但变量是给程序传的——程序侧的错误应当由程序侧拦截。ValidatedTemplate 用 schema 描述每个变量的约束:

class ValidatedTemplate:
    def __init__(self, template, schema):
        self.template = template
        self.schema = schema

    def validate_vars(self, **kwargs):
        for var_name, var_schema in self.schema.items():
            if var_name in kwargs:
                value = kwargs[var_name]

                # Type validation
                if 'type' in var_schema:
                    expected_type = var_schema['type']
                    if not isinstance(value, expected_type):
                        raise TypeError(f"{var_name} must be {expected_type}")

                # Range validation
                if 'min' in var_schema and value < var_schema['min']:
                    raise ValueError(f"{var_name} must be >= {var_schema['min']}")

                if 'max' in var_schema and value > var_schema['max']:
                    raise ValueError(f"{var_name} must be <= {var_schema['max']}")

                # Enum validation
                if 'choices' in var_schema and value not in var_schema['choices']:
                    raise ValueError(f"{var_name} must be one of {var_schema['choices']}")

    def render(self, **kwargs):
        self.validate_vars(**kwargs)
        return self.template.format(**kwargs)

# Usage
template = ValidatedTemplate(
    template="Summarize in {length} words with {tone} tone",
    schema={
        'length': {'type': int, 'min': 10, 'max': 500},
        'tone': {'type': str, 'choices': ['formal', 'casual', 'technical']}
    }
)

这套"声明式 schema + 渲染前校验"的思路,与 SKILL.md 推荐的 Pydantic schema enforcement 一脉相承;在模型输出侧,details.md 的 Pattern 1(SentimentAnalysis Pydantic 模型)与 Pattern 5(ResponseWithConfidence 模型 + ValidationError 捕获回退)则把同样的思想应用到模型输出解析上。输入侧与输出侧双校验,共同构成结构化 LLM 应用的可靠性底座。

4.3 模板缓存:静态模板渲染结果的复用

LLM 调用成本与延迟主要由 Token 决定,Prompt 渲染本身虽便宜,但在高吞吐场景下仍值得缓存。CachedTemplate 以 kwargs 的 frozenset 哈希作为缓存键:

class CachedTemplate:
    def __init__(self, template):
        self.template = template
        self.cache = {}

    def render(self, use_cache=True, **kwargs):
        if use_cache:
            cache_key = self.get_cache_key(kwargs)
            if cache_key in self.cache:
                return self.cache[cache_key]

        result = self.template.format(**kwargs)

        if use_cache:
            self.cache[cache_key] = result

        return result

    def get_cache_key(self, kwargs):
        return hash(frozenset(kwargs.items()))

    def clear_cache(self):
        self.cache = {}

使用注意事项:

  • 缓存键基于 kwargs.items() 的不可变 frozenset,因此变量值必须是可哈希的(str、int、tuple 等),传 list/dict 会抛 TypeError;
  • 文档 Best Practices 第 8 条明确告诫 "Cache Wisely: Cache static templates, not dynamic ones"——只缓存变量稳定、可复用的模板,不要缓存内容频繁变化的动态 Prompt;
  • clear_cache() 用于长驻服务中定期失效。

这一思想在 details.md 的 Performance Optimization 一节得到呼应:对于反复使用的超长系统提示词,可借助 Anthropic 客户端的 cache_control: {"type": "ephemeral"}服务端做 prompt caching,客户端与渲染层缓存互补。

五、多轮模板:对话历史与状态机

单轮 Prompt 模板解决"一次问答",生产级助手还需要处理多轮对话与多步骤工作流。参考文档给出两类模板。

5.1 对话模板:维护 messages 历史

ConversationTemplate 把系统提示词与历史消息统一管理,并提供两种渲染出口:

class ConversationTemplate:
    def __init__(self, system_prompt):
        self.system_prompt = system_prompt
        self.history = []

    def add_user_message(self, message):
        self.history.append({'role': 'user', 'content': message})

    def add_assistant_message(self, message):
        self.history.append({'role': 'assistant', 'content': message})

    def render_for_api(self):
        messages = [{'role': 'system', 'content': self.system_prompt}]
        messages.extend(self.history)
        return messages

    def render_as_text(self):
        result = f"System: {self.system_prompt}\n\n"
        for msg in self.history:
            role = msg['role'].capitalize()
            result += f"{role}: {msg['content']}\n\n"
        return result
  • render_for_api() 输出 [{"role": "system"}, {"role": "user"}, ...] 结构,可直接作为 Anthropic / OpenAI 等 Chat API 的 messages 参数——这也正是 SKILL.md Quick Start 中 ChatPromptTemplate.from_messages([("system", ...), ("user", ...)]) 所代表的 LangChain 等价物;
  • render_as_text() 则把历史扁平化为 System:/User:/Assistant: 纯文本,适配补全式模型或需要整段文本注入的场景;
  • 模板库中的 Multi-Turn Q&A 模板(Previous conversation: {conversation_history}\n\nNew question: {question})正是文本渲染路径的实例化。

5.2 状态机模板:多步骤工作流的"当前步骤即模板"

复杂交互(多步表单、引导式流程)需要根据当前状态切换提示内容。StatefulTemplatecurrent_state 选择模板:

class StatefulTemplate:
    def __init__(self):
        self.state = {}
        self.templates = {}

    def set_state(self, **kwargs):
        self.state.update(kwargs)

    def register_state_template(self, state_name, template):
        self.templates[state_name] = template

    def render(self):
        current_state = self.state.get('current_state', 'default')
        template = self.templates.get(current_state)

        if not template:
            raise ValueError(f"No template for state: {current_state}")

        return template.format(**self.state)

# Usage for multi-step workflows
workflow = StatefulTemplate()

workflow.register_state_template('init', """
Welcome! Let's {task}.
What is your {first_input}?
""")

workflow.register_state_template('processing', """
Thanks! Processing {first_input}.
Now, what is your {second_input}?
""")

workflow.register_state_template('complete', """
Great! Based on:
- {first_input}
- {second_input}

Here's the result: {result}
""")

状态变量 current_state 驱动模板切换,所有工作流数据统一放在 state 字典中按名引用。注意 render() 对未注册状态抛 ValueError,与基础模板的缺失变量校验形成一致的"fail fast"策略。从仓库技能体系看,这种"分步骤、按状态推进"的提示编排,为多步 Agent 工作流(如 SKILL.md 中提及的 chain-of-thought 逐步推理、details.md 中 Pattern 4 的渐进式揭示 PROMPT_LEVELS 分级)提供了模板层的支撑。

六、模板库速查:拿来即用的开箱模板

参考文档附带了 QA 与内容生成两大模板库,完整继承如下,变量名即占位符,填入即可运行。

6.1 问答模板库(QA_TEMPLATES)

QA_TEMPLATES = {
    'factual': """Answer the question based on the context.

Context: {context}
Question: {question}
Answer:""",

    'multi_hop': """Answer the question by reasoning across multiple facts.

Facts: {facts}
Question: {question}

Reasoning:""",

    'conversational': """Continue the conversation naturally.

Previous conversation:
{history}

User: {question}
Assistant:"""
}

三个变体覆盖三种问答范式:factual 面向基于上下文的单跳问答(即 RAG 问答,模板库中的 RAG Template 与之同构);multi_hop 显式声明 "Reasoning:" 引导跨事实推理,契合 few-shot-learning.md 中对复杂推理任务采用逐步示例的建议;conversational 面向多轮续接。仓库 few-shot-examples.json 的 question_answering 区块提供了可直接注入 {context}/{question} 的真实问答样本对。

6.2 内容生成模板库(GENERATION_TEMPLATES)

GENERATION_TEMPLATES = {
    'blog_post': """Write a blog post about {topic}.

Requirements:
- Length: {word_count} words
- Tone: {tone}
- Include: {key_points}

Blog post:""",

    'product_description': """Write a product description for {product}.

Features: {features}
Benefits: {benefits}
Target audience: {audience}

Description:""",

    'email': """Write a {type} email.

To: {recipient}
Context: {context}
Key points: {key_points}

Email:"""
}

可见通用模式:需求显式列出(Requirements / Features / Key points)+ 输出锚点("Blog post:" / "Email:")。输出锚点让模型从"补全"而非"自由创作"的角度续写,显著提升格式一致性。模板库中的 Email Generation 模板(要求输出 Subject:Body: 两段)即 email 变体的强化版。

此外,prompt-template-library.md 还提供了分析类(Code Review、SWOT)与专业类(SQL 生成、正则创建、API 文档)模板,例如 SQL 生成模板显式注入 Database schema,正则模板同时给出"应匹配/不应匹配"两组测试用例——这些都可以视为四类基元模板的行业化延伸。

七、性能考量与最佳实践

7.1 性能要点

参考文档给出五条渲染层性能准则,与仓库源码相互印证:

  1. 预编译模板重复使用:避免每次调用重新解析模板字符串;
  2. 变量静态时缓存渲染结果:对应 CachedTemplate 的适用前提;
  3. 循环内减少字符串拼接ConditionalTemplateeach 块采用 '\n'.join(...) 而非循环 +=,正是这一原则的实现;
  4. 使用高效格式化(f-string / .format()):全库模板统一使用 .format()
  5. 对渲染做性能剖析:找出热点再优化。

details.md 中还有一条易被忽略的 Token 效率对比:一段 150+ token 的冗长指令("I would like you to please take the following text and provide me with a comprehensive summary...")可压缩为约 30 token 的 Summarize the key points concisely: ... Summary:。模板在固定表达上的精简,直接影响每次调用的成本与延迟。

7.2 八大最佳实践

参考文档给出的模板工程化清单,完整继承如下:

  1. Keep It DRY:用模板避免重复,同一指令只维护一份;
  2. Validate Early:渲染前检查变量(对应 PromptTemplate 缺失变量校验与 ValidatedTemplate schema 校验);
  3. Version Templates:像跟踪代码一样跟踪模板变更(对应 SKILL.md "Treat prompts as code with proper versioning");
  4. Test Variations:用多样化输入回归测试模板,确保鲁棒性;
  5. Document Variables:明确标注必填/可选变量;
  6. Use Type Hints:变量类型显式化(对应 schema 的 type 校验);
  7. Provide Defaults:合理设置默认值(对应条件块的缺省折叠行为);
  8. Cache Wisely:只缓存静态模板,不缓存动态模板。

7.3 与 Prompt 优化的闭环

模板不是终点,需要持续迭代。仓库 optimize-prompt.pyPromptOptimizer 演示了如何用测试套件评估模板变体:它对每个模板用 prompt_template.format(**test_case.input) 渲染(说明模板 API 与该脚本兼容),并行跑测试用例,聚合 avg_accuracy / avg_latency / p95_latency / avg_tokens / success_rate 五项指标,再通过 generate_variations(追加格式指令、追加 "Let's solve this step by step"、追加校验步骤、精简措辞、补充示例)生成最多 3 个变体进行 A/B 比较,直至精度达标或无可改进变体。这为第 4 条最佳实践"Test Variations"提供了可运行的自动化实现。

八、落地建议:把模板系统接入生产 LLM 应用

综合参考文档与仓库技能体系,落地一套生产级模板系统的最小路径如下:

  1. 从四类基元模板起步:先按分类/抽取/生成/变换骨架建模任务,用 PromptTemplate 保证变量校验;
  2. 需要条件结构时升级:接入 {{#if}} / {{#each}},用开关变量折叠可选区块,控制 Token 消耗;
  3. 多场景复用用模块化组合:注册 system/context/examples 等组件,用结构清单声明组合顺序;
  4. 多轮与多步骤用对话/状态机模板render_for_api() 直接对接 Chat API,StatefulTemplate 管理引导式流程;
  5. 配齐校验与缓存ValidatedTemplate 拦截错误输入,CachedTemplate 复用静态渲染结果;
  6. 纳入测试与版本管理:用 optimize-prompt.py 的评估管线做回归与 A/B,把模板字符串作为代码入库;
  7. 与技能其他部分协同:模板负责"结构",few-shot 负责"示例"(见 few-shot-examples.jsonfew-shot-learning.md),chain-of-thought 与 system prompt 设计(见 system-prompts.md)负责"推理与角色"——四者组合才构成完整的生产级提示工程体系。

模板系统是"提示工程工程化"的根基:它让 Prompt 从一次性文本变为可组合、可校验、可缓存、可测试的代码资产。参考文档中所有代码均为可直接运行的 Python 实现,配合仓库内的模板库与示例数据,即可无缝迁移到你自己的 LLM 应用项目中。

登录后查看全文
热门项目推荐
相关项目推荐

项目优选

收起
kernelkernel
deepin linux kernel
C
33
18
ops-transformerops-transformer
本项目是CANN提供的transformer类大模型算子库,实现网络在NPU上加速计算。
C++
1.14 K
2.76 K
pytorchpytorch
作为 Ascend for PyTorch 社区的核心组件,TorchNPU 是昇腾专为 PyTorch 打造的深度学习适配插件,使 PyTorch 框架能够直接调用昇腾 NPU,为开发者提供昇腾 AI 处理器的超强算力。
Python
860
1.35 K
docsdocs
暂无描述
Markdown
899
5.83 K
ops-nnops-nn
本项目是CANN提供的神经网络类计算算子库,实现网络在NPU上加速计算。
C++
925
1.85 K
jiuwenswarmjiuwenswarm
JiuwenSwarm 是一款基于openJiuwen开发的智能AI Agent,它能够将大语言模型的强大能力,通过你日常使用的各类通讯应用,直接延伸至你的指尖。
Python
3.84 K
1.02 K
kernelkernel
openEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。
C
533
601
cann-learning-hubcann-learning-hub
CANN 学习中心仓,支持在线互动运行、边学边练,提供教程、示例与优化方案,一站式助力昇腾开发者快速上手。
Jupyter Notebook
1.03 K
525
ops-mathops-math
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
1.37 K
1.46 K
AscendNPU-IRAscendNPU-IR
AscendNPU-IR是基于MLIR(Multi-Level Intermediate Representation)构建的,面向昇腾亲和算子编译时使用的中间表示,提供昇腾完备表达能力,通过编译优化提升昇腾AI处理器计算效率,支持通过生态框架使能昇腾AI处理器与深度调优
C++
548
395