三种访问Qwen大模型的方式

三种访问Qwen大模型的方式

1. 通过API Key访问大模型


这是最直接的方式,通过官方API接口调用Qwen模型服务。你需要先在阿里云百炼平台获取API Key。

import dashscope
from dashscope.api_entities.dashscope_response import Role
​
# 设置API Key (替换为你的实际Key)
dashscope.api_key = "your_api_key_here"def get_response(messages):
    response = dashscope.Generation.call(
        model='qwen-turbo',  # 或使用其他Qwen模型如'qwen-plus'
        messages=messages,
        result_format='text'  # 输出格式可以是'message'或'text'
       #result_format='message'  # 将输出设置为message形式
    )
    return response
​
# 示例使用
review = '这本书写得很烂,读也读不懂。'
messages = [
    {"role": "system", "content": "你是一名舆情分析师,帮我判断产品口碑的正负向,回复请用一个词语:正向 或者 负向"},
    {"role": "user", "content": review}
]
​
response = get_response(messages)#对应text格式的输出
print(response.output.text)
# 对应message格式的content输出
#print(response.json()["output"]["choices"][0]["message"]["content"])
#print(response.output.choices[0].message.content)




说明:需替换your_api_key_here,支持流式输出(添加"stream": true参数)。

2. 本地部署大模型后在程序中封装调用


这种方式需要先在本地部署Qwen模型,然后通过transformers库直接调用。

from transformers import AutoModelForCausalLM, AutoTokenizer
​
# 加载本地部署的Qwen模型
# model_path = "/path/to/your/qwen_model"  # 替换为你的模型路径
model_path="C:\\Users\\Administrator\\AInewModels\\deepseek-ai\\DeepSeek-R1-Distill-Qwen-1___5B"
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(model_path, 
                                           device_map="auto", #如果有GPU可选"cuda"
                                           torch_dtype="auto", 
                                           trust_remote_code=True).eval()def query_model(text):
    inputs = tokenizer([text], return_tensors="pt").to(model.device)
    outputs = model.generate(**inputs, max_length=128,max_new_tokens=200)
    return tokenizer.decode(outputs[0], skip_special_tokens=True)# 示例使用
review = '这本书写得很烂,读也读不懂。'
messages = [
    {"role": "system", "content": "你是一名舆情分析师,帮我判断产品口碑的正负向,回复请用一个词语:正向 或者 负向"},
    {"role": "user", "content": review}
]
prompt = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    add_generation_prompt=True
)
response = query_model(prompt)
print(response)
'你是一名舆情分析师,帮我判断产品口碑的正负向,回复请用一个词语:正向 或者 负向<|User|>这本书写得很烂,读也读不懂。<|Assistant|><think>\n好,我现在需要分析用户的问题。用户提到这本书写得很烂,读也读不懂。首先,我应该判断这是正面还是负面评价。书的内容质量差,影响读者阅读体验,这属于负面评价。所以,回复应该是“负向”。\n</think>\n\n负向'


3. 本地部署大模型后通过类似API Key的方式调用


适用场景:将本地模型封装为HTTP服务供多端调用。
步骤

  1. 使用FastAPIFlask启动本地API服务。
  2. 通过requests访问本地端口。

    代码示例(服务端):
from fastapi import FastAPI
from transformers import AutoModelForCausalLM, AutoTokenizer
​
app = FastAPI()
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen-7B-Chat", device_map="auto")
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen-7B-Chat")@app.post("/chat")
def chat(question: str):
    inputs = tokenizer(question, return_tensors="pt").to("cuda")
    outputs = model.generate(**inputs, max_new_tokens=50)
    return {"answer": tokenizer.decode(outputs[0], skip_special_tokens=True)}


客户端调用

import requests
response = requests.post("http://localhost:8000/chat", json={"question": "Python怎么排序列表?"})
print(response.json()["answer"])


说明:可结合Ollama简化部署流程(如ollama run qwen2:7b)。



