示例#

Kork 允许在提示中提供示例。

  1. 示例帮助 LLM 理解语言的语法

  2. 示例可以根据用户查询动态生成,以呈现最相关的程序。

示例的格式是 2 元组序列,形式为:(str, Program)。

让我们看看如何指定它们。

最简单的方式#

from kork.parser import parse
examples_as_strings = [
    (
        "declare a variable called `y` and assign to it the value 8",
        "var y = 8",
    )
]
examples = [(query, parse(code)) for query, code in examples_as_strings]
examples
[('declare a variable called `y` and assign to it the value 8',
  Program(stmts=(VarDecl(name='y', value=Literal(value=8)),)))]

最困难的方式#

让我们导入 AST 元素,并编写一个示例查询和一个对应的简短程序。

from kork.ast import Program, VarDecl, Literal
examples = [
    (
        "declare a variable called `y` and assign to it the value 8",
        Program(stmts=[VarDecl("y", Literal(value=8))]),
    )
]

格式化示例#

该链使用 AstPrinter 格式化示例,将示例格式化为 2 元组序列,形式为 (str, str)。

以下是发生的情况

from kork.examples import format_examples
from kork import AstPrinter
print(format_examples("SmirkingCat", examples, AstPrinter()))
[('declare a variable called `y` and assign to it the value 8', '```SmirkingCat\nvar y = 8\n```')]
print(
    format_examples(
        "SmirkingCat", examples, AstPrinter(), input_formatter="text_prefix"
    )
)
[('Text: """\ndeclare a variable called `y` and assign to it the value 8\n"""', '```SmirkingCat\nvar y = 8\n```')]

让最困难的方式变得更简单#

有一些实用函数可以更轻松地生成调用外部函数的程序——这预计会是一种常见的模式。

from kork import c_, r_
?c_
Signature: c_(name: Callable, *args: Any) -> kork.ast.FunctionCall
Docstring: Create a kork function call.
File:      ~/src/kork/kork/examples.py
Type:      function
?r_
Signature: r_(expr: kork.ast.Expr) -> kork.ast.Program
Docstring: Assign last program expression to a result variable.
File:      ~/src/kork/kork/examples.py
Type:      function
import math
import operator

这是一个调用外部函数 log10,参数为 2 的小程序。

c_(math.log10, 2)
FunctionCall(name='log10', args=[Literal(value=2)])

一个调用 log10,参数为 2,并将结果存储在全局命名空间中的 result 变量中的程序。

r_(c_(math.log10, 2))
Program(stmts=[VarDecl(name='result', value=FunctionCall(name='log10', args=[Literal(value=2)]))])
program = r_(c_(operator.add, 2, c_(math.log10, 3)))
print(AstPrinter().visit(program))
var result = add(2, log10(3))
examples = [("take the log base 10 of 3 and add 2 to the result.", program)]