【Model】【llm38】Llama API - 示例

【Model】【llm38】Llama API - 示例

案例目标

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="user", content="What is your name"), ] resp = llm.chat(messages) print(resp)

输出示例:

assistant: Arrrr, me hearty! Me name be Captain Blackbeak, the scurviest dog on the seven seas! Yer lookin' fer a swashbucklin' adventure, eh? Well, hoist the sails and set course fer the high seas, matey! I be here to help ye find yer treasure and battle any scurvy dogs who dare cross our path! So, what be yer first question, landlubber?

3. 函数调用

使用函数调用功能,定义一个Song模型:

from pydantic import BaseModel from llama_index.core.llms.openai_utils import to_openai_function class Song(BaseModel): """A song with name and artist""" name: str artist: str song_fn = to_openai_function(Song)
使用函数调用生成歌曲信息
llm = LlamaAPI(api_key=api_key) response = llm.complete("Generate a song", functions=[song_fn]) function_call = response.additional_kwargs["function_call"] print(function_call)

输出示例:

{'name': 'Song', 'arguments': {'name': 'Happy', 'artist': 'Pharrell Williams'}}

4. 结构化数据提取

定义Album和Song模型,用于结构化数据提取:

from pydantic import BaseModel from typing import List class Song(BaseModel): """Data model for a song.""" title: str length_mins: int class Album(BaseModel): """Data model for an album.""" name: str artist: str songs: List[Song]
创建Pydantic程序
from llama_index.program.openai import OpenAIPydanticProgram"\ Extract album and songs from the text provided. For each song, make sure to specify the title and the length_mins. {text} """ llm = LlamaAPI(api_key=api_key, temperature=0.0) program = OpenAIPydanticProgram.from_defaults( output_cls=Album, llm=llm, prompt_template_str=prompt_template_str, verbose=True, )
运行程序提取结构化数据
output = program(" "Echoes of Eternity" is a compelling and thought-provoking album, skillfully crafted by the renowned artist, Seraphina Rivers. \ This captivating musical collection takes listeners on an introspective journey, delving into the depths of the human experience \ and the vastness of the universe. With her mesmerizing vocals and poignant songwriting, Seraphina Rivers infuses each track with \ raw emotion and a sense of cosmic wonder. The album features several standout songs, including the hauntingly beautiful "Stardust \ Serenade," a celestial ballad that lasts for six minutes, carrying listeners through a celestial dreamscape. "Eclipse of the Soul" \ captivates with its enchanting melodies and spans over eight minutes, inviting introspection and contemplation. Another gem, "Infinity \ Embrace," unfolds like a cosmic odyssey, lasting nearly ten minutes, drawing listeners deeper into its ethereal atmosphere. "Echoes of Eternity" \ is a masterful testament to Seraphina Rivers' artistic prowess, leaving an enduring impact on all who embark on this musical voyage through \ time and space. """ )

输出示例:

Function call: Album with args: {'name': 'Echoes of Eternity', 'artist': 'Seraphina Rivers', 'songs': [{'title': 'Stardust Serenade', 'length_mins': 6}, {'title': 'Eclipse of the Soul', 'length_mins': 8}, {'title': 'Infinity Embrace', 'length_mins': 10}]}
查看结构化输出
output

输出示例:

Album(name='Echoes of Eternity', artist='Seraphina Rivers', songs=[Song(title='Stardust Serenade', length_mins=6), Song(title='Eclipse of the Soul', length_mins=8), Song(title='Infinity Embrace', length_mins=10)])

案例效果

本案例展示了Llama API的多种功能和应用场景:

  • 基本文本补全:能够完成简单的文本补全任务,如介绍Paul Graham
  • 对话交互:支持多轮对话,能够根据系统提示和用户消息生成符合角色的回应
  • 函数调用:支持函数调用功能,能够根据输入生成结构化的函数调用参数
  • 结构化数据提取:能够从非结构化文本中提取结构化信息,如从专辑描述中提取专辑名、艺术家和歌曲列表
  • OpenAI兼容性:与OpenAI API兼容,可以使用OpenAI的工具和库进行集成

案例实现思路

本案例的实现基于以下思路:

  1. API集成:通过LlamaIndex的LlamaAPI类封装Llama API服务,提供统一的接口
  2. 基本交互:实现complete和chat两种基本交互方式,满足不同场景需求
  3. 函数调用:利用OpenAI兼容的函数调用功能,实现模型与外部工具的交互
  4. 结构化数据提取:通过Pydantic模型定义数据结构,使用OpenAIPydanticProgram提取结构化信息
  5. 模型定义:使用Pydantic定义数据模型,确保输出的结构化和类型安全
  6. 提示工程:设计合适的提示模板,引导模型生成符合要求的输出

