生成式AI应用与FMOps实践
立即解锁
发布时间: 2025-09-03 00:28:29 阅读量: 5 订阅数: 13 AIGC 


生成式AI实战:从理论到应用
# 生成式AI应用与FMOps实践
## 1. 程序辅助语言框架(PAL)
在处理复杂计算时,基础模型可能存在局限性。为克服这一问题,可以将模型连接到擅长执行计算的应用程序,如代码解释器,程序辅助语言模型(PAL)框架就是这样做的。
### 1.1 PAL工作原理
PAL使用思维链(CoT)推理在中间推理步骤中生成程序,以帮助解决给定问题。这些程序随后被传递给解释器(如Python解释器),解释器运行代码并将结果返回给基础模型。具体步骤如下:
1. 添加示例到提示中,每个示例以问题开头,接着是推理步骤和解决问题的Python代码行。
2. 将新问题添加到提示中,形成PAL格式的提示。
3. 将提示传递给基础模型,模型会按照示例生成Python脚本。
4. 将脚本发送到Python解释器运行,返回结果。
5. 将结果追加到提示中,大语言模型(LLM)生成包含正确答案的完成内容。
### 1.2 PAL示例
以下是一个PAL提示模板示例:
```plaintext
Translate a math problem into an expression that can be executed using Python's numexpr library.
Use the output of running this code to answer the question.
Question: ${{Question with hard calculation}}
${{Code that prints what you need to know}}
Question: I have four bananas and buy three more, how many bananas do I have?
def solution():
initial_bananas = 4
extra_bananas = 2
return initial_bananas + extra_bananas
Question: {question}
```
可以向模型提出类似的数学问题,模型会遵循提供的示例进行解答。例如:
```plaintext
Prompt:
Antje has five times the number of books than Chris. Chris has 3 books. How many books does Antje have?
Completion:
def solution():
books_chris = 3
books_antje = 5 * books_chris
return books_antje
```
### 1.3 PAL的优势
对于简单的数学运算,使用CoT推理可能就能得到正确答案。但对于更复杂的数学问题,如大数运算、三角学或微积分,PAL是一种强大的技术,可确保基础模型进行的任何计算准确可靠。
### 1.4 使用ReAct和PAL与LangChain Agents
以下代码示例展示了如何使用ReAct和PAL与LangChain Agents,包括serpapi(可执行Google搜索等多种操作):
```python
from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from transformers import AutoTokenizer, AutoModelForCausalLM
from transformers import pipeline
from langchain.llms import HuggingFacePipeline
model_checkpoint = "..." # generative model like Llama2, Falcon
tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)
model = AutoModelForCausalLM.from_pretrained(model_checkpoint)
pipeline = pipeline(
"text-generation",
model=model,
tokenizer=tokenizer
)
llm = HuggingFacePipeline(pipeline=pipeline)
tools = load_tools(["serpapi", "llm-math"], llm=llm)
agent = initialize_agent(tools,
llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
agent.run("""
Which hotel is closest to the most
popular beach in Hawaii, and how much
is each night with 50% discount?
""")
```
输出结果类似如下:
```plaintext
> Entering new AgentExecu
```
0
0
复制全文
相关推荐









