调用openrouter的免费API模型

方式1

使用langchain

python 复制代码
from langchain.agents import create_agent
# 读取 .env 里的 OPENROUTER_API_KEY,避免把密钥写进代码
from dotenv import load_dotenv

# override=True 让 .env 的值覆盖系统环境变量里可能存在的同名旧值
load_dotenv(override=True)

def get_weather(city: str) -> str:
    """获取指定城市的天气信息"""
    return f"{city}今天大部分晴朗!"

agent = create_agent(
    model="openrouter:openrouter/free",
    tools=[get_weather],
    system_prompt="你是一个简洁的天气助手,查询天气时调用 get_weather 工具,不要编造结果",
)

result = agent.invoke(
    {"messages": [{"role": "user", "content": "北京的天气怎么样"}]}
)
print(result["messages"][-1].content)

方式2

使用openai

python 复制代码
from openai import OpenAI
import os
# 读取 .env 里的 OPENROUTER_API_KEY
from dotenv import load_dotenv

# override=True 让 .env 的值覆盖系统环境变量里可能存在的同名旧值
load_dotenv(override=True)

client = OpenAI(
  base_url=os.getenv("OPENROUTER_API_BASE"),
  api_key=os.getenv("OPENROUTER_API_KEY"),
)

# First API call with reasoning
response = client.chat.completions.create(
  model="openrouter/free",
  messages=[
          {
            "role": "user",
            "content": "你是谁?"
          }
        ],
  extra_body={"reasoning": {"enabled": True}}
)

# Extract the assistant message with reasoning_details
response = response.choices[0].message.content

print(response)

环境变量.env

powershell 复制代码
OPENROUTER_API_KEY=sk-or-v1-123
OPENROUTER_API_BASE=https://openrouter.ai/api/v1
相关推荐
步行cgn2 小时前
Spring MVC 拦截器 Interceptor 详解:从执行流程到实战应用
java·spring·mvc
文丑颜不良啊2 小时前
LeetCode1381~1400题目解析
java·leetcode
赛博守夜人2 小时前
AI安全攻防与治理之十四:AI 安全测试不能脱离传统安全,Web、API、移动端与模型攻击面的组合拳
前端·人工智能·安全
开开心心_Every2 小时前
快速隐藏程序工具自定义快捷键一键切换
java·开发语言·前端·spring·智能手机·word·intellij-idea
networknomad3 小时前
OpenReplay:自己搭的会话回放工具,给前端排错用的
前端·其他
萧瑟余晖3 小时前
Spring Batch核心模型与快速上手详解
java·spring·batch
缓慢更新3 小时前
AI 辅助生成单测:从接口定义到用例的流水线
java·服务器·前端·网络·数据库·人工智能
陈随易4 小时前
AI 运维服务器,安全又可靠的方法
前端·后端·程序员
风骏时光牛马5 小时前
AI稳定性治理体系构建与疑难问题深度分析
前端