ARTICLE DETAIL

资讯详情

深耕编程入门与网站建设的一线实战洞察。

在 agno 中使用 Cerebras 模型:从基础对话到结构化输出、工具调用与记忆存储的完整实战指南

在 agno 中使用 Cerebras 模型:从基础对话到结构化输出、工具调用与记忆存储的完整实战指南 在 agno 中使用 Cerebras 模型从基础对话到结构化输出、工具调用与记忆存储的完整实战指南【免费下载链接】agnoBuild, run, and manage agent platforms.项目地址: https://gitcode.com/GitHub_Trending/ag/agno本指南围绕 cookbook/90_models/cerebras 目录下的完整示例展开讲解如何在 agno 中接入 Cerebras 云端推理平台默认模型gpt-oss-120b。读完本文你将掌握 Cerebras 模型的基本对话与流式输出、严格结构化输出JSON Schema、工具调用、请求重试策略以及结合知识库PgVector和会话数据库PostgreSQL构建带记忆的智能体并理解底层 Cerebras 模型实现 的关键参数与调用机制。一、示例总览与运行方式cookbook/90_models/cerebras目录是 agno 官方 cookbook 中面向 Cerebras 模型的示例集合共包含 7 个可直接运行的 Python 示例示例文件核心主题basic.py最基本的对话含同步 / 异步 / 流式四种调用方式structured_output.py基于 Pydantic 的严格结构化输出strict / guided 两种模式tool_use.py工具Function Calling调用oss_gpt.py使用开源 GPT 模型gpt-oss-120b结合 Web 搜索工具retry.py请求失败时的自动重试与指数退避knowledge.py知识库 向量数据库PgVector检索增强生成RAGdb.py会话历史持久化PostgreSQL实现多轮记忆目录中的 README.md 给出了统一的运行入口使用项目 demo 虚拟环境中的 Python 解释器执行对应示例脚本.venvs/demo/bin/python cookbook/90_models/cerebras/example.py例如运行基础对话示例.venvs/demo/bin/python cookbook/90_models/cerebras/basic.py从源码结构看所有示例均通过from agno.models.cerebras import Cerebras导入模型类这与 libs/agno/agno/models/cerebras/init.py 的导出定义一致该模块还导出了一个基于 OpenAI 兼容协议的CerebrasOpenAI类。目录下的 TEST_LOG.md 目前尚未记录自动化测试结果因此本文以示例代码和模型实现源码为准。二、环境准备与依赖运行 Cerebras 示例前需要先安装官方 Cerebras 云 SDK。在 cerebras.py 中模型类会在导入时尝试加载cerebras.cloud.sdk中的Cerebras与AsyncCerebras客户端若未安装则直接抛出ImportError: cerebras-cloud-sdk not installed. Please install using pip install cerebras-cloud-sdk因此请先执行pip install cerebras-cloud-sdk随后设置 Cerebras API Key 环境变量源码中通过getenv(CEREBRAS_API_KEY)读取见 cerebras.pyexport CEREBRAS_API_KEYyour-cerebras-api-key若未设置该环境变量模型会在日志中输出错误提示CEREBRAS_API_KEY not set. Please set the CEREBRAS_API_KEY environment variable.对于知识库RAG和会话数据库示例还需按文件头部注释安装额外依赖# knowledge.py 所需依赖 uv pip install ddgs sqlalchemy pgvector pypdf cerebras_cloud_sdk # db.py 所需依赖 uv pip install ddgs sqlalchemy cerebras_cloud_sdk三、基础对话同步、异步与流式cookbook/90_models/cerebras/basic.py 演示了用 agno 创建 Cerebras 智能体的最小写法import asyncio from agno.agent import Agent from agno.models.cerebras import Cerebras agent Agent( modelCerebras(idgpt-oss-120b), markdownTrue, # 以 Markdown 格式渲染输出 )Agent是 agno 的核心智能体封装markdownTrue让终端输出以 Markdown 渲染阅读性更好。示例脚本在__main__块中依次演示了四种调用方式if __name__ __main__: # --- 同步调用 --- agent.print_response(write a two sentence horror story) # --- 同步 流式 --- agent.print_response(write a two sentence horror story, streamTrue) # --- 异步调用 --- asyncio.run(agent.aprint_response(write a two sentence horror story)) # --- 异步 流式 --- asyncio.run(agent.aprint_response(write a two sentence horror story, streamTrue))四种方式覆盖了绝大部分应用场景print_response用于同步脚本与 CLIaprint_response用于异步服务如 FastAPI 接口streamTrue用于需要边生成边输出打字机效果的交互场景。从源码看流式调用由 cerebras.py 中的invoke_stream方法实现它会调用 Cerebras 客户端的chat.completions.create并以迭代器方式返回分块响应ChatChunkResponse配合 agno 的run_response逐块分发。同步/异步调用则分别由invoke与ainvoke完成内部统一走get_request_params()构造请求参数。模型参数速查Cerebras数据类继承自agno.models.base.Model在 cerebras.py 中定义了完整的请求参数均可作为关键字传入构造函数参数默认值说明idgpt-oss-120b模型 ID示例均使用 Cerebras 上的开源模型 gpt-oss-120btemperatureNone采样温度控制输出随机性top_p/top_kNone核采样与 top-k 采样参数max_completion_tokensNone单次生成的最大 token 数repetition_penaltyNone重复惩罚系数parallel_tool_callsNone是否允许模型并行发起多个工具调用strict_outputTrue结构化输出时是否强制遵循 JSON Schema详见下一节api_keyNone显式传入 API Key不传则读CEREBRAS_API_KEY环境变量base_urlNone自定义 API 端点默认指向 Cerebras 官方端点timeout/max_retriesNone客户端超时与底层连接重试次数extra_headers/extra_query/extra_bodyNone追加到请求上的额外头部、查询参数与请求体字段request_params/client_paramsNone批量透传给请求或客户端的额外参数字典需要特别说明的是max_retries是 SDK 客户端的底层连接重试与下一节示例中retries参数应用层的请求重试是两套机制。四、结构化输出strict 与 guided 两种模式cookbook/90_models/cerebras/structured_output.py 展示了如何让 Cerebras 模型按照 Pydantic Schema 输出结构化数据。示例定义一个电影剧本模型from typing import List from pydantic import BaseModel, Field class MovieScript(BaseModel): setting: str Field(..., descriptionProvide a nice setting for a blockbuster movie.) ending: str Field(..., descriptionEnding of the movie. If not available, provide a happy ending.) genre: str Field(..., descriptionGenre of the movie. If not available, select action, thriller or romantic comedy.) name: str Field(..., descriptionGive a name to this movie) characters: List[str] Field(..., descriptionName of characters for this movie.) storyline: str Field(..., description3 sentence storyline for the movie. Make it exciting!)然后创建两种模式的 Agent# 严格模式默认strict_outputTrue保证输出符合 Schema structured_output_agent Agent( modelCerebras(idgpt-oss-120b), descriptionYou write movie scripts., output_schemaMovieScript, ) # 引导模式strict_outputFalseSchema 仅作引导可能偶尔偏离 guided_output_agent Agent( modelCerebras(idgpt-oss-120b, strict_outputFalse), descriptionYou write movie scripts., output_schemaMovieScript, ) structured_output_agent.print_response(New York) guided_output_agent.print_response(New York)两种模式的含义在模型源码的strict_output字段注释中写得很明确True时保证结构化输出严格遵循 SchemaFalse时模型把 Schema 当作引导guided mode可能偶尔偏离。代码中还注释了通过RunOutput把响应存入变量的方式structured_output_response: RunOutput structured_output_agent.run(New York) pprint(structured_output_response.content)从实现细节看Cerebras 模型不支持原生结构化输出supports_native_structured_outputs: bool False但支持 JSON Schema 输出supports_json_schema_outputs: bool True因此 agno 会把 Pydantic 模型转换为 JSON Schema 交给 Cerebras 校验。其中有一个关键约束Cerebras API 要求 JSON Schema 中的所有 object 类型都必须显式声明additionalProperties: false为此 cerebras.py 提供了_ensure_additional_properties_false方法在发送前递归遍历 Schema含嵌套properties、items、$defs自动补上该字段。这也意味着当你在自定义 Schema 时若嵌套对象未声明additionalPropertiesagno 会自动帮你修正无需手动处理。若想改用 OpenAI 兼容协议访问 Cerebras可参考init.py 中导出的CerebrasOpenAI类依赖openai包未安装时会抛出相应 ImportError 提示。五、工具调用Function Calling与 Web 搜索tool_use.py 演示了让 Cerebras 智能体使用 agno 内置的 Web 搜索工具import asyncio from agno.agent import Agent from agno.models.cerebras import Cerebras from agno.tools.websearch import WebSearchTools agent Agent( modelCerebras(idgpt-oss-120b), tools[WebSearchTools()], markdownTrue, ) if __name__ __main__: agent.print_response(Whats happening in France?) agent.print_response(Whats happening in France?, streamTrue) asyncio.run(agent.aprint_response(Whats happening in France?)) asyncio.run(agent.aprint_response(Whats happening in France?, streamTrue))当模型判断问题需要实时信息时会自动生成工具调用请求agno 执行WebSearchTools并回传搜索结果模型再基于结果组织最终回答。工具调用的请求格式由 agno 统一生成并会经过 cerebras.py 中的normalize_tool_messages做消息归一化后再发给 Cerebras API。oss_gpt.py 是它的姊妹示例写法几乎一致特别强调了 Cerebras 平台上的开源 GPT 模型gpt-oss-120b同样具备完整的工具调用能力from agno.agent.agent import Agent from agno.models.cerebras.cerebras import Cerebras from agno.tools.websearch import WebSearchTools agent Agent( modelCerebras(idgpt-oss-120b), tools[WebSearchTools()], markdownTrue, ) agent.print_response(Whats happening in France?)六、失败重试重试次数、间隔与指数退避cookbook/90_models/cerebras/retry.py 演示了请求失败时的自动重试配置。示例刻意使用一个错误的模型 ID 来触发重试逻辑from agno.agent import Agent from agno.models.cerebras import Cerebras # 故意使用错误的模型 ID以触发重试 wrong_model_id cerebras-wrong-id agent Agent( modelCerebras( idwrong_model_id, retries3, # 请求失败后的重试次数 delay_between_retries1, # 每次重试之间的延迟秒 exponential_backoffTrue, # 若为 True每次重试延迟翻倍 ), ) agent.print_response(What is the capital of France?)三个参数组合起来构成了完整的重试策略retries最多重试次数。配合错误模型 ID 运行时可以看到多次失败的日志与间隔性重试过程delay_between_retries每次重试前的固定等待秒数exponential_backoff开启后等待时间按 1s、2s、4s……指数递增避免瞬时洪峰下反复撞击服务端。在生产环境中建议把retries与exponential_backoffTrue搭配使用以应对 Cerebras API 的瞬时限流或网络抖动。七、知识库接入PgVector 向量检索增强生成RAGknowledge.py 展示了把 Cerebras 智能体与向量数据库结合实现基于自有文档的问答。示例使用 pgvector 存储食谱知识from agno.agent import Agent from agno.knowledge.knowledge import Knowledge from agno.models.cerebras import Cerebras from agno.vectordb.pgvector import PgVector db_url postgresqlpsycopg://ai:ailocalhost:5532/ai knowledge Knowledge( vector_dbPgVector(table_namerecipes, db_urldb_url), ) # 向知识库写入内容PDF 文档会被解析并向量化 knowledge.insert(urlhttps://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf) agent Agent(modelCerebras(idgpt-oss-120b), knowledgeknowledge) agent.print_response(How to make Thai curry?, markdownTrue)工作链路如下Knowledge对象挂载PgVector向量库table_namerecipes指定 pgvector 中的表名db_url指向运行中的 PostgreSQL示例使用ai:ailocalhost:5532/ai需要先用仓库 scripts/run_pgvector.sh 等脚本启动对应的 pgvector 容器knowledge.insert(...)下载并解析 PDF 文档切片后向量化写入 pgvector智能体收到用户问题时先在知识库中检索最相关的片段连同问题一起交给 Cerebras 模型生成答案从而让gpt-oss-120b掌握训练数据之外的自有领域知识。需要说明的是运行该示例需要ddgs、sqlalchemy、pgvector、pypdf、cerebras_cloud_sdk等依赖文件头部注释已列出。八、会话记忆持久化PostgreSQL 多轮上下文db.py 演示了把会话历史写入 PostgreSQL让智能体在多轮对话间保持上下文记忆from agno.agent import Agent from agno.db.postgres import PostgresDb from agno.models.cerebras import Cerebras from agno.tools.websearch import WebSearchTools db_url postgresqlpsycopg://ai:ailocalhost:5532/ai db PostgresDb(db_urldb_url) agent Agent( modelCerebras(idgpt-oss-120b), dbdb, # 会话历史持久化到 PostgreSQL tools[WebSearchTools()], add_history_to_contextTrue, # 将历史对话加入上下文 ) agent.print_response(How many people live in Canada?) agent.print_response(What is their national anthem called?)关键配置是add_history_to_contextTrue它会把数据库中存储的历史消息拼入每次请求的上下文。因此第二问“What is their national anthem called?”中的“their”才能正确指代上一问的 Canada——这正是多轮对话记忆的核心价值。PostgresDb负责消息的持久化存储即使进程重启历史也不会丢失。在实际部署时可以进一步与 agno 的 06_storage 系列示例结合如 01_persistent_session_storage.py为不同的会话session建立独立的记忆空间。九、小结从示例到生产围绕cookbook/90_models/cerebras目录你可以用最短的代码把 Cerebras 的gpt-oss-120b模型接入 agno 智能体并逐步叠加能力对话能力basic.py的同步 / 异步 / 流式四件套可靠性retry.py的重试 指数退避应对瞬时故障结构化输出structured_output.py的 strict / guided 两种模式配合 agno 自动补全additionalProperties: false让输出严格符合 Pydantic Schema工具调用tool_use.py/oss_gpt.py挂载 Web 搜索等工具扩展模型实时信息获取能力知识注入knowledge.py PgVector 实现 RAG记忆持久化db.py PostgreSQL 实现多轮上下文。所有示例的模型实现都集中在 libs/agno/agno/models/cerebras/cerebras.py它基于cerebras-cloud-sdk封装统一了invoke/ainvoke/invoke_stream/ainvoke_stream四类调用路径并通过strict_output、JSON Schema 输出和递归 Schema 修正等机制让 Cerebras 平台能力与 agno 的 Agent / Team / Workflow 生态无缝衔接。如果你后续还需要了解 OpenAI 兼容的访问方式CerebrasOpenAI 类提供了另一条可选路径。【免费下载链接】agnoBuild, run, and manage agent platforms.项目地址: https://gitcode.com/GitHub_Trending/ag/agno创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表