Overview
OpenAI's function calling feature allows ChatGPT to call external APIs when it needs additional information. By integrating WikiRest, your ChatGPT application can search and retrieve Wikipedia knowledge in real-time.
Function Definition
First, define the WikiRest search function for ChatGPT:
import openai
import requests
import json
# WikiRest function definition for ChatGPT
WIKI_SEARCH_FUNCTION = {
"name": "search_wikipedia",
"description": "Search Wikipedia for information. Use this when you need factual information about a topic, person, place, event, or concept.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The search query to find relevant Wikipedia articles"
},
"limit": {
"type": "integer",
"description": "Number of results to return (1-10)",
"default": 5
}
},
"required": ["query"]
}
}
# For newer OpenAI API format
WIKI_TOOL = {
"type": "function",
"function": WIKI_SEARCH_FUNCTION
} Implementing the Function
Create the function that actually calls the WikiRest API:
WIKIREST_API_KEY = "your_wikirest_api_key"
WIKIREST_URL = "https://api.wikirest.com/v1"
def search_wikipedia(query: str, limit: int = 5) -> str:
"""
Search Wikipedia and return formatted results.
Returns a string that ChatGPT can use in its response.
"""
response = requests.get(
f"{WIKIREST_URL}/search",
params={"q": query, "limit": limit},
headers={"X-API-Key": WIKIREST_API_KEY}
)
if response.status_code != 200:
return f"Error searching Wikipedia: {response.status_code}"
hits = response.json().get("hits", [])
if not hits:
return f"No Wikipedia results found for: {query}"
# Format results for ChatGPT
results = []
for hit in hits:
title = hit.get("title", "Unknown")
text = hit.get("text", "")
section = hit.get("section", "")
url = hit.get("url", "")
result = f"**{title}"
if section:
result += f" - {section}"
result += f"**\n{text}\nSource: {url}"
results.append(result)
return "\n\n---\n\n".join(results) Complete Integration
Here's the complete ChatGPT integration with function calling:
from openai import OpenAI
import json
client = OpenAI(api_key="your_openai_key")
def chat_with_wikipedia(user_message: str, conversation_history: list = None):
"""
Have a conversation with ChatGPT that can search Wikipedia.
"""
if conversation_history is None:
conversation_history = []
messages = [
{
"role": "system",
"content": """You are a helpful assistant with access to Wikipedia.
When you need factual information, use the search_wikipedia function.
Always cite your sources when using Wikipedia information.
If you're unsure about something, search Wikipedia rather than guessing."""
}
] + conversation_history + [
{"role": "user", "content": user_message}
]
# First API call - may trigger function call
response = client.chat.completions.create(
model="gpt-4",
messages=messages,
tools=[WIKI_TOOL],
tool_choice="auto"
)
assistant_message = response.choices[0].message
# Check if ChatGPT wants to call a function
if assistant_message.tool_calls:
# Process each function call
for tool_call in assistant_message.tool_calls:
if tool_call.function.name == "search_wikipedia":
# Parse arguments
args = json.loads(tool_call.function.arguments)
# Call WikiRest
wiki_result = search_wikipedia(
query=args["query"],
limit=args.get("limit", 5)
)
# Add function result to messages
messages.append(assistant_message)
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": wiki_result
})
# Second API call - generate response with Wikipedia data
final_response = client.chat.completions.create(
model="gpt-4",
messages=messages
)
return final_response.choices[0].message.content
else:
# No function call needed
return assistant_message.content
# Example usage
if __name__ == "__main__":
# Simple question
answer = chat_with_wikipedia(
"What is the capital of France and what is it famous for?"
)
print(answer)
# Follow-up conversation
history = [
{"role": "user", "content": "Tell me about quantum computing"},
{"role": "assistant", "content": "...previous response..."}
]
follow_up = chat_with_wikipedia(
"What companies are working on it?",
conversation_history=history
) Streaming Responses
For a better user experience, stream the responses:
def chat_with_wikipedia_stream(user_message: str):
"""Stream ChatGPT responses with Wikipedia search."""
messages = [
{"role": "system", "content": "You have access to Wikipedia search."},
{"role": "user", "content": user_message}
]
# First, check if we need to search
response = client.chat.completions.create(
model="gpt-4",
messages=messages,
tools=[WIKI_TOOL],
tool_choice="auto"
)
assistant_message = response.choices[0].message
if assistant_message.tool_calls:
# Handle function calls, then stream the final response
for tool_call in assistant_message.tool_calls:
if tool_call.function.name == "search_wikipedia":
args = json.loads(tool_call.function.arguments)
wiki_result = search_wikipedia(**args)
messages.append(assistant_message)
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": wiki_result
})
# Stream the final response
stream = client.chat.completions.create(
model="gpt-4",
messages=messages,
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
yield chunk.choices[0].delta.content
else:
# No function call, stream directly
stream = client.chat.completions.create(
model="gpt-4",
messages=messages,
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
yield chunk.choices[0].delta.content
# Usage
for token in chat_with_wikipedia_stream("What caused World War I?"):
print(token, end="", flush=True) Best Practices
Tips for Better Results
- Clear function descriptions - Help ChatGPT understand when to use Wikipedia
- Include source URLs - Always provide Wikipedia links for citations
- Limit results - 5 chunks is usually enough; more can overwhelm the context
- Cache results - Wikipedia content is stable; cache for better performance