2026/1/11 23:41:30
网站建设
项目流程
哪些网站是做货源的,wordpress插件密钥实现,百度网站做要多少钱,构建一个商务网站的步骤有哪些在 LLM#xff08;大语言模型#xff09; 的语境中#xff0c;Sampling#xff08;采样#xff09; 指的是模型从预测的候选词概率分布中#xff0c;选择下一个词来生成文本的过程。
简单来说#xff0c;大语言模型生成文本时#xff0c;不会直接 “确定” 下一个词大语言模型 的语境中Sampling采样 指的是模型从预测的候选词概率分布中选择下一个词来生成文本的过程。简单来说大语言模型生成文本时不会直接 “确定” 下一个词而是先计算出当前语境下所有可能出现的词的概率值再通过特定的采样策略从这个概率分布里挑选一个词逐步拼接成完整的文本。一、给MCP服务绑定LLMimportasyncioimportosfromopenaiimportOpenAIfromfastmcpimportFastMCPfromfastmcp.experimental.sampling.handlers.openaiimportOpenAISamplingHandler# 1. 初始化 FastMCP 服务器配置大模型处理器serverFastMCP(nameServer-Controlled LLM,# 配置 OpenAI 大模型处理器支持官方 API 或兼容 APIsampling_handlerOpenAISamplingHandler(default_modelgpt-4o-mini,# 默认使用的大模型clientOpenAI(api_keyos.getenv(OPENAI_API_KEY),# 大模型 API 密钥base_urlos.getenv(OPENAI_BASE_URL),# 可选自定义 API 地址如代理、私有部署),),# 触发策略always强制用服务端大模型/ fallback客户端不支持时兜底sampling_handler_behavioralways,)二、通过 ctx.sample() 与大模型问答方法一*ctx.sample# async method请求大语言模型生成文本并自动运行直至完成。场景 1简单文本生成基础提问server.toolasyncdefgenerate_summary(content:str,ctx:Context)-str:向大模型请求生成文本摘要# 构造提问提示promptf请简洁总结以下内容\n\n{content}# 调用大模型responseawaitctx.sample(messagesprompt,# 简单字符串提问temperature0.3,# 低随机性保证摘要稳定max_tokens300,# 限制摘要长度)# 返回大模型生成的结果response.text 为文本内容returnresponse.text场景 2带系统提示的专业问答定义大模型角色server.toolasyncdefgenerate_python_code(concept:str,ctx:Context)-str:让大模型生成 Python 代码示例指定角色为专家responseawaitctx.sample(messagesf写一个简单的 Python 代码示例演示{concept},system_prompt你是资深 Python 工程师只提供可运行的简洁代码不附加解释,# 系统提示定义角色temperature0.7,# 适度随机性允许代码变体max_tokens500,model_preferencesgpt-4,# 本次请求优先使用 gpt-4覆盖默认的 gpt-4o-mini)# 格式化代码输出returnfpython\n{response.text}\n场景 3多轮对话结构化消息通过 SamplingMessage 构造多轮对话上下文支持角色区分user/assistantfromfastmcp.client.samplingimportSamplingMessageserver.toolasyncdefmulti_turn_analysis(user_query:str,context_data:str,ctx:Context)-str:多轮对话式分析带历史上下文# 构造多轮消息角色内容messages[SamplingMessage(roleuser,contentf我的数据{context_data}),# 第一轮用户提供数据SamplingMessage(roleassistant,content已收到数据你想分析什么),# 第二轮助手回应SamplingMessage(roleuser,contentuser_query)# 第三轮用户具体提问]responseawaitctx.sample(messagesmessages,# 传入结构化消息列表system_prompt你是数据分析师基于对话上下文提供详细分析,temperature0.2,# 低随机性保证分析严谨)returnresponse.text场景 4情感分析简单分类任务server.toolasyncdefanalyze_sentiment(text:str,ctx:Context)-dict:让大模型分析文本情感正面/负面/中性promptf 分析以下文本的情感仅输出一个词positive正面、negative负面或 neutral中性。 文本{text}responseawaitctx.sample(prompt,temperature0.0)# 0 随机性保证分类一致sentimentresponse.text.strip().lower()# 标准化结果ifpositiveinsentiment:resultpositiveelifnegativeinsentiment:resultnegativeelse:resultneutralreturn{text:text,sentiment:result}方法二ctx.sample_step()三、结构化输出当你需要经过验证的、有类型的数据而非自由格式的文本时请使用 result_type 参数。FastMCP 确保大语言模型返回与你的类型相匹配的数据并自动处理验证和重试操作。result_type 参数可接受 Pydantic 模型、数据类以及基本类型如 int、list [str] 或 dict [str, int]。frompydanticimportBaseModelfromfastmcpimportFastMCP,Context mcpFastMCP()classSentimentResult(BaseModel):sentiment:strconfidence:floatreasoning:strmcp.toolasyncdefanalyze_sentiment(text:str,ctx:Context)-SentimentResult:Analyze text sentiment with structured output.resultawaitctx.sample(messagesfAnalyze the sentiment of:{text},result_typeSentimentResult,)returnresult.result# A validated SentimentResult object当你调用这个工具时大语言模型LLM会返回一个结构化响应FastMCP 会根据你的 Pydantic 模型对该响应进行验证。你可以通过result.result访问经过验证的对象而result.text则包含 JSON 格式的表示。当你传入result_type时sample ()会自动创建一个 final_response 工具大语言模型会调用该工具来提供其响应。如果验证失败错误会被发送回大语言模型以进行重试。这种自动处理仅适用于sample ()—— 对于sample_step ()你必须自行管理结构化输出。四、使用工具进行采样借助工具进行采样能够实现智能体工作流让大语言模型LLM在做出回应前可以调用函数来收集信息。这一功能实现了 SEP-1577允许大语言模型自主编排多步骤操作。将 Python 函数传递给 tools 参数FastMCP 会自动处理执行循环 —— 调用工具、将结果返回给大语言模型并持续这一过程直到大语言模型给出最终回应。4.1 定义工具使用类型提示和文档字符串定义常规的 Python 函数。FastMCP 会提取函数的名称、文档字符串和参数类型以创建大语言模型能够理解的工具模式。fromfastmcpimportFastMCP,Contextdefsearch(query:str)-str:Search the web for information.returnfResults for:{query}defget_time()-str:Get the current time.fromdatetimeimportdatetimereturndatetime.now().strftime(%H:%M:%S)mcpFastMCP()mcp.toolasyncdefresearch(question:str,ctx:Context)-str:Answer questions using available tools.resultawaitctx.sample(messagesquestion,tools[search,get_time],)returnresult.textor大语言模型LLM会查看每个函数的签名和文档字符串并利用这些信息来决定何时以及如何调用它们。工具错误会被捕获并反馈给大语言模型使其能够平稳地恢复。一个内部安全限制可防止无限循环。4.2 工具错误处理默认情况下当采样工具抛出异常时错误消息包括详细信息会发送回大语言模型以便其尝试恢复。为防止敏感信息泄露给大语言模型请使用 mask_error_details 参数resultawaitctx.sample(messagesquestion,tools[search],mask_error_detailsTrue,# Generic error messages only)当 mask_error_detailsTrue 时工具错误会变成诸如 “执行工具‘search’时出错” 之类的通用消息而不会暴露堆栈跟踪或内部细节。若要不管是否启用屏蔽都特意向 LLM 提供特定的错误消息请抛出 ToolErrorfromfastmcp.exceptionsimportToolErrordefsearch(query:str)-str:Search for information.ifnotquery.strip():raiseToolError(Search query cannot be empty)returnfResults for:{query}工具错误消息总会传递给大语言模型LLM使其成为你希望大语言模型看到并处理错误的应急出口。对于自定义名称或描述请使用 SamplingTool.from_function ()fromfastmcp.server.samplingimportSamplingTool toolSamplingTool.from_function(my_func,namecustom_name,descriptionCustom description)resultawaitctx.sample(messages...,tools[tool])4.3 组合结构化输出将工具与结果类型相结合用于生成能返回经过验证的结构化数据的智能代理工作流。大语言模型LLM会使用你的工具来收集信息然后返回与你的类型相匹配的响应。resultawaitctx.sample(messagesResearch Python async patterns,tools[search,fetch_url],result_typeResearchResult,)五、循环控制虽然 sample () 会自动处理工具执行循环但在某些场景下需要对每个步骤进行精细控制。sample_step () 方法会进行一次 LLM 调用并返回一个包含响应和更新后历史记录的 SampleStep。与 sample () 不同sample_step () 是无状态的 —— 它不会记住之前的调用。你需要通过每次传递完整的消息历史来控制对话。返回的 step.history 包含截至当前响应的所有消息便于继续循环。在以下情况时使用 sample_step ()在工具调用执行前对其进行检查实现自定义终止条件在步骤之间添加日志记录、指标监控或检查点设置利用特定领域逻辑构建自定义智能体循环5.1 使用 sample_step ()默认情况下sample_step () 会执行所有工具调用并将结果包含在历史记录中。在循环中调用它每次传递更新后的历史记录直到满足停止条件。frommcp.typesimportSamplingMessagemcp.toolasyncdefcontrolled_agent(question:str,ctx:Context)-str:Agent with manual loop control.messages:list[str|SamplingMessage][question]# strings auto-convertwhileTrue:stepawaitctx.sample_step(messagesmessages,tools[search,get_time],)ifstep.is_tool_use:# Tools already executed (execute_toolsTrue by default)# Log what was called before continuingforcallinstep.tool_calls:print(fCalled tool:{call.name})ifnotstep.is_tool_use:returnstep.textor# Continue with updated historymessagesstep.history5.2 SampleStep属性每个 SampleStep 都会提供有关大语言模型LLM返回内容的信息step.is_tool_use— 如果大语言模型请求调用工具则为 Truestep.tool_calls— 请求的工具调用列表如有step.text— 文本内容如有step.history— 到目前为止交换的所有消息step.history的内容取决于 execute_toolsexecute_toolsTrue默认值包含工具结果为下一次迭代做好准备execute_toolsFalse包含助手的工具请求但需要您自行添加结果5.3 手动执行工具将 execute_tools 设置为 False以便自行处理工具执行。禁用该功能时step.history 会包含用户消息以及带有工具调用的助手回复但不包含工具结果。您需要执行这些工具并将结果作为用户消息追加进去。frommcp.typesimportSamplingMessage,ToolResultContent,TextContentfromfastmcpimportFastMCP,Context mcpFastMCP()mcp.toolasyncdefresearch(question:str,ctx:Context)-str:Research with manual tool handling.defsearch(query:str)-str:returnfResults for:{query}defget_time()-str:return12:00 PM# Map tool names to functionstools{search:search,get_time:get_time}messages:list[SamplingMessage][question]# strings are converted automaticallywhileTrue:stepawaitctx.sample_step(messagesmessages,toolslist(tools.values()),execute_toolsFalse,)ifnotstep.is_tool_use:returnstep.textor# Execute tools and collect resultstool_results[]forcallinstep.tool_calls:fntools[call.name]resultfn(**call.input)tool_results.append(ToolResultContent(typetool_result,toolUseIdcall.id,content[TextContent(typetext,textresult)],))messageslist(step.history)messages.append(SamplingMessage(roleuser,contenttool_results))错误处理要报告错误请将 isError 设置为 True。大语言模型LLM会看到该错误并能决定如何继续处理tool_resultToolResultContent(typetool_result,toolUseIdcall.id,content[TextContent(typetext,textPermission denied)],isErrorTrue,)六、备用处理MCP 默认优先调用客户端已配置的大模型服务端无需额外配置大模型信息直接通过 ctx.sample() 触发即可。客户端对采样的支持是可选的 —— 有些客户端可能不会实现这一功能。为确保你的工具无论客户端具备何种能力都能正常运行请配置一个直接向大语言模型LLM提供商发送请求的采样处理器sampling_handler。FastMCP 为 OpenAI 和 Anthropic 的应用程序接口API提供了内置处理器。这些处理器支持完整的采样应用程序接口包括工具相关功能能自动将你的 Python 函数转换为各个提供商所需的格式。使用 pip install fastmcp [openai] 或 pip install fastmcp [anthropic] 安装处理器。fromfastmcpimportFastMCPfromfastmcp.client.sampling.handlers.openaiimportOpenAISamplingHandler serverFastMCP(nameMy Server,sampling_handlerOpenAISamplingHandler(default_modelgpt-4o-mini),sampling_handler_behaviorfallback,)或者fromfastmcpimportFastMCPfromfastmcp.client.sampling.handlers.anthropicimportAnthropicSamplingHandler serverFastMCP(nameMy Server,sampling_handlerAnthropicSamplingHandler(default_modelclaude-sonnet-4-5),sampling_handler_behaviorfallback,)6.1 行为模式sampling_handler_behavior参数控制handler的使用时机“fallback”默认值仅当客户端不支持采样时使用处理器。这使得有能力的客户端可以使用自己的大语言模型LLM同时确保你的工具在缺乏采样支持的客户端上仍然能正常工作。“always”始终使用handler完全绕过客户端。当你需要确保对处理请求的大语言模型LLM拥有控制权时使用此选项例如出于成本控制、合规要求或者当特定的模型特性至关重要时。使用工具进行采样要求客户端声明具备sampling.tools能力。FastMCP 客户端会自动进行声明。对于不支持工具启用采样的外部客户端请将 fallback 处理器配置为 sampling_handler_behavior“always”。