扩展建议

  • 更多函数调用:定义更多复杂的函数,实现更丰富的交互功能
  • 多模态支持:如果API支持,可以扩展到多模态数据处理
  • 错误处理:添加完善的错误处理机制,提高应用稳定性
  • 缓存机制:实现响应缓存,减少重复请求,提高效率
  • 流式响应:如果API支持,实现流式响应功能
  • 性能监控:监控API调用的响应时间和资源消耗
  • 成本控制:监控API调用成本,优化使用策略
  • 自定义工具:开发自定义工具,扩展模型的能力边界

总结

Llama API为开发者提供了一个便捷的方式来使用Llama 2模型,无需本地部署,可以直接通过API调用模型服务。通过LlamaIndex的集成,开发者可以使用简单的API调用实现文本补全、对话交互、函数调用和结构化数据提取等功能。特别是函数调用和结构化数据提取功能,使得模型能够与外部工具和服务进行交互,大大扩展了应用场景。Llama API的OpenAI兼容性也使得开发者可以复用现有的OpenAI工具和库,降低了学习成本。总体而言,Llama API是一个值得考虑的Llama 2模型服务方案,特别适合那些希望快速部署Llama 2应用的开发者。

Read more

黑马程序员java web学习笔记--后端进阶(二)SpringBoot原理

目录 1 配置优先级 2 Bean的管理 2.1 Bean的作用域 2.2 第三方Bean 3 SpringBoot原理 3.1 起步依赖 3.2 自动配置 3.2.1 实现方案 3.2.2 原理分析 3.2.3 自定义starter 1 配置优先级 SpringBoot项目当中支持的三类配置文件: * application.properties * application.yml ❤ * application.yaml 配置文件优先级排名(从高到低):properties配置文件 > yml配置文件 > yaml配置文件 虽然springboot支持多种格式配置文件,但是在项目开发时,推荐统一使用一种格式的配置。

年度心得总结——前端领域

年度心得总结——前端领域

又是一年时光转,岁月如梭学习繁。 笔耕岁月求知路,心悟真谛志愈坚。 往昔耕耘结硕果,未来展望展宏愿。 共聚一堂话成就,再创辉煌谱新篇。 此刻,我暂且搁下手中的键盘,让思绪飘回那过往的日日夜夜。回望这一年的风雨兼程,心中不禁涌动着无尽的感慨。前端领域,这片充满无限可能的天地,又经历了一轮轰轰烈烈的蓬勃发展与变革。新技术如雨后春笋般涌现,旧框架在不断迭代中焕发新生,这一切都让我对这份事业充满了无尽的热爱与敬意。 同样是在这流转的一年里,我踏上了ZEEKLOG技术博主的星辰大海之旅,愿以我余温之烛,照亮同行者的征途,期盼自己能成为ZEEKLOG夜空中那颗即便只刹那闪耀,亦能点亮梦想的星辰。 文章目录 * 一、React 框架 * (一) React 优化 * (二) 开发效率提升 * (三) 服务端渲染(SSR)集成 * (四) 其他重要优化和功能支持 * 二、Vue 框架 * (一) Vue 版本与维护方面 * (二) 性能优化与增强 * 三、技术探索

OpenClaw 中 web_search + web_fetch 最佳实践速查表

OpenClaw 中 web_search + web_fetch 最佳实践速查表

OpenClaw 中 web_search + web_fetch 最佳实践速查表 摘要:本文帮助读者明确 OpenClaw 网络搜索工具和不同搜索技能的的职责边界,理解“先搜索、再抓取、后总结”的最佳实践,并能更稳定地在 OpenClaw 中使用 tavily-search 与 web_fetch 完成网络信息搜索任务。主要内容包括:解决 OpenClaw 中 web_search、tavily-search、web_fetch、原生 provider 与扩展 skill 容易混淆的问题、网络搜索能力分层说明、OpenClaw 原生搜索 provider 与 Tavily/Firecrawl 扩展 skill 的区别、标准工作流、提示词模板、

前端文件上传处理:别再让用户等待了!

前端文件上传处理:别再让用户等待了! 毒舌时刻 文件上传?听起来就像是前端工程师为了显得自己很专业而特意搞的一套复杂流程。你以为随便加个input[type=file]就能实现文件上传?别做梦了!到时候你会发现,大文件上传会导致页面崩溃,用户体验极差。 你以为FormData就能解决所有问题?别天真了!FormData在处理大文件时会导致内存溢出,而且无法显示上传进度。还有那些所谓的文件上传库,看起来高大上,用起来却各种问题。 为什么你需要这个 1. 用户体验:良好的文件上传处理可以提高用户体验,减少用户等待时间。 2. 性能优化:合理的文件上传策略可以减少服务器负担,提高上传速度。 3. 错误处理:完善的错误处理可以避免上传失败时的用户困惑。 4. 安全保障:安全的文件上传处理可以防止恶意文件上传,保障系统安全。 5. 功能丰富:支持多文件上传、拖拽上传、进度显示等功能,满足不同场景的需求。 反面教材 // 1. 简单文件上传 <input type="file&