案例目标
Llama API 是一个托管的 Llama 2 API 服务,支持函数调用功能。本案例展示了如何通过 LlamaIndex 集成 Llama API,实现基本的文本补全、对话交互、函数调用和结构化数据提取功能。Llama API 为开发者提供了一个便捷的方式来使用 Llama 2 模型,无需本地部署,可以直接通过 API 调用模型服务,大大简化了使用流程。同时,该 API 支持函数调用功能,使得模型能够与外部工具和服务进行交互,扩展了应用场景。
环境配置
1. 安装依赖
安装必要的依赖包:
pip install llama-index-program-openai
pip install llama-index-llms-llama-api
pip install llama-index
2. 获取 API 密钥
要运行此示例,您需要从 Llama API 官网 获取 API 密钥。
3. 导入库并设置 API 密钥
导入必要的库并设置 API 密钥:
from llama_index.llms.llama_api import LlamaAPI
api_key = "LL-your-key"
llm = LlamaAPI(api_key=api_key)
案例实现
1. 基本用法 - 文本补全
使用 complete 方法进行文本补全:
resp = llm.complete("Paul Graham is ")
print(resp)
输出示例:
Paul Graham is a well-known computer scientist and entrepreneur, best known for his work as a co-founder of Viaweb and later Y Combinator, a successful startup accelerator. He is also a prominent essayist and has written extensively on topics such as entrepreneurship, software development, and the tech industry.
2. 基本用法 - 对话交互
使用 chat 方法进行对话交互:
from llama_index.core.llms import ChatMessage
messages = [
ChatMessage(role="system", content="You are a pirate with a colorful personality"),
ChatMessage(role=, content=),
]
resp = llm.chat(messages)
(resp)


