0 背景
crewAI中默認使用的gpt4的模型, 在環境中配置OPENAI_API_KEY
即可使用。 但openai的api畢竟是要花錢的, 況且現在對大陸地區做了封禁, 使用起來不是那么方便。 而Ollama可以方便的運行本地的大模型, 既不用花錢, 又可以在本地進行使用。 crewAI中也支持Ollama使用本地模型。
1 使用方式
import os##默認方式,直接使用gpt4, 需要設置OPENAI_API_KEY
# os.environ["OPENAI_API_KEY"] = "Your Key"###通過Ollama使用本地模型的方式1:
os.environ["OPENAI_API_BASE"] = 'http://localhost:11434/v1' ## 這里如果填http://localhost:11434 會報404錯誤
os.environ["OPENAI_MODEL_NAME"] ='llama3:8b' # Adjust based on available model
os.environ["OPENAI_API_KEY"] ='NA'
# ####################################### # ###通過Ollama使用本地模型的方式2:
# from langchain.llms import Ollama
#
# llm = Ollama(
# model="llama3:8b",
# base_url="http://localhost:11434/") ##不給base_url參數也可以。如果給的話這里寫http://localhost:11434/v1 會報錯,提示langchain_community.llms.ollama.OllamaEndpointNotFoundError: Ollama call failed with status code 404. Maybe your model is not found and you should pull the model with `ollama pull llama3:8b`.
# ##############################from crewai import Agent, Task, Crewresearch_agent = Agent(role='Researcher',goal='Find and summarize the latest AI news',backstory="""You're a researcher at a large company.You're responsible for analyzing data and providing insightsto the business.""",verbose=True,# llm=llm ### 注意使用方式2時, 這里需要手動傳入llm
)task = Task(description='Find and summarize the latest AI news',expected_output='A bullet list summary of the top 5 most important AI news',agent=research_agent,tools=[]
)crew = Crew(agents=[research_agent],tasks=[task],verbose=2
)result = crew.kickoff()
print(result)
上面的代碼給出了2種不同的使用Ollama的方式,
第一種方式是與openai api使用方式兼容的一種方式, 直接設置OPENAI_API_BASE
, OPENAI_MODEL_NAME
和OPENAI_API_KEY
即可。OPENAI_API_BASE
填Ollama服務的本地地址和端口。 注意,此時雖然沒用用openai 的api, 但是OPENAI_API_KEY
也是必不可少的, 可以隨便給個值。
第二種方式是顯式的用Ollama定義模型, 然后在agent中手動傳入llm
參數, 注意base_url
的值。