-
Notifications
You must be signed in to change notification settings - Fork 162
Implement tool calling for Ollama and include examples #441
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
Open
kalrasamridhi7
wants to merge
1
commit into
neo4j:main
Choose a base branch
from
kalrasamridhi7:skalra/ollama-tool-calling
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+425
−1
Open
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
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,99 @@ | ||
| """ | ||
| Example showing how to use Ollama tool calls with parameter extraction. | ||
| Both synchronous and asynchronous examples are provided. | ||
| To run this example: | ||
| 1. Make sure you have `ollama serve` running | ||
| 2. Run: python examples/tool_calls/ollama_tool_calls.py | ||
| """ | ||
|
|
||
| import asyncio | ||
| import json | ||
| from typing import Dict, Any | ||
|
|
||
| from neo4j_graphrag.llm import OllamaLLM | ||
| from neo4j_graphrag.llm.types import ToolCallResponse | ||
| from neo4j_graphrag.tool import ( | ||
| Tool, | ||
| ObjectParameter, | ||
| StringParameter, | ||
| IntegerParameter, | ||
| ) | ||
|
|
||
|
|
||
| # Create a custom Tool implementation for person info extraction | ||
| parameters = ObjectParameter( | ||
| description="Parameters for extracting person information", | ||
| properties={ | ||
| "name": StringParameter(description="The person's full name"), | ||
| "age": IntegerParameter(description="The person's age"), | ||
| "occupation": StringParameter(description="The person's occupation"), | ||
| }, | ||
| required_properties=["name"], | ||
| additional_properties=False, | ||
| ) | ||
| person_info_tool = Tool( | ||
| name="extract_person_info", | ||
| description="Extract information about a person from text", | ||
| parameters=parameters, | ||
| execute_func=lambda **kwargs: kwargs, | ||
| ) | ||
|
|
||
| # Create the tool instance | ||
| TOOLS = [person_info_tool] | ||
|
|
||
|
|
||
| def process_tool_calls(response: ToolCallResponse) -> Dict[str, Any]: | ||
| """Process all tool calls in the response and return the extracted parameters.""" | ||
| if not response.tool_calls: | ||
| raise ValueError("No tool calls found in response") | ||
|
|
||
| print(f"\nNumber of tool calls: {len(response.tool_calls)}") | ||
| print(f"Additional content: {response.content or 'None'}") | ||
|
|
||
| results = [] | ||
| for i, tool_call in enumerate(response.tool_calls): | ||
| print(f"\nTool call #{i + 1}: {tool_call.name}") | ||
| print(f"Arguments: {tool_call.arguments}") | ||
| results.append(tool_call.arguments) | ||
|
|
||
| # For backward compatibility, return the first tool call's arguments | ||
| return results[0] if results else {} | ||
|
|
||
|
|
||
| async def main() -> None: | ||
| # Initialize the Ollama LLM | ||
| llm = OllamaLLM( | ||
| # model_name="gpt-4o", | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nitpicking, we can remove the commented line. |
||
| model_name="mistral:latest", | ||
| model_params={"temperature": 0}, | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The proper way to set temperature for OllamaLLM now is: (in order to match the Ollama client parameters) |
||
| ) | ||
|
|
||
| # Example text containing information about a person | ||
| text = "Stella Hane is a 35-year-old software engineer who loves coding." | ||
|
|
||
| print("\n=== Synchronous Tool Call ===") | ||
| # Make a synchronous tool call | ||
| sync_response = llm.invoke_with_tools( | ||
| input=f"Extract information about the person from this text: {text}", | ||
| tools=TOOLS, | ||
| ) | ||
| sync_result = process_tool_calls(sync_response) | ||
| print("\n=== Synchronous Tool Call Result ===") | ||
| print(json.dumps(sync_result, indent=2)) | ||
|
|
||
| print("\n=== Asynchronous Tool Call ===") | ||
| # Make an asynchronous tool call with a different text | ||
| text2 = "Molly Hane, 32, works as a data scientist and enjoys machine learning." | ||
| async_response = await llm.ainvoke_with_tools( | ||
| input=f"Extract information about the person from this text: {text2}", | ||
| tools=TOOLS, | ||
| ) | ||
| async_result = process_tool_calls(async_response) | ||
| print("\n=== Asynchronous Tool Call Result ===") | ||
| print(json.dumps(async_result, indent=2)) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| # Run the async main function | ||
| asyncio.run(main()) | ||
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
Oops, something went wrong.
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.