为什么选择 API 调用

发布时间:2026/7/22 5:37:33
为什么选择 API 调用 无需本地部署 GPU只需一行请求即可调用大模型。灵活支持多种模型qwen-turbo / qwen-plus / qwen-max可按需切换。兼容DashScope 提供了 OpenAI API 兼容模式能直接复用 LangChain、OpenAI SDK 等生态。二、准备工作配置 API Key参考阿里云百炼的官方教程注册账号后获取 API Key国内用户需实名认证获取并使用 API Key⚠️ 安全提示为了安全和复用性建议根据官方教程通过系统环境变量或 .env 文件配置 API Key避免在代码中明文写入密钥。若项目公开请务必在提交前移除或打码。本文为帮助读者迅速复现采取了在代码中直接放入 API Key 的方式并对其作打码处理。三、大模型调用最小可运行示例from langchain_openai import ChatOpenAIimport osos.environ[“DASHSCOPE_API_KEY”] ‘sk-xx’ # 替换为你的 API Keychat ChatOpenAI(model“qwen-plus”, # 可选 qwen-turbo / qwen-maxapi_keyos.environ[“DASHSCOPE_API_KEY”],base_url“https://dashscope.aliyuncs.com/compatible-mode/v1”,#若为国际版则改为 https://dashscope-intl.aliyuncs.com/compatible-mode/v1temperature0)resp chat.invoke(“温度是什么”)print(resp.content)如果这个代码可以让模型成功给出答案那么则说明调用成功了。输出答案示例温度是表示物体冷热程度的物理量从微观角度来看它反映了物体内部分子或原子热运动的剧烈程度。温度越高物质内部粒子如分子、原子的无规则运动就越剧烈温度越低粒子的运动就越缓慢。四、结合 RAG 的调用示例代码示例在 RAG 场景中API 调用通常和我们上次生成的那种向量库结合。示例from langchain_community.embeddings import ModelScopeEmbeddingsfrom langchain_community.vectorstores import FAISSfrom langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate, MessagesPlaceholderfrom langchain_core.messages import HumanMessagefrom langchain_openai import ChatOpenAIfrom operator import itemgetterimport os1. 加载 embedding 模型和向量库try:# 加载embedding模型 用于将query向量化embeddings ModelScopeEmbeddings(model_id‘iic/nlp_corom_sentence-embedding_chinese-base’)#加载 FAISS 向量库 用于知识召回vector_db FAISS.load_local(‘faiss_index/LLM’, embeddings, allow_dangerous_deserializationTrue) # 替换为你的向量库路径# allow_dangerous_deserializationTrue 仅在本地加载向量库时使用请勿在不可信环境下启用添加异常处理except Exception as e:print(f模型或向量库加载失败: {str(e)})exit(1)2. 创建检索器 Retriever检索器将 query 转为向量并返回最相似文档片段retriever vector_db.as_retriever(search_kwargs{“k”: 5}) # 设置返回的相关相似对最高的模块数量为 53. 配置 API Key初始化 Chat 模型此处使用阿里云达观智能 DashScope 平台的模型接口os.environ[“DASHSCOPE_API_KEY”] ‘sk-xx’ # 替换为你的 API Keychat ChatOpenAI(model“qwen-plus”, # 按照需要更换模型名称api_keyos.environ[“DASHSCOPE_API_KEY”],base_url“https://dashscope.aliyuncs.com/compatible-mode/v1”,#若为国际版则改为 https://dashscope-intl.aliyuncs.com/compatible-mode/v1temperature0)4. Prompt模板system_prompt SystemMessagePromptTemplate.from_template(‘你是一个有帮助的助手。’) # 系统提示user_prompt HumanMessagePromptTemplate.from_template(‘’’只基于以下内容回答问题不要使用你在训练中学到的知识:{context}问题: {query}‘’) # 用户提示full_chat_prompt ChatPromptTemplate.from_messages([system_prompt, MessagesPlaceholder(variable_name“chat_history”), user_prompt]) # 构建完整的聊天提示模板5. 构建对话链 Chat chainchat_chain {“context”: itemgetter(“query”) | retriever,“query”: itemgetter(“query”),“chat_history”: itemgetter(“chat_history”),} | full_chat_prompt | chat6. 开始对话chat_history [] # 初始化对话历史while True:query input(“请输入问题输入 exit 退出”)if query.lower() “exit”:breakresponse chat_chain.invoke({‘query’: query, ‘chat_history’: chat_history}) # 获取模型响应chat_history.extend((HumanMessage(contentquery), response)) # 更新对话历史print(“AI:”, response.content)chat_history chat_history[-20:] # 保留最近 20 条消息2. 代码中需要手动修改的部分向量库地址调用模型名称自己的 API Keybase url 地址3. 预期输出结果示例