-
Notifications
You must be signed in to change notification settings - Fork 77
Add examples of agent using Tavily server with key #25
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| import asyncio | ||
| import logging | ||
| import os | ||
|
|
||
| from agent_framework import ChatAgent, MCPStreamableHTTPTool | ||
| from agent_framework.azure import AzureOpenAIChatClient | ||
| from agent_framework.openai import OpenAIChatClient | ||
| from azure.identity import DefaultAzureCredential | ||
| from dotenv import load_dotenv | ||
| from rich import print | ||
| from rich.logging import RichHandler | ||
|
|
||
| # Configure logging | ||
| logging.basicConfig(level=logging.WARNING, format="%(message)s", datefmt="[%X]", handlers=[RichHandler()]) | ||
| logger = logging.getLogger("agentframework_tavily") | ||
| logger.setLevel(logging.INFO) | ||
|
|
||
| # Load environment variables | ||
| load_dotenv(override=True) | ||
|
|
||
| # Configure chat client based on API_HOST | ||
| API_HOST = os.getenv("API_HOST", "github") | ||
| if API_HOST == "azure": | ||
| client = AzureOpenAIChatClient( | ||
| credential=DefaultAzureCredential(), | ||
| deployment_name=os.environ.get("AZURE_OPENAI_CHAT_DEPLOYMENT"), | ||
| endpoint=os.environ.get("AZURE_OPENAI_ENDPOINT"), | ||
| api_version=os.environ.get("AZURE_OPENAI_VERSION"), | ||
| ) | ||
| elif API_HOST == "github": | ||
| client = OpenAIChatClient( | ||
| base_url="https://models.github.ai/inference", | ||
| api_key=os.environ["GITHUB_TOKEN"], | ||
| model_id=os.getenv("GITHUB_MODEL", "openai/gpt-4o"), | ||
| ) | ||
| elif API_HOST == "ollama": | ||
| client = OpenAIChatClient( | ||
| base_url=os.environ.get("OLLAMA_ENDPOINT", "http://localhost:11434/v1"), | ||
| api_key="none", | ||
| model_id=os.environ.get("OLLAMA_MODEL", "llama3.1:latest"), | ||
| ) | ||
| else: | ||
| client = OpenAIChatClient( | ||
| api_key=os.environ.get("OPENAI_API_KEY"), model_id=os.environ.get("OPENAI_MODEL", "gpt-4o") | ||
| ) | ||
|
|
||
|
|
||
| async def http_mcp_example(): | ||
| """ | ||
| Creates an agent that can search the web using the Tavily MCP server. | ||
| """ | ||
|
|
||
| tavily_key = os.environ["TAVILY_API_KEY"] | ||
| headers = {"Authorization": f"Bearer {tavily_key}"} | ||
| async with ( | ||
| MCPStreamableHTTPTool(name="Tavily MCP", url="https://mcp.tavily.com/mcp/", headers=headers) as mcp_server, | ||
| ChatAgent( | ||
| chat_client=client, | ||
| name="WebSearchAgent", | ||
| instructions="You search the web with Tavily and provide concise answers with links.", | ||
| ) as agent, | ||
| ): | ||
| query = "What's new in Python 3.14? Include relevant links." | ||
| result = await agent.run(query, tools=mcp_server) | ||
| print(result) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| asyncio.run(http_mcp_example()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| """LangChain + Tavily MCP Example | ||
|
|
||
| Creates a simple research agent that uses the Tavily MCP server | ||
| to search the web and answer questions with relevant links. | ||
| """ | ||
|
|
||
| import asyncio | ||
| import logging | ||
| import os | ||
|
|
||
| import azure.identity | ||
| from dotenv import load_dotenv | ||
| from langchain.agents import create_agent | ||
| from langchain_core.messages import HumanMessage | ||
| from langchain_mcp_adapters.client import MultiServerMCPClient | ||
| from langchain_openai import ChatOpenAI | ||
| from pydantic import SecretStr | ||
| from rich.logging import RichHandler | ||
|
|
||
| # Configure logging | ||
| logging.basicConfig(level=logging.WARNING, format="%(message)s", datefmt="[%X]", handlers=[RichHandler()]) | ||
| logger = logging.getLogger("langchainv1_tavily") | ||
| logger.setLevel(logging.INFO) | ||
|
|
||
| # Load environment variables | ||
| load_dotenv(override=True) | ||
|
|
||
| api_host = os.getenv("API_HOST", "github") | ||
|
|
||
| if api_host == "azure": | ||
| token_provider = azure.identity.get_bearer_token_provider( | ||
| azure.identity.DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default" | ||
| ) | ||
| model = ChatOpenAI( | ||
| model=os.environ.get("AZURE_OPENAI_CHAT_DEPLOYMENT"), | ||
| base_url=os.environ["AZURE_OPENAI_ENDPOINT"] + "/openai/v1/", | ||
| api_key=token_provider, | ||
| ) | ||
| elif api_host == "github": | ||
| model = ChatOpenAI( | ||
| model=os.getenv("GITHUB_MODEL", "gpt-4o"), | ||
| base_url="https://models.inference.ai.azure.com", | ||
| api_key=SecretStr(os.environ["GITHUB_TOKEN"]), | ||
| ) | ||
| elif api_host == "ollama": | ||
| model = ChatOpenAI( | ||
| model=os.environ.get("OLLAMA_MODEL", "llama3.1"), | ||
| base_url=os.environ.get("OLLAMA_ENDPOINT", "http://localhost:11434/v1"), | ||
| api_key=SecretStr(os.environ.get("OLLAMA_API_KEY", "none")), | ||
| ) | ||
| else: | ||
| model = ChatOpenAI(model=os.getenv("OPENAI_MODEL", "gpt-4o-mini")) | ||
|
Comment on lines
+34
to
+52
|
||
|
|
||
|
|
||
| async def run_agent() -> None: | ||
| """Run a Tavily-backed research agent via MCP tools.""" | ||
| tavily_key = os.environ["TAVILY_API_KEY"] | ||
| client = MultiServerMCPClient( | ||
| { | ||
| "tavily": { | ||
| "url": "https://mcp.tavily.com/mcp/", | ||
| "transport": "streamable_http", | ||
| "headers": {"Authorization": f"Bearer {tavily_key}"}, | ||
| } | ||
| } | ||
| ) | ||
|
|
||
| # Fetch available tools and create the agent | ||
| tools = await client.get_tools() | ||
| agent = create_agent(model, tools, prompt="You search the web and include relevant links in answers.") | ||
|
|
||
| query = "What's new in Python 3.14? Include relevant links." | ||
| response = await agent.ainvoke({"messages": [HumanMessage(content=query)]}) | ||
|
|
||
| final_response = response["messages"][-1].content | ||
| print(final_response) | ||
|
|
||
|
|
||
| def main() -> None: | ||
| asyncio.run(run_agent()) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The variable name
api_hostshould follow Python naming conventions for constants that are module-level configuration values. Since this value is determined at module load time and used to configure the model, it should be namedAPI_HOST(all uppercase) to be consistent with other similar files in the codebase (e.g., langchainv1_http.py line 27, agentframework_tavily.py line 22).