FastAPI 教程翻译 - 用户指南 14 - Header 参数

FastAPI 教程翻译 - 用户指南 14 - Header 参数

FastAPI Tutorial - User Guide - Header Parameters

You can define Header parameters the same way you define Query, Path and Cookie parameters.

您可以使用定义 QueryPathCookie 参数的方法来定义 Header 参数。

Import Header

导入 Header

First import Header:

首先导入 Header

from fastapi import FastAPI, Header

app = FastAPI()


@app.get("/items/")
async def read_items(*, user_agent: str = Header(None)):
    return {"User-Agent": user_agent}

Declare Header parameters

声明 Header 参数

Then declare the header parameters using the same structure as with Path, Query and Cookie.

然后使用与 PathQueryCookie 相同的结构声明 Header 参数。

The first value is the default value, you can pass all the extra validation or annotation parameters:

第一个值是默认值,您可以传递所有其他验证或注释参数:

from fastapi import FastAPI, Header

app = FastAPI()


@app.get("/items/")
async def read_items(*, user_agent: str = Header(None)):
    return {"User-Agent": user_agent}

Technical Details

技术细节

Header is a “sister” class of Path, Query and Cookie. It also inherits from the same common Param class.

HeaderPathQueryCookie 的『姐妹』类。它也继承自相同的通用 Param 类。

But remember that when you import Query, Path, Header, and others from fastapi, those are actually functions that return special classes.

但是请记住,当您从 fastapi 中导入 QueryPathHeader 和其他文件时,这些实际上是返回特殊类的函数。

Info

信息

To declare headers, you need to use Header, because otherwise the parameters would be interpreted as query parameters.

要声明 Header,您需要使用 Header,否则参数将被解释为查询参数。

Automatic conversion

自动转换

Header has a little extra functionality on top of what Path, Query and Cookie provide.

HeaderPathQueryCookie 的基础上具有一些额外的功能。

Most of the standard headers are separated by a “hyphen” character, also known as the “minus symbol” (-).

大多数标准 header 由『连字符』(也称为『减号』)(-)分隔。

But a variable like user-agent is invalid in Python.

但是像 user-agent 这样的变量在 Python 中无效。

So, by default, Header will convert the parameter names characters from underscore (_) to hyphen (-) to extract and document the headers.

因此,默认情况下,Header 会将参数名称字符从下划线(_)转换为连字符(-),以提取并记录 header。

Also, HTTP headers are case-insensitive, so, you can declare them with standard Python style (also known as “snake_case”).

另外,HTTP header 不区分大小写,因此,您可以使用标准 Python 样式(也称为『snake_case』)声明它们。

So, you can use user_agent as you normally would in Python code, instead of needing to capitalize the first letters as User_Agent or something similar.

因此,您可以像在 Python 代码中一样正常使用 user_agent,而无需将首字母大写为 User_Agent 或类似名称。

If for some reason you need to disable automatic conversion of underscores to hyphens, set the parameter convert_underscores of Header to False:

如果由于某种原因需要禁用下划线自动转换为连字符,请将 Header 的参数 convert_underscores 设置为 False

from fastapi import FastAPI, Header

app = FastAPI()


@app.get("/items/")
async def read_items(*, strange_header: str = Header(None, convert_underscores=False)):
    return {"strange_header": strange_header}

Warning

警告

Before setting convert_underscores to False, bear in mind that some HTTP proxies and servers disallow the usage of headers with underscores.

在将 convert_underscores 设置为 False 之前,请记住,某些 HTTP 代理和服务器禁止使用带下划线的 header。

Duplicate headers

header 重复

It is possible to receive duplicate headers. That means, the same header with multiple values.

可能会收到重复的 header。也就是说,同一个 header 具有多个值。

You can define those cases using a list in the type declaration.

您可以使用类型声明中的列表来定义这些情况。

You will receive all the values from the duplicate header as a Python list.

您将从重复 header 中将所有值作为一个 Python 的 list 接收。

For example, to declare a header of X-Token that can appear more than once, you can write:

例如,要声明可以多次出现的 X-Token 的 header,可以编写:

from typing import List

from fastapi import FastAPI, Header