补充: 使用Ollama等工具本地部署Qwen后,可以创建兼容OpenAI API的本地服务。

from openai import OpenAI
​
# 配置本地API服务
client = OpenAI(
    base_url='http://localhost:11434/v1',  # Ollama默认端口
    api_key='ollama'  # 本地服务通常不需要真实API Key
)def get_local_response(prompt):
    completion = client.chat.completions.create(
        model="qwen",  # 本地部署的模型名称
        messages=[
            {"role": "system", "content": "你是一个有帮助的助手。"},
            {"role": "user", "content": prompt}
        ],
        temperature=0.7
    )
    return completion.choices[0].message.content
​
# 示例使用
response = get_local_response("请用Python写一个快速排序算法")
print(response)

总结对比

方法适用场景优点缺点
API Key访问快速测试、轻量级应用、无硬件资源简单、无需部署、支持流式输出依赖网络、长期成本高、隐私性低
本地直接调用数据敏感、离线环境、高性能需求隐私性强、离线可用、高度定制化硬件要求高、部署复杂
本地HTTP服务调用团队协作、多端调用、本地化部署多端兼容、隐私性好、集中管理需额外开发、硬件依赖、可能延迟


注意事项

  1. API Key方式需要网络连接,但使用最简单
  2. 本地部署方式需要足够的硬件资源(特别是GPU)
  3. Ollama方式对硬件要求较低,适合快速本地测试
  4. 所有代码示例中的参数(如模型名称、路径等)需要根据你的实际情况调整
### 集成Qwen大模型API到网页应用 为了在网页应用程序中集成和调用Qwen大模型API,可以采用Spring Boot框架作为后端服务器来处理来自前端页面的请求,并通过Java代码调用Qwen API完成交互操作[^1]。 #### 后端配置与开发 创建一个新的Spring Boot项目,在`pom.xml`文件里加入必要的依赖项以便支持RESTful Web服务以及HTTP客户端功能。对于连接至阿里云的服务,则需引入特定于Aliyun SDK的相关库用于管理认证信息如API Key等敏感数据的安全存储及访问控制机制[^2]。 ```xml <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alicloud-dashscope</artifactId> </dependency> <!-- Other dependencies --> ``` 编写控制器类接收从前端传来的参数并转发给Qwen接口;同时定义好相应的异常处理器以应对可能出现的各种错误情况。这里假设已经获取到了有效的API密钥并且将其设置为环境变量或配置文件中的属性值。 ```java @RestController @RequestMapping("/api/qwen") public class QwenController { @Value("${aliyun.dashscope.apiKey}") private String apiKey; @PostMapping("/query") public ResponseEntity<String> query(@RequestBody Map<String, Object> body) { try { // 构建请求对象... DashScope dashScope = new DashScope(apiKey); Response response = dashScope.textGeneration().call(body); if (response.isSuccessful()) { return ResponseEntity.ok(response.getResult()); } else { throw new RuntimeException("Failed to call Qwen API"); } } catch (Exception e) { log.error(e.getMessage(), e); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); } } } ``` #### 前端设计 构建一个简单的HTML表单让用户输入想要询问的内容并通过AJAX异步提交至上述提到的后端路由地址上。当收到回复之后再动态更新DOM结构显示结果给访客查看。此部分可以根据实际需求选用任意一种流行的JavaScript框架(比如Vue.js、React等)来进行快速迭代开发。 ```html <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"/> <title>Query with Qwen Model</title> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> </head> <body> <div id="app"> <h1>Ask Anything!</h1> <form onsubmit="event.preventDefault(); submitForm()"> <textarea name="prompt" required></textarea><br/> <button type="submit">Submit</button> </form> <pre id="output"></pre> </div> <script> function submitForm() { const form = document.querySelector('form'); axios.post('/api/qwen/query', new FormData(form)) .then(res => {document.getElementById('output').textContent=res.data;}) .catch(err=>console.log(err)); } </script> </body> </html> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

alpha xu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值