defget_env_llms_api(): import getpass import os """ Get the environment variables for the LLMS API." """ ifnot os.environ.get("OPENAI_API_KEY"): os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter your OpenAI API key: ") ifnot os.environ.get("OPENAI_API_BASE"): os.environ["OPENAI_API_BASE"] = getpass.getpass("Enter the OpenAI API base URL: ") ifnot os.environ.get("LANGSMITH_TRACING"): os.environ["LANGSMITH_TRACING"] = "true" ifnot os.environ.get("LANGSMITH_API_KEY"): os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your Langsmith API key: ") # ......
defEasyTranslate(): """ EasyTranslate using langchain and openai 轻松翻译,使用 langchain 和 openai """ from langchain_openai import ChatOpenAI # openai for langchain from langchain_core.prompts import PromptTemplate # prompt template for langchain
llm = ChatOpenAI ( model_name="gpt-4o", # gpt-4o for openai temperature=0, # 创作自由度,越高越自由,越低越严谨 max_tokens=4096, # 输出长度 streaming=True# streaming for openai )
for chunk in structured_llm.stream([message]): print(f"源语言:{chunk.src_language}") print(f"目标语言:{chunk.dst_language}") print(f"要翻译的文本:{chunk.text_message}") print(f"翻译后的文本:{chunk.response}")
def caclulate(): from langchain_core.tools import tool from langchain.chat_models import init_chat_model from pydantic import BaseModel, Field llm = init_chat_model(model="gpt-4o", model_provider="openai")
# 加法运算参数描述 class AdditionInput(BaseModel): a: int = Field(..., description="First number") b: int = Field(..., description="Second number")
# 定义加法运算工具,绑定参数,函数描述不可少 # 修饰器tool的第一个参数是工具名称,第二个参数是参数描述 @tool("Addition", args_schema=AdditionInput) def Addition(a: int, b: int) -> int: """Add two numbers""" return a + b
# 乘法运算参数描述 class MultiplyInput(BaseModel): a: int = Field(..., description="First number") b: int = Field(..., description="Second number") # 定义乘法运算工具,绑定参数,函数描述不可少 # 修饰器tool的第一个参数是工具名称,第二个参数是参数描述 @tool("Multiply", args_schema=MultiplyInput) def Multiply(a: int, b: int) -> int: """Multiply two numbers""" return a * b