app = FastAPI()


@app.get("/items/")
async def read_items(x_token: List[str] = Header(None)):
    return {"X-Token values": x_token}

If you communicate with that path operation sending two HTTP headers like:

如果您与该路径操作通信,则发送两个 HTTP header,例如:

X-Token: foo
X-Token: bar

The response would be like:

{
    "X-Token values": [
        "bar",
        "foo"
    ]
}

Recap

回顾

Declare headers with Header, using the same common pattern as Query, Path and Cookie.

使用与 QueryPathCookie 相同的通用模式,用 Header 声明 header。

And don’t worry about underscores in your variables, FastAPI will take care of converting them.

不用担心变量中的下划线,FastAPI 将负责转换它们。

<think>好的,我现在要帮用户解答关于DeepSeek-R1部署完成后如何使用的问题。首先,我需要回顾之前的对话历史,看看用户之前的问题是什么。用户之前问过关于将显卡升级到4060 Ti是否可行以及token生成速度的问题,这说明用户可能在本地部署大语言模型,并且对硬件性能比较关注。现在用户已经部署好了DeepSeek-R1,想知道如何使用。 首先,我需要确定DeepSeek-R1是什么。根据名称,这可能是一个由深度求索(DeepSeek)公司开发的大语言模型,类似于LLaMA或者GPT。用户可能是在本地或者云端部署了这个模型,现在需要基本的使用方法、API调用、调优技巧等。 接下来,用户的使用场景可能是开发者或者研究人员,想要在本地运行模型进行测试或开发应用。因此,我需要涵盖基本的交互方式,比如命令行、API接口,以及可能的集成方法,比如LangChain。此外,用户可能关心如何优化性能,比如使用量化模型,或者调整生成参数如temperature和max_tokens。 用户可能没有明确提到的深层需求包括如何监控模型性能,处理多轮对话,以及进行模型微调。这些可能是进阶使用的重要部分,需要包含在回答中。同时,用户之前提到过显卡升级,可能需要强调如何利用GPU资源来提升推理速度,比如使用CUDA加速。 我需要确保回答结构清晰,分步骤说明,涵盖基础交互、API调用、参数调整、高级功能(如微调、多模态处理)、性能优化和常见问题。可能还需要提供示例代码,比如Python调用API的示例,或者量化模型的命令,这样用户可以直接参考使用。 另外,需要注意用户可能使用的是Windows环境,之前的问题提到过Windows环境下的部署,所以在路径示例中使用反斜杠,或者在性能优化部分提到CUDA和DirectML的配置。同时,用户可能有成本效益的考虑,所以优化推理速度和省电的配置建议也是有必要的。 最后,要检查是否有遗漏的部分,比如安全建议,比如API密钥的管理,或者模型版本的选择。确保回答全面,同时避免过于技术化,保持易懂,但也要提供足够细节供用户深入操作。</think>以下是关于**DeepSeek-R1**模型部署后的完整使用指南,涵盖从基础操作到高级功能的实践建议: --- ### 一、基础交互模式 #### 1. 命令行直接调用(推荐给开发者) ```bash # 启动交互式对话(假设使用transformers库) from transformers import AutoModelForCausalLM, AutoTokenizer model = AutoModelForCausalLM.from_pretrained("./deepseek-r1") tokenizer = AutoTokenizer.from_pretrained("./deepseek-r1") while True: input_text = input("User: ") inputs = tokenizer(input_text, return_tensors="pt") outputs = model.generate(**inputs, max_new_tokens=200) print("AI:", tokenizer.decode(outputs[0], skip_special_tokens=True)) ``` #### 2. Gradio WebUI(适合非技术用户) ```python # 安装依赖:pip install gradio import gradio as gr def respond(message, history): inputs = tokenizer(message, return_tensors="pt") outputs = model.generate(**inputs, max_new_tokens=300) return tokenizer.decode(outputs[0], skip_special_tokens=True) gr.ChatInterface(respond).launch(server_port=7860) ``` 访问 `http://localhost:7860` 即可使用可视化界面 --- ### 二、API服务化部署 #### 1. 启动FastAPI服务 ```python from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Query(BaseModel): prompt: str max_tokens: int = 200 @app.post("/generate") async def generate_text(query: Query): inputs = tokenizer(query.prompt, return_tensors="pt") outputs = model.generate(**inputs, max_new_tokens=query.max_tokens) return {"response": tokenizer.decode(outputs[0])} ``` 启动命令:`uvicorn api:app --reload --port 8000` #### 2. 调用示例(cURL) ```bash curl -X POST "http://localhost:8000/generate" \ -H "Content-Type: application/json" \ -d '{"prompt": "如何做蛋炒饭?", "max_tokens": 300}' ``` --- ### 三、关键参数调优 | 参数名 | 推荐值范围 | 作用说明 | 性能影响 | |--|------------------------| | `temperature` | 0.7-1.2 | 控制输出随机性(值越高越创意) | 高温可能降低输出连贯性 | | `top_p` | 0.85-0.95 | 核采样阈值 | 平衡多样性与相关性 | | `repetition_penalty` | 1.0-1.2 | 抑制重复内容 | 过高会导致语句碎片化 | | `num_beams` | 3-5 | 集束搜索宽度 | 提升质量但增加计算量 | **优化配置示例**: ```python outputs = model.generate( **inputs, max_new_tokens=400, temperature=0.9, top_p=0.9, repetition_penalty=1.1, num_beams=4 ) ``` --- ### 四、高级功能开发 #### 1. 多轮对话管理 ```python from transformers import Conversation conversation = Conversation() while True: user_input = input("User: ") conversation.add_user_input(user_input) model_output = model.generate( conversation, max_length=1000, pad_token_id=tokenizer.eos_token_id ) conversation.mark_processed() print("AI:", conversation.generated_responses[-1]) ``` #### 2. 长文本处理(支持16K上下文) ```python # 启用FlashAttention优化 model = AutoModelForCausalLM.from_pretrained( "./deepseek-r1", attn_implementation="flash_attention_2" ) # 分块处理长文本 def process_long_text(text, chunk_size=2048): chunks = [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)] for chunk in chunks: yield model.generate(**tokenizer(chunk, return_tensors="pt")) ``` --- ### 五、性能优化技巧 #### 1. 量化加速(RTX 4060 Ti适用) ```bash # 使用AutoGPTQ量化(需先安装optimum) python -m optimum.exporters.gptq deepseek-r1 \ --quant-bits 4 \ --quant-group-size 128 \ --act-order ``` #### 2. GPU显存优化配置 ```python # 混合精度推理(节省30%显存) model.half().cuda() # 启用PagedAttention(需vLLM支持) from vllm import LLM llm = LLM(model="./deepseek-r1", tensor_parallel_size=1) ``` --- ### 六、监控与调试 #### 1. 实时性能看板 ```bash # 使用nvitop监控GPU状态 nvitop -m full # 日志记录建议格式 import logging logging.basicConfig( filename='deepseek.log', format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO ) ``` #### 2. 常见错误处理 | 错误类型 | 解决方案 | 预防措施 | |--|------------------------------|----------------------------| | CUDA内存不足 | 启用`memory_efficient_attention` | 降低`max_tokens`值 | | 文本重复循环 | 增加`repetition_penalty` | 设置`no_repeat_ngram_size=3` | | 生成结果不符合预期 | 调整`temperature`和`top_p` | 添加system prompt约束 | --- ### 七、安全建议 1. API访问控制 ```python # 添加API密钥验证 from fastapi.security import APIKeyHeader api_key_header = APIKeyHeader(name="X-API-Key") async def check_api_key(key: str = Depends(api_key_header)): if key != "YOUR_SECRET_KEY": raise HTTPException(status_code=403, detail="Invalid API Key") ``` 2. 内容过滤机制 ```python # 安装:pip install profanity-filter from profanity_filter import ProfanityFilter pf = ProfanityFilter() def sanitize_output(text): return pf.censor(text) ``` --- **扩展建议**:对于企业级部署,建议结合Ray框架实现分布式推理,单个RTX 4060 Ti可支持约15-20并发请求(Q4量化下)。若需处理多模态任务,可参考OpenAI的CLIP架构扩展图像理解能力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值