综述由AI生成提示工程是创建能产生期望结果的提示的过程,涉及一系列技术应用。少样本提示、思维链、生成知识、从最少到最多、自我完善及多维度提示等核心技巧,并通过 Python 代码示例演示了如何优化大语言模型输出。此外,文章还讲解了温度参数对输出确定性的影响以及指定上下文、限制输出、使用模板等最佳实践,旨在帮助开发者提升 AI 交互的稳定性和准确性。
Prompt:"Lisa has 7 apples, throws 1 apple, gives 4 apples to Bart and Bart gives one back: 7 -1 = 6 6 -4 = 2 2 +1 = 3
Alice has 5 apples, throws 3 apples, gives 2 to Bob and Bob gives one back, how many apples does Alice have?"Answer:1
Explain
``` ext
{{company}}: {{company_name}}
{{products}}:
{{products_list}}
Please suggest an insurance given the following budget and requirements:
Budget: {{budget}}
Requirements: {{requirements}}
在上面,您可以看到如何使用模板构建提示。模板中有许多变量,用'{{variable}}'表示,这些变量将替换为公司 API 中的实际值。
以下示例展示了变量被公司内容替换后提示的外观:
Explain```extInsurance company:ACMEInsuranceInsurance products (cost per month):-Car,cheap,500USD-Car,expensive,1100 USD-Home,cheap,600USD-Home,expensive,1200 USD-Life,cheap,100USDPlease suggest an insurance given the following budget and requirements:Budget:$1000Requirements:Car,Home
通过 LLM 运行此提示将产生如下响应:
Explain
``` ext
, and Life insurance
Given the budget and requirements, we suggest the following insurance package from ACME Insurance:
- Car, cheap, 500 USD- Home, cheap, 600 USD- Life, cheap, 100 USD
Total cost: $1,200 USD
Explain```extInsurance company:ACMEInsuranceInsurance products (cost per month):-type:Car,cheap,cost:500USD-type:Car,expensive,cost:1100 USD-type:Home,cheap,cost:600USD-type:Home,expensive,cost:1200 USD-type:Life,cheap,cost:100USDPlease suggest an insurance given the following budget and requirements:Budget:$1000restrict choice to types:Car,Home
请注意添加 type 和 cost 以及使用关键字 restrict 如何帮助 LLM 理解我们想要的内容。
现在我们得到以下响应:
Explain
``` ext
Given the budget and requirements, we suggest the Car, Cheap insurance product which costs 500 USD per month.
Prompt: 'Create a Python Web API with routes products and customers'
AI Answer:
```python
import flask
app = Flask(__name__)
@app.route('/products')defproducts():
return'Products'@app.route('/customers')defcustomers():
return'Customers'
Prompt: suggest 3 improvements of the above code
AI Answer:
Sure, here are three suggestions to improve the code:
Import the correct module: The first line should import Flask instead of flask. The correct import statement should be from flask import Flask.
Add a main function: Add a if __name__ == '__main__': block to the end of the file to run the application when the file is executed.
Use f-strings: Use f-strings to format the return statements in the route functions. For example, return 'Products' can be changed to return f'This is the {request.path} page'.
from flask import Flask, request
app = Flask(__name__)
@app.route('/products')defproducts():
returnf'This is the {request.path} page'@app.route('/customers')defcustomers():
returnf'This is the {request.path} page'if __name__ == '__main__':
app.run()
prompt: How can I create a crisis plan to mitigate for a pandemic in5 steps? LLM answer:
```text1. Identify the risks
1. Identify the stakeholders
1. Identify the resources
1. Identify the actions
1. Identify the communication channels
它确定了 5 个步骤,但是我们可以确定这是否正确吗?让我们请 LLM 解释一下每一步:
prompt: Explain the first step in more detail, what are the risks in detail with a pandemic?
```text
The risks are the following:
- Loss of life- Loss of business- Loss of reputation- Loss of customers- Loss of employees
"Generate code for a Python Web API"
```text
# Import necessary modules
import flask
from flask import request, jsonify
# Create a Flask appapp = flask.Flask(__name__)
# Create a route for the API
@app.route('/api', methods=['GET'])
def api():
# Get the data from the requestdata = request.args
# Process the dataresult = process_data(data)
# Return the result as JSON
return jsonify(result)
# Function to process the data
def process_data(data):
# Do something with the dataresult = data + 1# Return the result
return result
# Run the app
if __name__ == '__main__':
app.run()
再次运行相同的提示会生成略有不同的响应:
#import necessary packagesimport flask
from flask import request, jsonify
#create the Flask application
app = flask.Flask(__name__)
app.config["DEBUG"] = True#create a list of books
books = [
{'id': 0,
'title': 'A Fire Upon the Deep',
'author': 'Vernor Vinge',
'first_sentence': 'The coldsleep itself was dreamless.',
'year_published': '1992'},
{'id': 1,
'title': 'The Ones Who Walk Away From Omelas',
'author': 'Ursula K. Le Guin',
'first_sentence': 'With a clamor of bells that set the swallows soaring, the Festival of Summer came to the city Omelas, bright-towered by the sea.',
'published': '1973'},
{'id': 2,
'title': 'Dhalgren',
'author': 'Samuel R. Delany',
'first_sentence': 'to wound the autumnal city.',
'published': '1975'}
]
#create an endpoint for the API@app.route('/', methods=['GET'])defhome():
return'''<h1>Books API</h1>
<p>A prototype API for retrieving books.</p>'''#create an endpoint to return all books@app.route('/api/v1/resources/books/all', methods=['GET'])defapi_all():
return jsonify(books)
#create an endpoint to return a single book@app.route('/api/v1/resources/books', methods=['GET'])defapi_id():
#check if an ID was provided as part of the URL#if ID is provided, assign it to a variable#if no ID is provided, display an errorif'id'in request.args:
id = int(request.args['id'])
else:
return"Error: No id field provided. Please specify an id."#create an empty list for our results
results = []
#loop through the data and match results that fit the requested ID#IDs are unique, but other fields might return many resultsfor book in books:
if book['id'] == id:
results.append(book)
#use the jsonify function from Flask to convert our list of#Python dictionaries to the JSON formatreturn jsonify(results)
app.run()
"Generate code for a Python Web API"
```python
#import necessary libraries
import flask
from flask import request, jsonify
#create an instance of the Flask classapp = flask.Flask(__name__)
#create an endpoint for the API
@app.route('/api/v1/endpoint', methods=['GET'])
def api_endpoint():
#get the request datadata = request.get_json()
#process the dataresult = process_data(data)
#return the result
return jsonify(result)
#function to process the data
def process_data(data):
#process the dataresult = {'result': 'success'}
#return the result
return result
#run the Flask app
if __name__ == '__main__':
app.run()
再次运行提示符会给我们这样的结果:
#import necessary libraries
import flask
from flask import request, jsonify
#create a Flask appapp = flask.Flask(__name__)
#create a route for the API
@app.route('/api', methods=['GET'])
def api_call():
#get the data from the requestdata = request.get_json()
#process the dataresult = process_data(data)
#return the result
return jsonify(result)
#define the process_data function
def process_data(data):
#do something with the dataresult = data + 1#return the result
return result
#run the app
if __name__ == '__main__':
app.run()
这两个输出之间只有很小的差异。这次我们反其道而行之,将温度设置为 0.9:
# Import necessary libraries
import flask
from flask import request, jsonify
# Create a Flask appapp = flask.Flask(__name__)
# Create a route for the API
@app.route('/api', methods=['GET'])
def api_call():
# Get the data from the requestdata = request.args
# Process the dataresult = process_data(data)
# Return the result
return jsonify(result)
# Function to process the data
def process_data(data):
# Do something with the dataresult = data + 1# Return the result
return result
# Run the app
if __name__ == '__main__':
app.run()
第二次尝试使用 0.9 作为温度值:
import flask
from flask import request, jsonify
# create the Flask app
app = flask.Flask(__name__)
app.config['DEBUG'] = True# create some test data
books = [
{'id': 0, 'title': 'A Fire Upon The Deep', 'author': 'Vernor Vinge', 'first_sentence': 'The coldsleep itself was dreamless.', 'year_published': '1992'},
{'id': 1, 'title': 'The Ones Who Walk Away From Omelas', 'author': 'Ursula K. Le Guin', 'first_sentence': 'With a clamor of bells that set the swallows soaring, the Festival of Summer came to the city Omelas, bright-towered by the sea.', 'published': '1973'},
{'id': 2, 'title': 'Dhalgren', 'author': 'Samuel R. Delany', 'first_sentence': 'to wound the autumnal city.', 'published': '1975'}
]
# create an endpoint@app.route('/', methods=['GET'])defhome():
return'''<h1>Welcome to our book API!</h1>'''@app.route('/api/v1/resources/books', methods=['GET'])defapi_books():
return jsonify(books)
app.run()
正如您所看到的,结果各式各样。
最佳实践
您可以应用许多实践来尝试获得您想要的东西。当您越来越多地使用提示时,你会发现自己的风格。
除了我们介绍的技术之外,在调用 LLMs 时还需要考虑一些好的做法。
以下是一些值得考虑的良好做法:
指定上下文。上下文很重要,您可以指定的领域、主题等越多越好。
限制输出。如果您想要特定数量的项目或特定长度,请指定。
指定内容和方式。请记住提及您想要什么以及您想要如何实现,例如'创建一个包含路由产品和客户的 Python Web API,将其分为 3 个文件'。