【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

Linux下libwebkit2gtk-4.1-0安装实战案例(从零实现)

Linux下 libwebkit2gtk-4.1-0 安装实战:从零搞定GTK 4应用的Web渲染引擎 你是否在开发一个基于 GTK 4 的桌面程序时,突然发现 webkit_web_view_new() 编译报错? 或者运行时提示“找不到 libwebkit2gtk-4.1.so.0 ”? 别急——这不是你的代码写错了,而是系统里缺了那个关键的 Web 渲染库: libwebkit2gtk-4.1-0 。 这玩意儿看起来只是个动态链接库,但它其实是现代 Linux 桌面应用中嵌入网页内容的“心脏”。无论是 OAuth 登录窗口、帮助文档展示,还是像 Epiphany 浏览器那样的完整 Web 客户端,都离不开它。 但问题来了:为什么这个包这么难装? 因为它依赖复杂、版本敏感、发行版支持参差不齐。Ubuntu

前端无障碍性:让所有人都能使用你的网站

前端无障碍性:让所有人都能使用你的网站 毒舌时刻 前端无障碍性?这不是给残障人士用的吗? "我的网站不需要无障碍性,用户都是正常人"——结果被投诉歧视, "无障碍性太麻烦了,我没时间做"——结果失去了一部分用户, "无障碍性就是加几个alt标签而已"——结果网站在屏幕阅读器下完全不可用。 醒醒吧,无障碍性不是慈善,而是一种责任! 为什么你需要这个? * 法律合规:许多国家和地区都有无障碍性法规 * 扩大用户群体:让残障人士也能使用你的网站 * SEO优化:无障碍性好的网站更容易被搜索引擎收录 * 用户体验:对所有人都友好的设计,对正常人也有好处 反面教材 <!-- 反面教材:缺乏语义化HTML --> <div> <div>网站logo</div> <

Claude Code本地化部署教程:零成本打造最强内网AI开发助手

Claude Code本地化部署教程:零成本打造最强内网AI开发助手

文章介绍了如何通过Ollama将Claude Code接入本地开源模型,实现不联网、不花钱、代码不出本地的开发环境。提供了详细配置教程,包括安装客户端、设置环境变量和启动本地模型。这种方式确保数据安全,无需订阅费用,可自由切换Qwen3、GLM等模型,为开发者提供了完全离线的AI辅助开发体验。 如果你是一个开发者,一定被Claude Code的能力震惊了。简单来说,它不仅仅是一个聊天框,而是一个能直接住在你的工作空间内的数字员工,能读懂你的源码、系统功能修BUG、写报告,互联网检索等,在授权的情况下,还能运行终端命令。 但是很多人担心隐私泄露,或者不想一直给Claude交昂贵的订阅费。今天,救星来了!通过Ollama可以把 Claude Code 这个“神级躯壳”接入本地运行的开源模型(如 Qwen3、GLM)。不联网、不花钱、代码不出本地,可谓是最强内网开发套装! 为什么又要本地跑Claude Code? * 数据安全:公司代码资产,怎么敢随便传输到云端?本地运行,物理隔离最安心。 * 告别订阅:

【大模型应用】Java开发者的AI智能编程实战解析:从Rule约束到Skill复用的全方位指南

Java开发者的AI智能编程实战解析:从Rule约束到Skill复用的全方位指南 作为Java资深开发者,掌握AI编程不仅关乎效率提升,更是技术竞争力的关键体现。 一、AI编程范式的技术演进与Java开发视角 2025年是AI编程工具从“辅助”走向“主导”的转折点。从最初的代码补全到现在的全流程自主开发,AI编程已经经历了六代技术演进。作为Java开发者,我们需要理解这一变革的技术本质。 1.1 演进历程与Java开发的影响 Vibe Coding(2024-2025年兴起)让Java开发者从繁琐的样板代码中解放出来,专注于架构设计和业务逻辑。而Rule、Skill、MCP、Agent等概念的形成,标志着AI编程从工具层面向工程化、体系化方向发展。 对于Java企业级开发而言,这一变化尤为显著:传统的Spring Boot项目初始化、依赖配置、项目结构搭建等重复性工作,现在可以通过AI Agent自动化完成,开发者只需关注核心业务架构。 核心概念定位与演进时间线 1. Vibe Coding:开发范式的革命 推出时间:2024年开始兴起,2025年形成明确方法论