An Implementation of IWE’s Context Bridge as an AI-Powered Knowledge Graph with Agentic RAG, OpenAI Function Calling, and Graph Traversal

by CryptoExpert
Customgpt


print(“โ”€” * 72)
print(” 5 ยท Agentic RAG โ€” AI Navigates Your Knowledge Graph”)
print(“โ”€” * 72)

AGENT_TOOLS = [
{
“type”: “function”,
“function”: {
“name”: “iwe_find”,
“description”: “Search the knowledge graph for documents matching a query. Returns a list of document keys.”,
“parameters”: {
“type”: “object”,
“properties”: {
“query”: {“type”: “string”, “description”: “Search query”},
“roots_only”: {“type”: “boolean”, “description”: “Only return root/MOC documents”, “default”: False},
},
“required”: [“query”],
},
},
},
{
“type”: “function”,
“function”: {
“name”: “iwe_retrieve”,
“description”: “Retrieve a document’s content with linked context. Use depth>0 to follow outgoing links, context>0 to include parent documents.”,
“parameters”: {
“type”: “object”,
“properties”: {
“key”: {“type”: “string”, “description”: “Document key to retrieve”},
“depth”: {“type”: “integer”, “description”: “How many levels of child links to follow (0-2)”, “default”: 1},
“context”: {“type”: “integer”, “description”: “How many levels of parent context (0-1)”, “default”: 0},
},
“required”: [“key”],
},
},
},
{
“type”: “function”,
“function”: {
“name”: “iwe_tree”,
“description”: “Show the document hierarchy starting from a given key.”,
“parameters”: {
“type”: “object”,
“properties”: {
“key”: {“type”: “string”, “description”: “Root document key”},
},
“required”: [“key”],
},
},
},
{
“type”: “function”,
“function”: {
“name”: “iwe_stats”,
“description”: “Get statistics about the entire knowledge base.”,
“parameters”: {“type”: “object”, “properties”: {}},
},
},
]

def execute_tool(name: str, args: dict) -> str:
if name == “iwe_find”:
results = kg.find(args[“query”], roots_only=args.get(“roots_only”, False))
return json.dumps({“results”: results})
elif name == “iwe_retrieve”:
content = kg.retrieve(
args[“key”],
depth=args.get(“depth”, 1),
context=args.get(“context”, 0),
)
return content[:3000]
elif name == “iwe_tree”:
return kg.tree(args[“key”])
elif name == “iwe_stats”:
return json.dumps(kg.stats(), indent=2)
return “Unknown tool”

def run_agent(question: str, max_turns: int = 6, model: str = “gpt-4o-mini”) -> str:
system_prompt = textwrap.dedent(“””\
You are an AI assistant with access to a personal knowledge graph (IWE).
Use the provided tools to navigate the graph and answer questions.

livechat

Workflow:
1. Use iwe_find to discover relevant documents
2. Use iwe_retrieve to read content (set depth=1 to follow links)
3. Follow relationships to build comprehensive understanding
4. Synthesize information from multiple documents

Be specific and cite which documents you found information in.
If you cannot find enough information, say so clearly.
“””)

messages = [
{“role”: “system”, “content”: system_prompt},
{“role”: “user”, “content”: question},
]

for turn in range(max_turns):
response = client.chat.completions.create(
model=model, messages=messages, tools=AGENT_TOOLS,
tool_choice=”auto”,
)
msg = response.choices[0].message

if msg.tool_calls:
messages.append(msg)
for tc in msg.tool_calls:
fn_name = tc.function.name
fn_args = json.loads(tc.function.arguments)
print(f” ๐Ÿ”ง Agent calls: {fn_name}({fn_args})”)
result = execute_tool(fn_name, fn_args)
messages.append({
“role”: “tool”,
“tool_call_id”: tc.id,
“content”: result,
})
else:
return msg.content

return “Agent reached maximum turns without completing.”

questions = [
“How does our authentication system work, and what database tables does it depend on?”,
“What is our deployment pipeline, and what are the performance SLO targets?”,
“Give me a high-level overview of the entire project architecture.”,
]

for i, q in enumerate(questions, 1):
print(f”\n{‘โ•’ * 72}”)
print(f” Question {i}: {q}”)
print(f”{‘โ•’ * 72}\n”)
answer = run_agent(q)
print(f”\n๐Ÿ’ก Agent Answer:\n{answer}\n”)

print(“\nโœ… Section 5 complete โ€” Agentic RAG demonstrated.\n”)



Source link

aistudios

You may also like